text stringlengths 0 1.05M | meta dict |
|---|---|
from forms import Form
from django.core.exceptions import ValidationError
from django.utils.encoding import StrAndUnicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput
from util import ErrorList
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
MAX_NUM_FORM_COUNT = 'MAX_NUM_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.data or self.files:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num
})
return form
management_form = property(_management_form)
def total_form_count(self):
"""Returns the total number of forms in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
initial_forms = self.initial_form_count()
total_forms = initial_forms + self.extra
# Allow all existing related objects/inlines to be displayed,
# but don't allow extra beyond max_num.
if initial_forms > self.max_num >= 0:
total_forms = initial_forms
elif total_forms > self.max_num >= 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Returns the number of forms that are required in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the inital data if it's there, 0 otherwise.
initial_forms = self.initial and len(self.initial) or 0
if initial_forms > self.max_num >= 0:
initial_forms = self.max_num
return initial_forms
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
def _get_empty_form(self, **kwargs):
defaults = {
'auto_id': self.auto_id,
'prefix': self.add_prefix('__prefix__'),
'empty_permitted': True,
}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, None)
return form
empty_form = property(_get_empty_form)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and self._should_delete_form(form):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blamk.
def compare_ordering_values(x, y):
if x[1] is None:
return 1
if y[1] is None:
return -1
return x[1] - y[1]
self._ordering.sort(compare_ordering_values)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
#@classmethod
def get_default_prefix(cls):
return 'form'
get_default_prefix = classmethod(get_default_prefix)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def _should_delete_form(self, form):
# The way we lookup the value of the deletion field here takes
# more code than we'd like, but the form's cleaned_data will
# not exist if the form is invalid.
field = form.fields[DELETION_FIELD_NAME]
raw_value = form._raw_value(DELETION_FIELD_NAME)
should_delete = field.clean(raw_value)
return should_delete
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
err = self.errors
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index is not None and index < self.initial_form_count():
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms and self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "ychen820/microblog",
"path": "y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/forms/formsets.py",
"copies": "44",
"size": "14303",
"license": "bsd-3-clause",
"hash": 6637038467698742000,
"line_mean": 40.338150289,
"line_max": 115,
"alpha_frac": 0.5981262672,
"autogenerated": false,
"ratio": 4.162689173457509,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0011524541646275232,
"num_lines": 346
} |
from forms import Form
from django.utils.encoding import StrAndUnicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput
from util import ErrorList, ErrorDict, ValidationError
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.data or self.files:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count()
})
return form
management_form = property(_management_form)
def total_form_count(self):
"""Returns the total number of forms in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
total_forms = self.initial_form_count() + self.extra
if total_forms > self.max_num > 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Returns the number of forms that are required in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the inital data if it's there, 0 otherwise.
initial_forms = self.initial and len(self.initial) or 0
if initial_forms > self.max_num > 0:
initial_forms = self.max_num
return initial_forms
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and self._should_delete_form(form):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blamk.
def compare_ordering_values(x, y):
if x[1] is None:
return 1
if y[1] is None:
return -1
return x[1] - y[1]
self._ordering.sort(compare_ordering_values)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
#@classmethod
def get_default_prefix(cls):
return 'form'
get_default_prefix = classmethod(get_default_prefix)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def _should_delete_form(self, form):
# The way we lookup the value of the deletion field here takes
# more code than we'd like, but the form's cleaned_data will
# not exist if the form is invalid.
field = form.fields[DELETION_FIELD_NAME]
raw_value = form._raw_value(DELETION_FIELD_NAME)
should_delete = field.clean(raw_value)
return should_delete
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index < self.initial_form_count():
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms and self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=0):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "sanjuro/RCJK",
"path": "vendor/django/forms/formsets.py",
"copies": "2",
"size": "13292",
"license": "apache-2.0",
"hash": 6073018351380563000,
"line_mean": 40.4080996885,
"line_max": 115,
"alpha_frac": 0.5997592537,
"autogenerated": false,
"ratio": 4.172002510985561,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0012097584868986178,
"num_lines": 321
} |
from forms import Form
from django.utils.encoding import StrAndUnicode
from django.utils.safestring import mark_safe
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput, TextInput
from util import ErrorList, ValidationError
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
MAX_FORM_COUNT = 'MAX_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[MAX_FORM_COUNT] = IntegerField(widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or 'form'
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# initialization is different depending on whether we recieved data, initial, or nothing
if data or files:
self.management_form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix)
if self.management_form.is_valid():
self._total_form_count = self.management_form.cleaned_data[TOTAL_FORM_COUNT]
self._initial_form_count = self.management_form.cleaned_data[INITIAL_FORM_COUNT]
self._max_form_count = self.management_form.cleaned_data[MAX_FORM_COUNT]
else:
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
if initial:
self._initial_form_count = len(initial)
if self._initial_form_count > self._max_form_count and self._max_form_count > 0:
self._initial_form_count = self._max_form_count
self._total_form_count = self._initial_form_count + self.extra
else:
self._initial_form_count = 0
self._total_form_count = self.extra
if self._total_form_count > self._max_form_count and self._max_form_count > 0:
self._total_form_count = self._max_form_count
initial = {TOTAL_FORM_COUNT: self._total_form_count,
INITIAL_FORM_COUNT: self._initial_form_count,
MAX_FORM_COUNT: self._max_form_count}
self.management_form = ManagementForm(initial=initial, auto_id=self.auto_id, prefix=self.prefix)
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self._total_form_count):
self.forms.append(self._construct_form(i))
def _construct_form(self, i):
"""
Instantiates and returns the i-th form instance in a formset.
"""
kwargs = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
kwargs['data'] = self.data
kwargs['files'] = self.files
if self.initial:
try:
kwargs['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self._initial_form_count:
kwargs['empty_permitted'] = True
form = self.form(**kwargs)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the intial forms in this formset."""
return self.forms[:self._initial_form_count]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self._initial_form_count:]
extra_forms = property(_get_extra_forms)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError is deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self._total_form_count):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self._initial_form_count and not form.has_changed():
continue
if form.cleaned_data[DELETION_FIELD_NAME]:
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError is deletion is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self._total_form_count):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self._initial_form_count and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]:
continue
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blamk.
def compare_ordering_values(x, y):
if x[1] is None:
return 1
if y[1] is None:
return -1
return x[1] - y[1]
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
self._ordering.sort(compare_ordering_values)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
for errors in self.errors:
if bool(errors):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self._total_form_count):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = e.messages
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index < self._initial_form_count:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label='Delete', required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=0):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'_max_form_count': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "diofeher/django-nfa",
"path": "django/newforms/formsets.py",
"copies": "1",
"size": "12445",
"license": "bsd-3-clause",
"hash": -2102450013114724400,
"line_mean": 41.7663230241,
"line_max": 111,
"alpha_frac": 0.5971876256,
"autogenerated": false,
"ratio": 4.162207357859532,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0024612553748488172,
"num_lines": 291
} |
from forms import Form
from django.utils.encoding import StrAndUnicode
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput, TextInput
from util import ErrorList, ValidationError
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or 'form'
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# initialization is different depending on whether we recieved data, initial, or nothing
if data or files:
self.management_form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix)
if self.management_form.is_valid():
self._total_form_count = self.management_form.cleaned_data[TOTAL_FORM_COUNT]
self._initial_form_count = self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
if initial:
self._initial_form_count = len(initial)
self._total_form_count = self._initial_form_count + self.extra
else:
self._initial_form_count = 0
self._total_form_count = self.extra
initial = {TOTAL_FORM_COUNT: self._total_form_count, INITIAL_FORM_COUNT: self._initial_form_count}
self.management_form = ManagementForm(initial=initial, auto_id=self.auto_id, prefix=self.prefix)
# instantiate all the forms and put them in self.forms
self.forms = []
for i in range(self._total_form_count):
self.forms.append(self._construct_form(i))
def __unicode__(self):
return self.as_table()
def _construct_form(self, i):
"""
Instantiates and returns the i-th form instance in a formset.
"""
kwargs = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
kwargs['data'] = self.data
kwargs['files'] = self.files
if self.initial:
try:
kwargs['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self._initial_form_count:
kwargs['empty_permitted'] = True
form = self.form(**kwargs)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the intial forms in this formset."""
return self.forms[:self._initial_form_count]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self._initial_form_count:]
extra_forms = property(_get_extra_forms)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError is deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self._total_form_count):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self._initial_form_count and not form.has_changed():
continue
if form.cleaned_data[DELETION_FIELD_NAME]:
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError is deletion is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self._total_form_count):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self._initial_form_count and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]:
continue
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blamk.
def compare_ordering_values(x, y):
if x[1] is None:
return 1
if y[1] is None:
return -1
return x[1] - y[1]
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
self._ordering.sort(compare_ordering_values)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
for errors in self.errors:
if bool(errors):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self._total_form_count):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = e.messages
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index < self._initial_form_count:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label='Order', required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label='Delete', required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return u'\n'.join([unicode(self.management_form), forms])
# XXX: This API *will* change. Use at your own risk.
def _formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra, 'can_order': can_order, 'can_delete': can_delete}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "rawwell/django",
"path": "django/newforms/formsets.py",
"copies": "2",
"size": "11633",
"license": "bsd-3-clause",
"hash": 7674110603090929000,
"line_mean": 41.3018181818,
"line_max": 111,
"alpha_frac": 0.6002750795,
"autogenerated": false,
"ratio": 4.1725251076040175,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5772800187104018,
"avg_score": null,
"num_lines": null
} |
from .forms import Form
def filter_form_factory(model):
fields = []
for field in model._meta.fields:
formfield = field.formfield()
if formfield:
formfield.required = False
field_name = field.column if field.rel else field.name
fields.append((field_name, formfield))
fields = dict(fields)
return type(Form)(model.__name__ + str('FilterForm'), (Form,), fields)
class QuerysetFilter(object):
def __init__(self, queryset, form_class=None):
self.form_class = form_class or filter_form_factory(queryset.model)
self.queryset = queryset
def narrow(self, data):
form = self.form_class(data)
if form.is_valid():
data = form.cleaned_data
really_cleaned_data = {}
for key, value in data.items():
if value is not None and value is not '' and value is not u'':
really_cleaned_data[key] = value
return self.queryset.filter(**really_cleaned_data)
return self.queryset
| {
"repo_name": "marcinn/restosaur",
"path": "restosaur/filters.py",
"copies": "1",
"size": "1060",
"license": "bsd-2-clause",
"hash": 1748043373152784000,
"line_mean": 31.1212121212,
"line_max": 78,
"alpha_frac": 0.5971698113,
"autogenerated": false,
"ratio": 4.1568627450980395,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 33
} |
from forms import Form
from django.core.exceptions import ValidationError
from django.utils.encoding import StrAndUnicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput
from util import ErrorList
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
MAX_NUM_FORM_COUNT = 'MAX_NUM_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.data or self.files:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count(),
MAX_NUM_FORM_COUNT: self.max_num
})
return form
management_form = property(_management_form)
def total_form_count(self):
"""Returns the total number of forms in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
initial_forms = self.initial_form_count()
total_forms = initial_forms + self.extra
# Allow all existing related objects/inlines to be displayed,
# but don't allow extra beyond max_num.
if initial_forms > self.max_num >= 0:
total_forms = initial_forms
elif total_forms > self.max_num >= 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Returns the number of forms that are required in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the inital data if it's there, 0 otherwise.
initial_forms = self.initial and len(self.initial) or 0
if initial_forms > self.max_num >= 0:
initial_forms = self.max_num
return initial_forms
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
def _get_empty_form(self, **kwargs):
defaults = {
'auto_id': self.auto_id,
'prefix': self.add_prefix('__prefix__'),
'empty_permitted': True,
}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, None)
return form
empty_form = property(_get_empty_form)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if self._should_delete_form(form):
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and self._should_delete_form(form):
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blank.
def compare_ordering_key(k):
if k[1] is None:
return (1, 0) # +infinity, larger than any number
return (0, k[1])
self._ordering.sort(key=compare_ordering_key)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
#@classmethod
def get_default_prefix(cls):
return 'form'
get_default_prefix = classmethod(get_default_prefix)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def _should_delete_form(self, form):
# The way we lookup the value of the deletion field here takes
# more code than we'd like, but the form's cleaned_data will
# not exist if the form is invalid.
field = form.fields[DELETION_FIELD_NAME]
raw_value = form._raw_value(DELETION_FIELD_NAME)
should_delete = field.clean(raw_value)
return should_delete
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
if self._should_delete_form(form):
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = self.error_class(e.messages)
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index is not None and index < self.initial_form_count():
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms and self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def as_p(self):
"Returns this formset rendered as HTML <p>s."
forms = u' '.join([form.as_p() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def as_ul(self):
"Returns this formset rendered as HTML <li>s."
forms = u' '.join([form.as_ul() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=None):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "hunch/hunch-sample-app",
"path": "django/forms/formsets.py",
"copies": "9",
"size": "15036",
"license": "mit",
"hash": 4222372203702600000,
"line_mean": 40.5949008499,
"line_max": 115,
"alpha_frac": 0.5858606012,
"autogenerated": false,
"ratio": 4.216489063376332,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9302349664576332,
"avg_score": null,
"num_lines": null
} |
from forms import Form
from django.utils.encoding import StrAndUnicode
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from fields import IntegerField, BooleanField
from widgets import Media, HiddenInput
from util import ErrorList, ErrorDict, ValidationError
__all__ = ('BaseFormSet', 'all_valid')
# special field names
TOTAL_FORM_COUNT = 'TOTAL_FORMS'
INITIAL_FORM_COUNT = 'INITIAL_FORMS'
ORDERING_FIELD_NAME = 'ORDER'
DELETION_FIELD_NAME = 'DELETE'
class ManagementForm(Form):
"""
``ManagementForm`` is used to keep track of how many form instances
are displayed on the page. If adding new forms via javascript, you should
increment the count field of this form as well.
"""
def __init__(self, *args, **kwargs):
self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
super(ManagementForm, self).__init__(*args, **kwargs)
class BaseFormSet(StrAndUnicode):
"""
A collection of instances of the same Form class.
"""
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList):
self.is_bound = data is not None or files is not None
self.prefix = prefix or self.get_default_prefix()
self.auto_id = auto_id
self.data = data
self.files = files
self.initial = initial
self.error_class = error_class
self._errors = None
self._non_form_errors = None
# construct the forms in the formset
self._construct_forms()
def __unicode__(self):
return self.as_table()
def _management_form(self):
"""Returns the ManagementForm instance for this FormSet."""
if self.data or self.files:
form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
if not form.is_valid():
raise ValidationError('ManagementForm data is missing or has been tampered with')
else:
form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
TOTAL_FORM_COUNT: self.total_form_count(),
INITIAL_FORM_COUNT: self.initial_form_count()
})
return form
management_form = property(_management_form)
def total_form_count(self):
"""Returns the total number of forms in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
else:
total_forms = self.initial_form_count() + self.extra
if total_forms > self.max_num > 0:
total_forms = self.max_num
return total_forms
def initial_form_count(self):
"""Returns the number of forms that are required in this FormSet."""
if self.data or self.files:
return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
else:
# Use the length of the inital data if it's there, 0 otherwise.
initial_forms = self.initial and len(self.initial) or 0
if initial_forms > self.max_num > 0:
initial_forms = self.max_num
return initial_forms
def _construct_forms(self):
# instantiate all the forms and put them in self.forms
self.forms = []
for i in xrange(self.total_form_count()):
self.forms.append(self._construct_form(i))
def _construct_form(self, i, **kwargs):
"""
Instantiates and returns the i-th form instance in a formset.
"""
defaults = {'auto_id': self.auto_id, 'prefix': self.add_prefix(i)}
if self.data or self.files:
defaults['data'] = self.data
defaults['files'] = self.files
if self.initial:
try:
defaults['initial'] = self.initial[i]
except IndexError:
pass
# Allow extra forms to be empty.
if i >= self.initial_form_count():
defaults['empty_permitted'] = True
defaults.update(kwargs)
form = self.form(**defaults)
self.add_fields(form, i)
return form
def _get_initial_forms(self):
"""Return a list of all the initial forms in this formset."""
return self.forms[:self.initial_form_count()]
initial_forms = property(_get_initial_forms)
def _get_extra_forms(self):
"""Return a list of all the extra forms in this formset."""
return self.forms[self.initial_form_count():]
extra_forms = property(_get_extra_forms)
# Maybe this should just go away?
def _get_cleaned_data(self):
"""
Returns a list of form.cleaned_data dicts for every form in self.forms.
"""
if not self.is_valid():
raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
return [form.cleaned_data for form in self.forms]
cleaned_data = property(_get_cleaned_data)
def _get_deleted_forms(self):
"""
Returns a list of forms that have been marked for deletion. Raises an
AttributeError if deletion is not allowed.
"""
if not self.is_valid() or not self.can_delete:
raise AttributeError("'%s' object has no attribute 'deleted_forms'" % self.__class__.__name__)
# construct _deleted_form_indexes which is just a list of form indexes
# that have had their deletion widget set to True
if not hasattr(self, '_deleted_form_indexes'):
self._deleted_form_indexes = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
if form.cleaned_data[DELETION_FIELD_NAME]:
self._deleted_form_indexes.append(i)
return [self.forms[i] for i in self._deleted_form_indexes]
deleted_forms = property(_get_deleted_forms)
def _get_ordered_forms(self):
"""
Returns a list of form in the order specified by the incoming data.
Raises an AttributeError if ordering is not allowed.
"""
if not self.is_valid() or not self.can_order:
raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
# Construct _ordering, which is a list of (form_index, order_field_value)
# tuples. After constructing this list, we'll sort it by order_field_value
# so we have a way to get to the form indexes in the order specified
# by the form data.
if not hasattr(self, '_ordering'):
self._ordering = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
# if this is an extra form and hasn't changed, don't consider it
if i >= self.initial_form_count() and not form.has_changed():
continue
# don't add data marked for deletion to self.ordered_data
if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]:
continue
self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
# After we're done populating self._ordering, sort it.
# A sort function to order things numerically ascending, but
# None should be sorted below anything else. Allowing None as
# a comparison value makes it so we can leave ordering fields
# blamk.
def compare_ordering_values(x, y):
if x[1] is None:
return 1
if y[1] is None:
return -1
return x[1] - y[1]
self._ordering.sort(compare_ordering_values)
# Return a list of form.cleaned_data dicts in the order spcified by
# the form data.
return [self.forms[i[0]] for i in self._ordering]
ordered_forms = property(_get_ordered_forms)
#@classmethod
def get_default_prefix(cls):
return 'form'
get_default_prefix = classmethod(get_default_prefix)
def non_form_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
form -- i.e., from formset.clean(). Returns an empty ErrorList if there
are none.
"""
if self._non_form_errors is not None:
return self._non_form_errors
return self.error_class()
def _get_errors(self):
"""
Returns a list of form.errors for every form in self.forms.
"""
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def is_valid(self):
"""
Returns True if form.errors is empty for every form in self.forms.
"""
if not self.is_bound:
return False
# We loop over every form.errors here rather than short circuiting on the
# first failure to make sure validation gets triggered for every form.
forms_valid = True
for i in range(0, self.total_form_count()):
form = self.forms[i]
if self.can_delete:
# The way we lookup the value of the deletion field here takes
# more code than we'd like, but the form's cleaned_data will
# not exist if the form is invalid.
field = form.fields[DELETION_FIELD_NAME]
raw_value = form._raw_value(DELETION_FIELD_NAME)
should_delete = field.clean(raw_value)
if should_delete:
# This form is going to be deleted so any of its errors
# should not cause the entire formset to be invalid.
continue
if bool(self.errors[i]):
forms_valid = False
return forms_valid and not bool(self.non_form_errors())
def full_clean(self):
"""
Cleans all of self.data and populates self._errors.
"""
self._errors = []
if not self.is_bound: # Stop further processing.
return
for i in range(0, self.total_form_count()):
form = self.forms[i]
self._errors.append(form.errors)
# Give self.clean() a chance to do cross-form validation.
try:
self.clean()
except ValidationError, e:
self._non_form_errors = e.messages
def clean(self):
"""
Hook for doing any extra formset-wide cleaning after Form.clean() has
been called on every form. Any ValidationError raised by this method
will not be associated with a particular form; it will be accesible
via formset.non_form_errors()
"""
pass
def add_fields(self, form, index):
"""A hook for adding extra fields on to each form instance."""
if self.can_order:
# Only pre-fill the ordering field for initial forms.
if index < self.initial_form_count():
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), initial=index+1, required=False)
else:
form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_(u'Order'), required=False)
if self.can_delete:
form.fields[DELETION_FIELD_NAME] = BooleanField(label=_(u'Delete'), required=False)
def add_prefix(self, index):
return '%s-%s' % (self.prefix, index)
def is_multipart(self):
"""
Returns True if the formset needs to be multipart-encrypted, i.e. it
has FileInput. Otherwise, False.
"""
return self.forms and self.forms[0].is_multipart()
def _get_media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
else:
return Media()
media = property(_get_media)
def as_table(self):
"Returns this formset rendered as HTML <tr>s -- excluding the <table></table>."
# XXX: there is no semantic division between forms here, there
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = u' '.join([form.as_table() for form in self.forms])
return mark_safe(u'\n'.join([unicode(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
can_delete=False, max_num=0):
"""Return a FormSet for the given form class."""
attrs = {'form': form, 'extra': extra,
'can_order': can_order, 'can_delete': can_delete,
'max_num': max_num}
return type(form.__name__ + 'FormSet', (formset,), attrs)
def all_valid(formsets):
"""Returns true if every formset in formsets is valid."""
valid = True
for formset in formsets:
if not formset.is_valid():
valid = False
return valid
| {
"repo_name": "greggian/TapdIn",
"path": "django/forms/formsets.py",
"copies": "1",
"size": "13568",
"license": "apache-2.0",
"hash": -4769442607603611000,
"line_mean": 40.6666666667,
"line_max": 115,
"alpha_frac": 0.5835053066,
"autogenerated": false,
"ratio": 4.278776411226742,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.001191657667343722,
"num_lines": 318
} |
from forms import LoginForm, RegistrationForm
from django.views import generic
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
# Create your views here.
class LoginView(generic.FormView):
form_class = LoginForm
template_name = 'accounts/login.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(self.request, user)
return super(LoginView, self).form_valid(form)
else:
return self.form_invalid(form)
class RegisterView(generic.CreateView):
form_class = RegistrationForm
model = User
template_name = 'accounts/register.html'
success_url = reverse_lazy('index')
def form_valid(self, form):
# set these so that we can login the user later? This probably isn't
# the best way to do this?
self.username = form.cleaned_data['username']
self.password = form.cleaned_data['password1']
return super(RegisterView, self).form_valid(form)
def get_success_url(self):
"""
This gets called after the object is created, so we should be safe to
login a user now
"""
user = authenticate(username=self.username, password=self.password)
login(self.request, user)
return super(RegisterView, self).get_success_url()
class LogoutView(generic.RedirectView):
url = reverse_lazy('index')
def get(self, request, *args, **kwargs):
logout(request)
return super(LogoutView, self).get(request, *args, **kwargs)
| {
"repo_name": "ncphillips/django_rpg",
"path": "accounts/views.py",
"copies": "1",
"size": "1873",
"license": "mit",
"hash": 5182021298917856000,
"line_mean": 32.4464285714,
"line_max": 77,
"alpha_frac": 0.6753870796,
"autogenerated": false,
"ratio": 4.071739130434783,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5247126210034783,
"avg_score": null,
"num_lines": null
} |
from .forms import *
from django.views.generic import View, TemplateView, ListView
from django.views.generic.edit import FormView
from django.contrib import messages
import calendar
from django.db.models import Sum,Count
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from datetime import datetime , timedelta, date
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_http_methods
from django.shortcuts import render_to_response, render, redirect, get_object_or_404
from tracking.models import PatientVisit,ReferringEntity, Organization, LAST_MONTH, LAST_12_MONTH
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as auth_logout
from tracking.templatetags.visite_counts import get_organization_counts, \
get_organization_counts_month_lastyear, get_organization_counts_year, \
get_organization_counts_year_lastyear
from Practice_Referral.settings import TIME_ZONE
class LoginRequiredMixin(object):
'''
a Mixin class to check login in class views. View calsses can inherit
from this class to enforce login_required.
'''
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
'''
check login_required for every actions(get, post, ...) by
this dispatcher
'''
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
class IndexView(LoginRequiredMixin, View):
# display the Organization form
# template_name = "index.html"
@staticmethod
def get_context(request, initial_ctx=None):
'''create context structure for both get and post handlers'''
clinic = Clinic.get_from_user(request.user)
orgform = OrganizationForm()
phyform = ReferringEntityForm()
refform = PatientVisitForm()
phyform.fields['organization'].queryset = Organization.objects.filter(
clinic=clinic)
refform.fields['referring_entity'].queryset = ReferringEntity.objects.filter(
organization__clinic=clinic)
refform.fields['treating_provider'].queryset = TreatingProvider.objects.filter(
clinic=clinic)
today_date = datetime.now().date()
start_date = today_date - timedelta(days=365)
end_date = today_date - timedelta(days=1)
referring_entity_visit_sum = ReferringEntity.objects.filter(
organization__clinic=clinic,
PatientVisit__visit_date__range=(start_date,end_date)).annotate(
total_visits=Sum('PatientVisit__visit_count')
).order_by('-total_visits')[:10]
org_visit_sum = Organization.objects.filter(
clinic=clinic,
ReferringEntity__PatientVisit__visit_date__range=(start_date,end_date)).annotate(
total_org_visits=Sum('ReferringEntity__PatientVisit__visit_count')
).order_by('-total_org_visits')[:5]
special_visit_sum = Organization.objects.filter(org_special=True).filter(
clinic=clinic,
ReferringEntity__PatientVisit__visit_date__range=(start_date,end_date)).annotate(
total_org_special_visits=Sum('ReferringEntity__PatientVisit__visit_count')
).order_by('-total_org_special_visits')[:5]
patient_visits = PatientVisit.objects.filter(treating_provider__clinic=clinic,
visit_date__range=[LAST_12_MONTH,LAST_MONTH])
if patient_visits:
try:
patient_visits = patient_visits.extra(select={'month': 'STRFTIME("%m",visit_date)'})
print (patient_visits[0].month)
except Exception:
patient_visits = patient_visits.extra(select={'month': 'EXTRACT(month FROM visit_date)'})
patient_visits = patient_visits.values('month').annotate(total_visit_count=Sum('visit_count'))
for patient_visit in patient_visits:
if LAST_MONTH.month <= int(patient_visit['month']) :
current_month = date(day=LAST_MONTH.day, month= int(patient_visit['month']), year=LAST_MONTH.year)
else:
current_month = date(day=LAST_12_MONTH.day, month= int(
patient_visit['month']), year=LAST_12_MONTH.year)
last_month = current_month-timedelta(days=364)
patient_visits_year = PatientVisit.objects.filter(
visit_date__range=[last_month, current_month]).aggregate(year_total=Sum('visit_count'))
patient_visit['year_total'] = patient_visits_year['year_total']
patient_visit['year_from'] = last_month
patient_visit['year_to'] = current_month
today = date.today()
week_ago = today - timedelta(days=7)
all_orgs = ReferringEntity.objects.filter(organization__clinic=clinic).order_by('entity_name')
all_ref = {}
for phys in all_orgs :
phys_ref = phys.get_patient_visit(
params={'from_date' : week_ago, 'to_date' : today},
clinic=clinic);
if phys_ref.count() :
for ref in phys_ref :
if not phys.id in all_ref :
all_ref[phys.id] = {'name' : phys.entity_name, 'refs' : [ ref ] }
else :
all_ref[phys.id]['refs'].append(ref)
ctx = {
"orgform": orgform,
"phyform": phyform,
"refform": refform,
"referring_entity_visit_sum": referring_entity_visit_sum,
"org_visit_sum": org_visit_sum,
"special_visit_sum": special_visit_sum,
"patient_visits": patient_visits,
"all_orgs": all_ref,
'today': today,
'week_ago': week_ago,
'timezone': TIME_ZONE,
'clinic': clinic
}
ctx.update(initial_ctx or {})
return ctx
def get(self, request, *args, **kwargs):
ctx = self.get_context(request)
return render(request, "index.html", ctx)
def post(self, request, *args, **kwargs):
phyform = ReferringEntityForm()
orgform = OrganizationForm()
refform = PatientVisitForm()
if 'phyform' in request.POST:
phyform = ReferringEntityForm(request.POST)
if phyform.is_valid():
phyform.save()
return redirect(reverse('index'))
elif 'orgform' in request.POST:
orgform = OrganizationForm(request.POST)
if orgform.is_valid():
organization = orgform.save(commit=False)
organization.clinic = Clinic.get_from_user(self.request.user)
organization.save()
return redirect(reverse('index'))
elif 'refform' in request.POST:
refform = PatientVisitForm(request.POST)
if refform.is_valid():
refform.save()
return redirect(reverse('index'))
ctx = self.get_context(request, initial_ctx={
"orgform": orgform,
"phyform": phyform,
"refform": refform,
})
return render(request, "index.html", ctx)
class OrganizationView(LoginRequiredMixin, View):
# display the Organization form
def get(self, request, *args, **kwargs):
form = OrganizationForm()
ctx = {"form": form}
return render(request,"tracking/organization.html",ctx )
def post(self, request, *args, **kwargs):
form = OrganizationForm(request.POST)
ctx = {"form": form}
if form.is_valid():
organization = form.save(commit=False)
organization.clinic = Clinic.get_from_user(self.request.user)
organization.save()
return redirect(reverse('add-referring-entity'))
return render(request,"tracking/organization.html",ctx )
class ReferringEntityView(LoginRequiredMixin, View):
# display the referring_entity form
def get(self, request, *args, **kwargs):
form = ReferringEntityForm()
form.fields['organization'].queryset = Organization.objects.filter(
clinic=Clinic.get_from_user(self.request.user))
ctx = {"form": form}
return render(request,"tracking/referring_entity.html",ctx )
def post(self, request, *args, **kwargs):
form = ReferringEntityForm(request.POST)
if form.is_valid():
form.save()
form = ReferringEntityForm()
ctx = {"form": form}
return render(request,"tracking/referring_entity.html",ctx )
class TreatingProviderView(LoginRequiredMixin, View):
# display the treating_provider form
def get(self, request, *args, **kwargs):
form = TreatingProviderForm()
ctx = {"form": form}
return render(request,"tracking/treating_provider.html",ctx )
def post(self, request, *args, **kwargs):
form = TreatingProviderForm(request.POST)
if form.is_valid():
treating_provider = form.save(commit=False)
treating_provider.clinic = Clinic.get_from_user(self.request.user)
treating_provider.save()
form = TreatingProviderForm()
ctx = {"form": form}
return render(request,"tracking/treating_provider.html",ctx )
class PatientVisitView(LoginRequiredMixin, View):
# display the patient_visit form
def get(self, request, *args, **kwargs):
clinic = Clinic.get_from_user(self.request.user)
form = PatientVisitForm()
form.fields['referring_entity'].queryset = ReferringEntity.objects.filter(
organization__clinic=clinic)
form.fields['treating_provider'].queryset = TreatingProvider.objects.filter(
clinic=clinic)
ctx = {"form": form, 'timezone': TIME_ZONE}
return render(request,"tracking/patient_visit.html",ctx )
def post(self, request, *args, **kwargs):
form = PatientVisitForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/add/patient_visit/')
ctx = {"form": form, 'timezone': TIME_ZONE}
return render(request,"tracking/patient_visit.html",ctx )
class GetPatientVisitReport(LoginRequiredMixin, View):
"""
Display a summary of patient_visits by Organization:provider:
"""
def get(self, request, *args, **kwargs):
all_orgs = Organization.objects.filter(
clinic=Clinic.get_from_user(self.request.user)).order_by('org_name')
today = datetime.now().date()
last_year = today.year - 1
orgs_counts = {}
total_counts = dict(counts=0, counts_month_lastyear=0,
counts_year=0, counts_year_lastyear=0)
for org in all_orgs:
counts = get_organization_counts(org)
counts_month_lastyear = get_organization_counts_month_lastyear(org)
counts_year = get_organization_counts_year(org)
counts_year_lastyear = get_organization_counts_year_lastyear(org)
orgs_counts[org.id] = dict(
counts=counts,
counts_month_lastyear=counts_month_lastyear,
counts_year=counts_year,
counts_year_lastyear=counts_year_lastyear,
)
total_counts['counts'] += counts
total_counts['counts_month_lastyear'] += counts_month_lastyear
total_counts['counts_year'] += counts_year
total_counts['counts_year_lastyear'] += counts_year_lastyear
ctx = {
'all_orgs': all_orgs,
'last_year': last_year,
'orgs_counts': orgs_counts,
'total_counts': total_counts
}
return render(request, "tracking/show_patient_visit_report.html", ctx)
class LogoutView(LoginRequiredMixin, View):
def get(self, request, *args, **kwargs):
auth_logout(request)
return redirect('/')
class GetPatientVisitHistory(LoginRequiredMixin, View):
"""
Display a summary of patient_visits by Date:ReferringEntity:Organization:Count:
"""
def get(self, request, *args, **kwargs):
today = date.today()
clinic = Clinic.get_from_user(self.request.user)
patient_visits = PatientVisit.objects.filter(
treating_provider__clinic=clinic,
visit_date=today).order_by('-visit_date')
form = PatientVisitHistoryForm(initial={'from_date': today, 'to_date' : today})
form.fields['referring_entity'].queryset = ReferringEntity.objects.filter(
organization__clinic=clinic)
ctx = {
'patient_visits': patient_visits,
'timezone': TIME_ZONE,
"form": form
}
return render(request,"tracking/show_patient_visit_history.html",ctx )
def post(self, request, *args, **kwargs):
form = PatientVisitHistoryForm(request.POST)
if form.is_valid():
cleaned_data = form.clean()
patient_visits = PatientVisit.objects\
.filter(
treating_provider__clinic=Clinic.get_from_user(self.request.user),
visit_date__gte=cleaned_data['from_date'],
visit_date__lte=cleaned_data['to_date'])\
.order_by('-visit_date')
if cleaned_data['referring_entity']:
patient_visits = patient_visits.filter(referring_entity__in=cleaned_data['referring_entity'])
else:
patient_visits = []
ctx = {
'patient_visits': patient_visits,
'timezone': TIME_ZONE,
"form": form
}
return render(request,"tracking/show_patient_visit_history.html",ctx )
@login_required
def edit_organization(request, organization_id):
organization = get_object_or_404(Organization, id=organization_id)
if request.method == 'POST':
form = OrganizationForm(request.POST, instance=organization)
if form.is_valid():
organization = form.save(commit=False)
organization.clinic = Clinic.get_from_user(request.user)
organization.save()
return render(request, 'tracking/organization_edit.html', {
'form': form,
'success': True})
else:
form = OrganizationForm(instance=organization)
return render(request, 'tracking/organization_edit.html', {'form': form})
@login_required
def edit_referring_entity(request, referring_entity_id):
referring_entity = get_object_or_404(ReferringEntity, id=referring_entity_id)
if request.method == 'POST':
form = ReferringEntityForm(request.POST, instance=referring_entity)
if form.is_valid():
form.save()
return render(request, 'tracking/referring_entity_edit.html', {
'form': form,
'success': True})
else:
form = ReferringEntityForm(instance=referring_entity)
form.fields['organization'].queryset = Organization.objects.filter(
clinic=Clinic.get_from_user(request.user))
return render(request, 'tracking/referring_entity_edit.html', {'form': form})
@login_required
def edit_treating_provider(request, treating_provider_id):
treating_provider = get_object_or_404(TreatingProvider, id=treating_provider_id)
if request.method == 'POST':
form = TreatingProviderForm(request.POST, instance=treating_provider)
if form.is_valid():
treating_provider = form.save(commit=False)
treating_provider.clinic = Clinic.get_from_user(request.user)
treating_provider.save()
return render(request, 'tracking/treating_provider_edit.html', {
'form': form,
'success': True})
else:
form = TreatingProviderForm(instance=treating_provider)
return render(request, 'tracking/treating_provider_edit.html', {'form': form})
@login_required
def edit_patient_visit(request, patient_visit_id):
''' A view to edit PatientVisit '''
patient_visit = get_object_or_404(PatientVisit, id=patient_visit_id)
if request.method == 'POST':
form = PatientVisitForm(request.POST, instance=patient_visit)
if form.is_valid():
form.save()
messages.success(request, 'Changes saved successfully.')
return render(request, 'tracking/patient_visit_edit.html', {
'form': form, 'timezone': TIME_ZONE})
else:
form = PatientVisitForm(instance=patient_visit)
return render(request, 'tracking/patient_visit_edit.html',
{'form': form, 'timezone': TIME_ZONE})
@login_required
@require_http_methods(["POST"])
def delete_patient_visit(request, patient_visit_id):
''' delete a patient_visit '''
patient_visit = get_object_or_404(PatientVisit, id=patient_visit_id)
form = GenericDeleteForm(request.POST)
if form.is_valid():
patient_visit.delete()
messages.success(request, 'Entity deleted successfully.')
next = request.META.get('HTTP_REFERER') or \
reverse('view-patient-visits')
return redirect(next)
@login_required
@require_http_methods(["POST"])
def delete_organization(request, organization_id):
''' delete an organization '''
organization = get_object_or_404(Organization, id=organization_id)
form = GenericDeleteForm(request.POST)
if form.is_valid():
organization.delete()
messages.success(request, 'Entity deleted successfully.')
next = request.META.get('HTTP_REFERER') or \
reverse('view-organizations')
return redirect(next)
@login_required
@require_http_methods(["POST"])
def delete_referring_entity(request, referring_entity_id):
''' delete a referring_entity '''
referring_entity = get_object_or_404(ReferringEntity,
id=referring_entity_id)
form = GenericDeleteForm(request.POST)
if form.is_valid():
referring_entity.delete()
messages.success(request, 'Entity deleted successfully.')
next = request.META.get('HTTP_REFERER') or \
reverse('view-referring-entities')
return redirect(next)
@login_required
@require_http_methods(["POST"])
def delete_treating_provider(request, treating_provider_id):
''' delete an treating_provider '''
treating_provider = get_object_or_404(TreatingProvider,
id=treating_provider_id)
form = GenericDeleteForm(request.POST)
if form.is_valid():
treating_provider.delete()
messages.success(request, 'Entity deleted successfully.')
next = request.META.get('HTTP_REFERER') or \
reverse('view-treating-providers')
return redirect(next)
class OrganizationListView(LoginRequiredMixin, ListView):
model = Organization
template_name = 'tracking/organization_list.html'
context_object_name = "organizations"
paginate_by = 10
def get_queryset(self):
qs = super(OrganizationListView, self).get_queryset()
return qs.filter(clinic=Clinic.get_from_user(self.request.user))
class ReferringEntityListView(LoginRequiredMixin, ListView):
model = ReferringEntity
template_name = 'tracking/referring_entity_list.html'
context_object_name = "referring_entitys"
paginate_by = 10
def get_queryset(self):
qs = super(ReferringEntityListView, self).get_queryset()
return qs.filter(organization__clinic=Clinic.get_from_user(self.request.user))
class TreatingProviderListView(LoginRequiredMixin, ListView):
model = TreatingProvider
template_name = 'tracking/treating_provider_list.html'
context_object_name = "treating_providers"
paginate_by = 10
def get_queryset(self):
qs = super(TreatingProviderListView, self).get_queryset()
return qs.filter(clinic=Clinic.get_from_user(self.request.user))
class PatientVisitListView(LoginRequiredMixin, ListView):
''' A view to show list of PatientVisit '''
model = PatientVisit
template_name = 'tracking/patient_visit_list.html'
context_object_name = "patient_visits"
paginate_by = 10
def get_queryset(self):
qs = super(PatientVisitListView, self).get_queryset()
return qs.filter(treating_provider__clinic=Clinic.get_from_user(self.request.user))
| {
"repo_name": "Heteroskedastic/Dr-referral-tracker",
"path": "tracking/views.py",
"copies": "1",
"size": "20763",
"license": "mit",
"hash": -2179593539767138000,
"line_mean": 38.3984819734,
"line_max": 118,
"alpha_frac": 0.6195636469,
"autogenerated": false,
"ratio": 3.97377990430622,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.509334355120622,
"avg_score": null,
"num_lines": null
} |
from .forms import *
from .models import *
from datetime import timedelta
from django.contrib import messages
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
from django.contrib.gis.geos import GEOSGeometry
from django.contrib.gis.measure import Distance
from django.db.models import Q
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.template import loader
from django.utils import timezone
from django.views.decorators.csrf import csrf_protect
from email.mime.message import MIMEMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from itertools import chain
from math import *
import datetime
import json
import numpy as np
import random
import requests
import smtplib
import string
#=====================
# GENERAL
#=====================
def actofgoods_startpage(request):
registerform = UserFormRegister()
needs = Need.objects.all().filter(done=False)
if request.user.is_authenticated():
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
return redirect('basics:home')
return render(request, 'basics/actofgoods_startpage.html', {'counter':len(needs),'registerform':registerform})
def aboutus(request):
return render(request, 'basics/aboutus.html')
def contact_us(request):
if request.method == "POST":
form = ContactUsForm(request.POST)
if form.is_valid() :
email = request.POST.get('email')
headline = request.POST.get('headline')
text = request.POST.get('text')
if email != "":
if headline != "":
if text != "":
contactUsData = ContactUs(email=email, headline=headline, text=text)
contactUsData.save()
messages.add_message(request, messages.INFO, 'success contact us')
return redirect('basics:actofgoods_startpage')
else:
messages.add_message(request, messages.INFO, 'no_description')
else:
messages.add_message(request, messages.INFO, 'no_headline')
else:
messages.add_message(request, messages.INFO, 'empty_email')
else:
messages.add_message(request, messages.INFO, 'wrong_email')
return render(request, 'basics/contact_us.html')
def faq_startpage(request):
return render(request, 'basics/faq_startpage.html')
@csrf_protect
def faq_signin(request):
if request.user.is_authenticated():
return render(request, 'basics/faq_signin.html')
return redirect('basics:actofgoods_startpage')
@csrf_protect
def home(request):
if request.user.is_superuser:
return redirect('administration:requests')
if request.user.is_authenticated():
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
return render(request, 'basics/home.html')
return redirect('basics:actofgoods_startpage')
@csrf_protect
def home_filter(request):
if request.user.is_authenticated():
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
if request.POST['group']:
group= Groupdata.objects.get(name=request.POST['group'])
needs = list(Need.objects.all().filter(author=request.user, group=group.group))
infos = list(Information.objects.all().filter(author=request.user, group=group.group))
needs_you_help = list(map(lambda x: x.need, list(Room.objects.all().filter(user_req=request.user))))
comm = list(Comment.objects.all().filter(author=request.user, group=group.group))
else:
needs = list(Need.objects.all().filter(author=request.user))
infos = list(Information.objects.all().filter(author=request.user))
needs_you_help = list(map(lambda x: x.need, list(Room.objects.all().filter(user_req=request.user))))
comm = list(Comment.objects.all().filter(author=request.user))
rel_comms = []
for c in comm:
if not c.inf in rel_comms:
rel_comms.append(c)
activity=request.POST['activity']
followed_infos = []
if activity=="all_activities":
usr_pk = request.user.userdata.pk
followed_infos = []
all_infos = Information.objects.all()
for i in all_infos:
follower = i.followed_by
if len(follower.filter(pk = usr_pk)) != 0:
followed_infos.append(i)
result_list = sorted(
chain(needs, infos, needs_you_help, rel_comms, followed_infos),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
elif activity=="posted_needs":
result_list = sorted(
chain(needs),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
elif activity=="needs_help":
result_list = sorted(
chain(needs_you_help),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
elif activity=="posted_information":
result_list = sorted(
chain(infos),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
elif activity=="written_comments":
result_list = sorted(
chain(rel_comms),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
elif activity=="followed_infos":
usr_pk = request.user.userdata.pk
followed_infos = []
all_infos = Information.objects.all()
for i in all_infos:
follower = i.followed_by
if len(follower.filter(pk = usr_pk)) != 0:
followed_infos.append(i)
result_list = sorted(
chain(followed_infos),
key=lambda instance: instance.was_helped_at.was_helped_at if hasattr(instance, 'was_helped_at') and instance not in needs else instance.date, reverse=True)
t = loader.get_template('snippets/home_filter.html')
return HttpResponse(t.render({'request': request, 'needs': needs, 'infos': infos, 'needs_you_help': needs_you_help, 'followed_infos': followed_infos, 'result_list': result_list}))
@csrf_protect
def home_unfollow(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
info.followed_by.remove(request.user.userdata)
info.save()
return home_filter(request)
def privacy(request):
return render(request, 'basics/privacy.html')
#=====================
# Profile & Req.
#=====================
@csrf_protect
def change_password(request):
if request.user.is_authenticated():
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
user=request.user
if request.method=="POST":
form=PasswordForm(request.POST)
if form.is_valid():
oldpw=request.POST['oldpw']
newpw1=request.POST.get('newpw1')
newpw2=request.POST.get('newpw2')
if (authenticate(username=user.email,password=oldpw)==user) and (newpw1 == newpw2):
user.set_password(newpw1)
user.save()
return render(request, 'basics/profil.html', {'Userdata':user.userdata})
else :
change=True
return render(request,'basics/change_password.html',{'change':change})
form=PasswordForm()
change=False
return render(request,'basics/change_password.html',{'form':form,'change':change})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def immediate_aid(request):
form = ImmediateAidFormNew(initial={'email': ''})
need = NeedFormNew()
if request.method == "POST":
#This method is super deprecated we need to make it more secure
#it could lead to data sniffing and shitlot of problems;
#But to demonstrate our features and only to demonstrate
#it will send the given email his password
form = ImmediateAidFormNew(request.POST)
need = NeedFormNew(request.POST)
if form.is_valid() and need.is_valid():
password_d = id_generator(9)
check_password = password_d
if request.POST.get('email', "") != "":
lat, lng = getAddress(request)
if lat != None and lng != None:
user_data = form.cleaned_data
user = User.objects.create_user(username=user_data['email'], password=password_d, email=user_data['email'])
userdata = Userdata(user=user,pseudonym=("user" + str(User.objects.count())), adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng)))
userdata.save()
content = "Thank you for joining Actofgoods \n\n You will soon be able to help people in your neighbourhood \n\n but please verify your account first on http://10.200.1.40/verification/%s"%(userdata.pseudonym)
subject = "Confirm Your Account"
data = need.cleaned_data
u=Update.objects.create(update_at=(timezone.now() + timedelta(hours=1)))
needdata = Need(author=user, group=None, headline=data['headline'], text=data['text'], categorie=data['categorie'], was_reported=False, adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng)), priority=priority_need_user(0), update_at=u)
needdata.save()
#Content could also be possibly HTML! this way beautifull emails are possible
content = "You are a part of Act of Goods! \n Help people in your hood. \n See ya http://10.200.1.40 \n Maybe we should give a direct link to your need, but its not implemented yet. \n Oh you need your password: %s"% (password_d)
subject = "Welcome!"
user = authenticate(username=user_data['email'],password=password_d)
auth_login(request,user)
sendmail(user.email, content, subject )
send_notifications(needdata)
return redirect('basics:actofgoods_startpage')
else:
messages.add_message(request, messages.INFO, 'location_failed')
else:
messages.add_message(request, messages.INFO, 'wp')
else:
messages.add_message(request, messages.INFO, 'eae')
return render(request, 'basics/immediate_aid.html', {'categories': CategoriesNeeds.objects.all().order_by('name'), 'form' : form, 'need' : need })
@csrf_protect
def login(request):
if request.method == 'POST':
email = request.POST.get('email',None)
password = request.POST.get('password',None)
user = authenticate(username=email,password=password)
if user is not None:
auth_login(request,user)
else :
messages.add_message(request, messages.INFO, 'lw')
return redirect('basics:actofgoods_startpage')
@csrf_protect
def logout(request):
auth_logout(request)
return HttpResponse(actofgoods_startpage(request))
@csrf_protect
def profil(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
userdata=request.user.userdata
return render(request, 'basics/profil.html',{'Userdata':userdata, 'selected': userdata.inform_about.all()})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def profil_edit(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
user=request.user
userdata=request.user.userdata
if request.method == "POST":
email = request.POST.get('email', None)
phone = request.POST.get('phone', None)
aux = request.POST.get('aux', None)
lat, lng = getAddress(request)
if email != "":
if (len(User.objects.all().filter(email=email)) == 0 or email == user.email):
user.username = email
user.email = email
user.save()
else:
form = ProfileForm()
return render(request, 'basics/profil_edit.html',
{'userdata': userdata, 'categories': CategoriesNeeds.objects.all().order_by('name'),
'selected': userdata.inform_about.all(), 'form': form, 'email': True, 'change':False})
if request.POST.get('changePassword') == "on":
oldpw = request.POST['oldpw']
newpw1 = request.POST.get('newpw1')
newpw2 = request.POST.get('newpw2')
if (authenticate(username=user.email, password=oldpw) == user) and (newpw1 == newpw2):
user.set_password(newpw1)
user.save()
else:
form = ProfileForm()
return render(request, 'basics/profil_edit.html',
{'userdata': userdata, 'categories': CategoriesNeeds.objects.all().order_by('name'),
'selected': userdata.inform_about.all(), 'form': form, 'change':True })
if lat != None and lng != None:
userdata.adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng))
userdata.save()
if aux != "":
try:
userdata.aux= float(aux)
except ValueError:
print("Something went wrong while converting float.")
if phone!= "":
userdata.phone=phone
if request.POST.get('information') == "on":
userdata.get_notifications = True
else:
userdata.get_notifications=False
categories= request.POST.getlist('categories[]')
for c in CategoriesNeeds.objects.all().order_by('name'):
if c.name in categories:
userdata.inform_about.add(c)
else:
userdata.inform_about.remove(c)
userdata.save()
return render(request, 'basics/profil.html', {'Userdata':userdata, 'selected': userdata.inform_about.all()})
form = ProfileForm()
return render(request, 'basics/profil_edit.html', {'userdata':userdata, 'categories': CategoriesNeeds.objects.all().order_by('name'), 'selected': userdata.inform_about.all(),'form':form,'change':False})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def profil_delete(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
user=request.user
user.delete()
sendmail(user.email, "Auf Wiedersehen " + user.username + ", \n schade das sie ihr Profil gelöscht haben, aber keine Angst wir speichern all ihre Daten weiter 50 Jahre. \n"
+"Wenn sie sich nicht innerhalb von 3 Tagen wieder anmelden werden wir ihren Wohnort an den höchst bietenden verkaufen. Wir bedanken uns für ihr Verständni. \n\n Mit Freundlichen Grüßen Act of Goods", "Auf Wiedersehen!")
return actofgoods_startpage(request)
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
@csrf_protect
def register(request):
if request.method == 'POST':
form = UserFormRegister(request.POST)
if form.is_valid():
id = id_generator(8)
while():
if(len(Userdata.objects.all().filter(id = id)) != 0):
break;
id = id_generator(8)
password = request.POST.get('password', "")
check_password = request.POST.get('check_password', "")
if password != "" and check_password != "" and request.POST.get('email', "") != "":
if password == check_password:
lat, lng = getAddress(request)
if lat != None and lng != None:
data = form.cleaned_data
user = User.objects.create_user(username=data['email'], password=data['password'], email=data['email'],)
userdata = Userdata(user=user,pseudonym=("user" + str(User.objects.count())), get_notifications= False, adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng)), verification_id = id)
userdata.save()
# user.is_active = False
# user.save()
content = "Thank you for joining Actofgoods \n\n Soon you will be able to help people in your neighbourhood \n\n but please verify your account first on http://10.200.1.40/verification/%s"%(userdata.verification_id)
subject = "Confirm Your Account"
# sendmail(user.email, content, subject)
return login(request)
else:
messages.add_message(request, messages.INFO, 'location_failed')
else:
messages.add_message(request, messages.INFO, 'wp')
elif not form.is_valid():
messages.add_message(request, messages.INFO, 'eae')
return redirect('basics:actofgoods_startpage')
def reset_password_page(request):
if request.method == "POST":
capForm = CaptchaForm(request.POST)
#This method is super deprecated we need to make it more secure
#it could lead to data sniffing and shitlot of problems;
#But to demonstrate our features and only to demonstrate
#it will send the given email his password
if 'email' in request.POST:
if capForm.is_valid():
email = request.POST['email']
user = User.objects.get(email = email)
if user is not None:
new_password = id_generator(9)
user.set_password(new_password)
user.save()
#Content could also be possibly HTML! this way beautifull emails are possible
content = 'Your new password is %s. Please change your password after you have logged in. \n http://10.200.1.40'%(new_password)
subject = "Reset Password - Act Of Goods"
#sendmail(email, content, subject )
messages.add_message(request, messages.INFO, 'success reset password')
return redirect('basics:actofgoods_startpage')
elif not capForm.is_valid():
messages.add_message(request, messages.INFO, 'wc')
return render(request, 'basics/password_reset.html')
def reset_password_confirmation(request):
return render(request, 'basics/password_reset_confirmation.html')
@csrf_protect
def verification(request,id):
if request.user.is_authenticated():
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.userdata.verification_id == id:
user=request.user
user.is_active = True
user.save()
return render(request, 'basics/verification.html', {'verified':True, 'active':True})
if request.method == "POST":
form = UserFormRegister(request.POST)
email = request.POST.get('email', None)
password = request.POST.get('password', None)
user = authenticate(username=email, password=password)
if user is not None and user.userdata.verification_id == id :
auth_login(request, user)
user.is_active = True
user.save()
return render(request, 'basics/verification.html', {'verified': True, 'active':True})
form=UserFormRegister()
return render (request, 'basics/verification.html', {'verified':False, 'form':form, 'id': id, 'active': True})
#=====================
# CHAT
#=====================
@csrf_protect
def chat(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
if request.method == "GET":
try:
room=get_valid_rooms(request.user).latest('last_message')
return redirect('basics:chat_room', roomname=room.name)
except:
return render(request,'basics/no_chat.html')
return redirect('basics:actofgoods_startpage')
@csrf_protect
def chat_room(request, roomname):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
try:
room = Room.objects.get(name=roomname)
except Room.DoesNotExist:
return page_not_found(request)
name = room.need.headline
if room.need.author == request.user or (room.user_req == request.user):
print(request.user.username)
room.set_saw(request.user)
messages = ChatMessage.objects.filter(room=roomname).order_by('date')
message_json = messages_to_json(messages)
#Get all rooms where request.user is in contact with
rooms = get_valid_rooms(request.user).exclude(name=roomname).order_by('-last_message')
rooms_json = rooms_to_json(rooms, request.user)
return render(request, 'basics/chat.html',{'name':name, 'room':room, 'roomname':roomname, 'messages':message_json, 'rooms':rooms, 'rooms_json':rooms_json})
else:
return permission_denied(request)
return redirect('basics:actofgoods_startpage')
def get_valid_rooms(user):
return Room.objects.filter(Q(need__author =user) | Q(user_req = user, helper_out=False))
@csrf_protect
def kick_user(request, roomname):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
try:
room = Room.objects.get(name=roomname)
except Room.DoesNotExist:
return page_not_found(request)
if request.user == room.user_req or request.user == room.need.author:
text = "Helper was kicked."
if request.user == room.user_req:
text = "Helper leaved."
room.helper_out = True
room.save()
ChatMessage.objects.create(room=room, text=text, author=None)
else:
return permission_denied(request)
return redirect('basics:actofgoods_startpage')
def messages_to_json(messages):
message_json = "["
for message in messages:
try:
message_json += json.dumps({
'message': message.text,
'username': message.author.username,
'date': message.date.__str__()[:-13]
}) + ","
except:
message_json += json.dumps({
'message': message.text,
'username': 'null',
'date': message.date.__str__()[:-13]
}) + ","
message_json += "]"
return message_json
@csrf_protect
def needs_finish(request, roomname):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
try:
room = Room.objects.get(name=roomname)
except Room.DoesNotExist:
return page_not_found(request);
if room.need.author == request.user:
if room.need.group:
text = "The need owner " + room.need.group.name + " considered the matter as settled."
else:
text = "The need owner considered the matter as settled."
elif room.user_req == request.user:
if room.group:
text = "The helper " + room.need.group.name + " considered the matter as settled."
else:
text = "The helper considered the matter as settled."
else:
return permission_denied(request)
room.set_room_finished(request.user)
ChatMessage.objects.create(room=room, text=text, author=None)
return redirect('basics:actofgoods_startpage')
def rooms_to_json(rooms, user):
rooms_json = "["
if len(rooms) > 0:
for room in rooms:
new_message = "true" if room.new_message(user) else "false"
rooms_json += json.dumps({
'name': room.need.headline,
'hash': room.name,
'new': new_message,
'last_message': room.recent_message(),
'date': room.last_message.__str__()[:-13]
}) + ","
rooms_json = rooms_json[:-1]
rooms_json += "]"
return rooms_json
#=====================
# CLAIM
#=====================
@csrf_protect
def claim(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
categories=CategoriesNeeds.objects.all().order_by('name')
return render(request, 'basics/map_claim.html', {'categories': categories,'group': name, 'polygons': ClaimedArea.objects.order_by('pk'), 'polyuser': ClaimedArea.objects.order_by('pk').filter(group=request.user.groups.get(name=name))})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_post(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
if request.method=="POST":
poly_path=request.POST['path']
#name=request.POST['name']
response_data = {}
claimname=request.POST['claimname']
wkt = "POLYGON(("+poly_path+"))"
gro = request.user.groups.get(name=name)
claim = ClaimedArea.objects.create(claimer=request.user,group=gro, poly=wkt, title=claimname)
claim.save()
response_data['result'] = 'Creation successful!'
response_data['owner']=request.user.email
response_data['poly']=claim.poly.geojson
response_data['pk']=claim.pk
response_data['claimname']=claim.title
return JsonResponse(response_data)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_delete(request,name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
if request.method=="POST":
pk=request.POST['pk']
ClaimedArea.objects.all().get(pk=pk).delete()
response_data = {}
response_data['result'] = 'Deletion successful!'
return JsonResponse(response_data)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_refresh(request,name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
index=request.POST['index']
pk = request.POST['pk']
t = loader.get_template('snippets/claim.html')
return HttpResponse(t.render({'index':index, 'poly': ClaimedArea.objects.get(pk=pk)}))
@csrf_protect
def claim_information(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
#TODO: Change this to somehing like user distance
group = Groupdata.objects.get(name=name)
liste=request.POST.getlist('liste[]')
if liste:
claims = ClaimedArea.objects.filter(pk__in=liste)
else:
claims = ClaimedArea.objects.filter(group=group.group)
infos=Information.objects.all().order_by('priority', 'pk').reverse()
#for claim in claims:
if claims.exists():
query = Q(adrAsPoint__within=claims[0].poly)
for q in claims[1:]:
query |= Q(adrAsPoint__within=q.poly)
infos = infos.filter(query)
if "" != request.POST['wordsearch']:
wordsearch = request.POST['wordsearch']
infos = infos.filter(Q(headline__icontains=wordsearch) | Q(text__icontains=wordsearch))
t = loader.get_template('snippets/claim_informations.html')
return HttpResponse(t.render({'user': request.user, 'infos':infos}))
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_needs(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
#TODO: Change this to somehing like user distance
group = Groupdata.objects.get(name=name)
liste=request.POST.getlist('liste[]')
if liste:
claims = ClaimedArea.objects.filter(pk__in=liste)
else:
claims = ClaimedArea.objects.filter(group=group.group)
needs=Need.objects.all().exclude(author=request.user).exclude(group=group.group).order_by('-priority', 'pk')
#for claim in claims:
if claims.exists():
query = Q(adrAsPoint__within=claims[0].poly)
for q in claims[1:]:
query |= Q(adrAsPoint__within=q.poly)
needs = needs.filter(query)
if "" != request.POST['category'] and "All" != request.POST['category']:
category = request.POST['category']
needs = needs.filter(categorie=CategoriesNeeds.objects.get(name=category))
if "" != request.POST['wordsearch']:
wordsearch = request.POST['wordsearch']
needs = needs.filter(Q(headline__icontains=wordsearch) | Q(text__icontains=wordsearch))
t = loader.get_template('snippets/claim_needs_group.html')
needs = [s for s in needs if not Room.objects.filter(need=s).filter(Q(helper_out=False)| Q(user_req=request.user)).exists()]
return HttpResponse(t.render({'user': request.user, 'needs':needs, 'group':group}))
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_reportInfo(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
if Userdata.objects.get(user=request.user) in info.reported_by.all():
return permission_denied(request)
info.was_reported = True
info.number_reports += 1
info.save()
info.reported_by.add(request.user.userdata)
return claim_information(request, name)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_reportNeed(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
need = get_object_or_404(Need, pk=pk)
if Userdata.objects.get(user=request.user) in need.reported_by.all():
return permission_denied(request)
need.was_reported = True
need.number_reports += 1
need.save()
need.reported_by.add(request.user.userdata)
t = loader.get_template('snippets/claim_report.html')
return HttpResponse(t.render({'user': request.user, 'need':need, 'group':Groupdata.objects.get(name=name)}))
return redirect('basics:actofgoods_startpage')
@csrf_protect
def claim_like(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
if Userdata.objects.get(user=request.user) in info.liked_by.all():
return permission_denied(request)
info.was_liked = True
info.number_likes += 1
info.liked_by.add(request.user.userdata)
info.save()
hours_elapsed = int((timezone.now() - info.date).seconds/3600)
info.priority = priority_info_user(hours_elapsed, info.number_likes)
info.save()
return claim_information(request, name)
@csrf_protect
def claim_unlike(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
info.number_likes -= 1
if info.number_likes == 0:
info.was_liked = False
info.liked_by.remove(request.user.userdata)
info.save()
return claim_information(request, name)
@csrf_protect
def claim_follow(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
info.followed_by.add(request.user.userdata)
info.save()
return claim_information(request, name)
@csrf_protect
def claim_unfollow(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
pk=int(request.POST['pk'])
info = Information.objects.get(pk=pk)
info.followed_by.remove(request.user.userdata)
info.save()
return claim_information(request, name)
#=====================
# Information
#=====================
@csrf_protect
def information_all(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
#TODO: Change this to somehing like user distance
if request.user.userdata:
dist = request.user.userdata.aux
else:
dist=500
return render(request, 'basics/information_all.html',{'range':dist})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_filter(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
cards_per_page = 10
wordsearch = ""
dist= int(request.POST['range'].replace(',',''))
infos=Information.objects.filter(adrAsPoint__distance_lte=(request.user.userdata.adrAsPoint, Distance(km=dist)))
if "" == request.POST['wordsearch']:
for i in infos:
if i.update_at.update_at < timezone.now():
hours_elapsed = int((timezone.now() - i.date).seconds/3600)
i.update_at.update_at = timezone.now() + timedelta(hours=1)
if i.group:
priority = priority_info_group(hours_elapsed, i.number_likes)
else:
priority = priority_info_user(hours_elapsed, i.number_likes)
i.priority = priority
i.save()
infos=infos.order_by('-priority','pk')
page = 1
page_range = np.arange(1, 5)
if request.method == "POST":
if "" != request.POST['page']:
page = int(request.POST['page'])
if "" != request.POST['range']:
dist= int(request.POST['range'].replace(',',''))
if not request.user.is_superuser:
infos=infos.filter(adrAsPoint__distance_lte=(request.user.userdata.adrAsPoint, Distance(km=dist)))
if "" != request.POST['wordsearch']:
wordsearch = request.POST['wordsearch']
infos = infos.filter(Q(headline__icontains=request.POST['wordsearch']) | Q(text__icontains=request.POST['wordsearch']))
if "" != request.POST['cards_per_page']:
cards_per_page = int(request.POST['cards_per_page'])
max_page = int(len(infos)/cards_per_page)+1
infos = infos[cards_per_page*(page-1):cards_per_page*(page)]
page_range = np.arange(1,max_page+1)
t = loader.get_template('snippets/info_filter.html')
return HttpResponse(t.render({'user': request.user, 'infos':infos, 'page':page, 'page_range':page_range, 'cards_per_page':cards_per_page, 'size': len(infos)}))
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_delete_comment(request, pk_inf, pk_comm):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
comment = Comment.objects.get(pk=pk_comm)
if request.user == comment.author:
comment.delete()
return redirect('basics:information_view', pk=pk_inf)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_new(request):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.method == "POST":
info = InformationFormNew(request.POST)
if info.is_valid():
lat, lng = getAddress(request)
u=Update.objects.create(update_at=(timezone.now() + timedelta(hours=1)))
priority = 0
group = None
author_is_admin = False
data = info.cleaned_data
if request.POST.get('group') != 'no_group' and request.POST.get('group') != None and request.POST.get('group') != 'admin':
group = Group.objects.get(pk=request.POST.get('group'))
priority = priority_info_group(0, 0)
elif request.POST.get('group') == 'no_group':
priority = priority_info_user(0, 0)
elif request.POST.get('group') == 'admin':
priority = priority_info_group(0, 0)
author_is_admin = True
if lat == None or lng == None:
lat, lng = Userdata.objects.get(user=request.user).get_lat_lng();
infodata = Information(author=request.user, author_is_admin=author_is_admin, headline=data['headline'], text=data['text'], adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng)), priority=priority, update_at=u)
infodata.group = group
infodata.save()
return redirect('basics:actofgoods_startpage')
else:
messages.add_message(request, messages.INFO, 'not_valid')
info = InformationFormNew()
return render(request, 'basics/information_new.html', {'info':info})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_update(request, pk):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
information= Information.objects.all().get(pk=pk)
if request.method == "POST":
text = request.POST.get('text', None)
lat, lng = getAddress(request)
if lat != None and lng != None:
information.adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng))
if text != "":
information.text = information.text + "\n\n UPDATE " + timezone.now().strftime("%Y-%m-%d %H:%M:%S %Z") +"\n\n" + text
else:
messages.add_message(request, messages.INFO, 'empty_text')
return render(request, 'basics/information_update.html', {'information':information})
information.save()
return actofgoods_startpage(request)
form = InformationFormNew()
return render(request, 'basics/information_update.html', {'information':information})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_view(request, pk):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
information = get_object_or_404(Information, pk=pk)
comments = Comment.objects.filter(inf=information).order_by('date')
return render (request, 'basics/information_view.html', {'information':information, 'comments':comments})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def information_view_comment(request, pk):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
information = get_object_or_404(Information, pk=pk)
if request.method == "POST":
group = None
if request.POST.get('group') != 'no_group' and request.POST.get('group') != None:
group = Group.objects.get(pk=request.POST.get('group'))
comment = Comment.objects.create(inf=information, author=request.user, group=group, text=request.POST['comment_text'])
return redirect('basics:information_view', pk=pk)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def info_delete(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
info = get_object_or_404(Information, pk=pk)
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
info.delete()
return redirect('basics:actofgoods_startpage')
@csrf_protect
def info_edit(request, pk):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
info = get_object_or_404(Information, pk=pk)
if request.method == "POST":
text = request.POST.get('text', None)
desc = request.POST.get('desc', None)
lat, lng = getAddress(request)
if lat != None and lng != None:
info.adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng))
if text != "":
info.text = text
if desc != "":
info.headline = desc
info.save()
return actofgoods_startpage(request)
form = InformationFormNew()
return render(request, 'basics/info_edit.html', {'info': info})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def follow(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = get_object_or_404(Information, pk=pk)
info.followed_by.add(request.user.userdata)
info.save()
return information_filter(request)
@csrf_protect
def unfollow(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = get_object_or_404(Information, pk=pk)
info.followed_by.remove(request.user.userdata)
info.save()
return information_filter(request)
@csrf_protect
def like_information(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = get_object_or_404(Information, pk=pk)
info.was_liked = True
info.number_likes += 1
info.liked_by.add(request.user.userdata)
info.save()
hours_elapsed = int((timezone.now() - info.date).seconds/3600)
info.priority = priority_info_user(hours_elapsed, info.number_likes)
info.save()
return information_filter(request)
@csrf_protect
def unlike_information(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = get_object_or_404(Information, pk=pk)
if Userdata.objects.get(user=request.user) in info.liked_by.all():
return permission_denied(request)
info.number_likes -= 1
if info.number_likes == 0:
info.was_liked = False
info.liked_by.remove(request.user.userdata)
info.save()
return information_filter(request)
@csrf_protect
def report_information(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
info = get_object_or_404(Information, pk=pk)
if Userdata.objects.get(user=request.user) in info.reported_by.all():
return permission_denied(request)
info.was_reported = True
info.number_reports += 1
info.save()
info.reported_by.add(request.user.userdata)
return information_filter(request)
#=====================
# NEEDS
#=====================
@csrf_protect
def needs_all(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
#TODO: Change this to somehing like user distance
if request.user.userdata:
dist = request.user.userdata.aux
else:
dist=500
category = "All"
return render(request, 'basics/needs_all.html',{'categorie':CategoriesNeeds.objects.all().order_by('name'), 'category':category, 'range':dist})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def needs_filter(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
category = "All"
cards_per_page = 10
wordsearch = ""
dist= int(request.POST['range'].replace(',',''))
needs=Need.objects.filter(adrAsPoint__distance_lte=(request.user.userdata.adrAsPoint, Distance(km=dist)))
needs = needs.exclude(author=request.user)
if "" == request.POST['wordsearch']:
for n in needs:
if n.update_at.update_at < timezone.now():
hours_elapsed = int((timezone.now() - n.date).seconds/3600)
n.update_at.update_at = timezone.now() + timedelta(hours=1)
if n.group:
priority = priority_need_group(hours_elapsed)
else:
priority = priority_need_user(hours_elapsed)
n.priority = priority
n.save()
needs=needs.order_by('-priority', 'pk')
page = 1
page_range = np.arange(1, 5)
if request.method == "POST":
if "" != request.POST['page']:
page = int(request.POST['page'])
if "" != request.POST['category'] and "All" != request.POST['category']:
category = request.POST['category']
try:
categoriesNeeds = CategoriesNeeds.objects.get(name=category)
except CategoriesNeeds.DoesNotExist:
return bad_request(request)
needs = needs.filter(categorie=categoriesNeeds)
if "" != request.POST['range']:
dist= int(request.POST['range'].replace(',',''))
if not request.user.is_superuser:
needs=needs.filter(adrAsPoint__distance_lte=(request.user.userdata.adrAsPoint, Distance(km=dist)))
if "" != request.POST['wordsearch']:
wordsearch = request.POST['wordsearch']
needs = needs.filter(Q(headline__icontains=request.POST['wordsearch']) | Q(text__icontains=request.POST['wordsearch']))
if "" != request.POST['cards_per_page']:
cards_per_page = int(request.POST['cards_per_page'])
elif request.method == "GET":
if not request.user.is_superuser:
needs=needs.filter(adrAsPoint__distance_lte=(request.user.userdata.adrAsPoint, Distance(km=dist)))
#TODO: this way is fucking slow and should be changed but i didn't found a better solution
needs = [s for s in needs if not Room.objects.filter(need=s).filter(Q(helper_out=False)| Q(user_req=request.user)).exists()]
max_page = int(len(needs)/cards_per_page)+1
needs = needs[cards_per_page*(page-1):cards_per_page*(page)]
#needs.sort(key=lambda x: (-x.priority, x.pk))
page_range = np.arange(1,max_page+1)
t = loader.get_template('snippets/need_filter.html')
return HttpResponse(t.render({'user': request.user, 'needs':needs, 'page':page, 'page_range':page_range, 'cards_per_page':cards_per_page, 'size': len(needs)}))
return redirect('basics:actofgoods_startpage')
@csrf_protect
def needs_help(request, id):
#cat = CategoriesNeeds.objects.create(name="cool")
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.method == "GET":
need = get_object_or_404(Need, id=id)
if need.author != request.user:
#TODO: id_generator will return random string; Could be already in use
if Room.objects.filter(need=need).filter(Q(user_req=request.user)|Q(helper_out=False)).exists():
#TODO: add error message, 'This need is currently in work'
return redirect('basics:actofgoods_startpage')
room = Room.objects.create(name=id_generator(), need=need)
room.user_req = request.user
room.save()
helped_at = Helped.objects.create(was_helped_at=timezone.now())
need.was_helped_at = helped_at
need.save()
return redirect('basics:chat_room', roomname=room.name)
else:
return permission_denied(request)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def needs_help_group(request, id, group_id):
#cat = CategoriesNeeds.objects.create(name="cool")
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.method == "GET":
try:
group = Group.objects.get(id=group_id)
except Group.DoesNotExist:
return bad_request(request)
if request.user not in list(group.user_set.all()):
return permission_denied(request)
need = get_object_or_404(Need, id=id)
if need.author != request.user:
#TODO: id_generator will return random string; Could be already in use
if Room.objects.filter(need=need).filter(Q(user_req=request.user)|Q(helper_out=False)).exists():
#TODO: add error message, 'This need is currently in work'
return redirect('basics:actofgoods_startpage')
room = Room.objects.create(name=id_generator(), group=group, need=need)
room.user_req = request.user
room.save()
helped_at = Helped.objects.create(was_helped_at=timezone.now())
need.was_helped_at = helped_at
need.save()
return redirect('basics:chat_room', roomname=room.name)
else:
return permission_denied(request)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def needs_new(request):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
#cat = CategoriesNeeds.objects.create(name="cool")
if request.user.is_authenticated() and not request.user.is_superuser:
if request.method == "POST":
need = NeedFormNew(request.POST)
if need.is_valid():
lat, lng = getAddress(request)
if lat == None or lng == None:
lat, lng =request.user.userdata.get_lat_lng()
data = need.cleaned_data
if data['headline'] != "":
if data['text'] != "":
group = None
priority = 0
if request.POST.get('group') != 'no_group' and request.POST.get('group') != None:
try:
group = Group.objects.get(id=request.POST.get('group'))
except Group.DoesNotExist:
return bad_request(request)
priority = priority_need_group(0)
else:
priority = priority_need_user(0)
u=Update.objects.create(update_at=(timezone.now() + timedelta(hours=1)))
needdata = Need(author=request.user, group=group, headline=data['headline'], text=data['text'], categorie=data['categorie'], was_reported=False, adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng)), priority=priority, update_at=u)
needdata.save()
send_notifications(needdata)
return redirect('basics:actofgoods_startpage')
else:
messages.add_message(request, messages.INFO, 'no_text')
else:
priority = priority_need_user(0)
messages.add_message(request, messages.INFO, 'no_headline')
else:
messages.add_message(request, messages.INFO, 'not_valid')
need = NeedFormNew()
c = CategoriesNeeds(name="Others")
c.save
return render(request, 'basics/needs_new.html', {'need':need, 'categories': CategoriesNeeds.objects.all().order_by('name')})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def needs_view(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
need = get_object_or_404(Need, pk=pk)
return render (request, 'basics/needs_view.html', {'need':need})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def need_delete(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
need = Need.objects.all().get(pk=pk)
need.delete()
return redirect('basics:actofgoods_startpage')
@csrf_protect
def need_edit(request, pk):
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active': False})
if request.user.is_authenticated() and not request.user.is_superuser:
need= Need.objects.all().get(pk=pk)
if request.method == "POST":
text = request.POST.get('text', None)
desc = request.POST.get('desc', None)
lat, lng = getAddress(request)
if lat != None and lng != None:
need.adrAsPoint=GEOSGeometry('POINT(%s %s)' % (lat, lng))
if text != "":
need.text=text
if desc != "":
need.headline=desc
need.save()
return actofgoods_startpage(request)
form = NeedFormNew()
return render(request, 'basics/need_edit.html', {'need':need, 'categories': CategoriesNeeds.objects.all().order_by('name')})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def report_need(request):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.is_ajax():
pk=int(request.POST['pk'])
need = get_object_or_404(Need, pk=pk)
if Userdata.objects.get(user=request.user) in need.reported_by.all():
return permission_denied(request)
need.was_reported = True
need.number_reports += 1
need.save()
need.reported_by.add(request.user.userdata)
return needs_filter(request)
#=====================
# COMMENTS
#=====================
@csrf_protect
def comm_delete(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
comm = Comment.objects.all().get(pk=pk)
comm.delete()
return redirect('basics:actofgoods_startpage')
@csrf_protect
def delete_comment_timeline(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
comment = Comment.objects.get(pk=pk)
comment.delete()
return redirect('basics:home')
return redirect('basics:actofgoods_startpage')
def report_comment(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
comment = get_object_or_404(Comment, pk=pk)# Comment.objects.get(pk=pk)
if Userdata.objects.get(user=request.user) in comment.reported_by.all():
return permission_denied(request)
comment.was_reported = True
comment.number_reports += 1
comment.reported_by.add(request.user.userdata)
comment.save()
return information_view(request, comment.inf.pk)
#=====================
# GROUPS
#=====================
def groups_all(request):
groups = Groupdata.objects.all().order_by('name')
return render(request, 'basics/groups_all.html', {'groups':groups})
def group_detail(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
try:
gro = request.user.groups.get(name=name)
except Group.DoesNotExist:
return bad_request(request)
if request.method == "POST":
form = GroupAddUserForm(request.POST)
if form.is_valid():
if 'add_group_member' in form.data:
email = request.POST.get('email')
if {'email': email} in User.objects.values('email'):
try:
user = User.objects.get(email=email)
except User.DoesNotExist:
return bad_request(request)
gro.user_set.add(user)
else:
messages.add_message(request, messages.INFO, 'wrong_email')
users = gro.user_set.all()
group = Groupdata.objects.get(name=gro.name)
claims = ClaimedArea.objects.filter(group=group.group)
groups = Groupdata.objects.all().order_by('name')
#for claim in claims:
needs = []
infos = []
if claims.exists():
query = Q(adrAsPoint__within=claims[0].poly)
for q in claims[1:]:
query |= Q(adrAsPoint__within=q.poly)
needs = Need.objects.filter(query)
infos = Information.objects.filter(query)
return render(request, 'basics/group_detail.html', {'group':group, 'groups':groups, 'users':users, 'needs':needs, 'infos':infos})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def group_detail_for_user(request, name):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
group = get_object_or_404(Groupdata, name=name)#Groupdata.objects.get(name=name)
return render(request, 'basics/group_detail_for_user.html', {'group':group})
return redirect('basics:actofgoods_startpage')
@csrf_protect
def group_edit(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.method == "GET":
group = get_object_or_404(Groupdata, pk=pk)
return render(request, 'basics/group_edit.html', {'group': group})
elif request.method == "POST":
form = GroupEditForm(request.POST)
lat, lng = getAddress(request)
if form.is_valid():
group = get_object_or_404(Groupdata, pk=pk)
email = request.POST.get('email')
if request.POST.get('email', "") != "":
group.email = request.POST.get('email')
if request.POST.get('phone') != "" :
group.phone = request.POST.get('phone')
if lat != None and lng != None:
address = Address.objects.create(latitude=lat, longditude=lng)
group.address =address
if request.POST.get('page') != "":
group.webpage=request.POST.get('page')
if request.POST.get('description') !="":
group.description=request.POST.get('description')
group.save()
return group_detail(request, group.name)
else:
return bad_request(request)
return redirect('basics:actofgoods_startpage')
@csrf_protect
def group_leave(request, pk):
if request.user.is_authenticated() and not request.user.is_superuser:
if not request.user.is_active:
return render(request, 'basics/verification.html', {'active':False})
if request.user.groups.filter(name=name).exists():
groupDa = get_object_or_404(Groupdata, pk=pk)
group = groupDa.group
group.user_set.remove(request.user)
group.save()
if len(group.user_set.all()) == 0:
group.delete()
return redirect('basics:home')
#=====================
# EXTRAS
#=====================
def getAddress(request):
try:
address = request.POST['address']
lat = request.POST['lat']
lng = request.POST['lng']
if not lat == "" and not lng == "":
lat = float(lat)
lng = float(lng)
elif address != "":
lat, lng = getLatLng(address)
else:
lat = None
lng = None
return lat, lng
except:
return None, None
def getLatLng(location):
location = location.replace(" ", "%20")
req = "https://maps.googleapis.com/maps/api/geocode/json?address=%s" % location #parameter
response = requests.get(req)
jsongeocode = response.json()
return jsongeocode['results'][0]['geometry']['location']['lat'], jsongeocode['results'][0]['geometry']['location']['lng']
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def sendmail(email, content, subject):
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg.attach(MIMEText(content))
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('actofgoods@gmail.com', 'actofgoods123')
mail.sendmail('actofgoods@gmail.com', email, msg.as_string())
print("message should have been sendd")
mail.close()
def send_notifications(needdata):
users_to_inform = needdata.categorie.userdata_set.all()
users_to_inform = filter(lambda x: x.adrAsPoint.distance(needdata.adrAsPoint)< x.aux, users_to_inform)
for user in users_to_inform:
sendmail(user.user.email, needdata.headline + "\n\n"+ needdata.text + "\n http://10.200.1.40/needs_help/%s" %(needdata.id), "Somebody needs your help: " + needdata.categorie.name )
#=====================
# PRIORITY
#=====================
def priority_need_user(x):
"""x is number of hours since need was posted"""
if x < 12 and x >= 0:
return pow(10, 4-(pow(x-12, 2)/144))
elif x >= 12:
return pow(10, 4-(pow((x-12)/6, 2)/144))
return 0
def priority_need_group(x):
if x < 12 and x >= 0:
return pow(10, 4-(pow(x-12, 2)/144)) + 1000
elif x >= 12:
return pow(11, 1-(pow(x-12, 2)/5184)) * 1000
return 0
def priority_info_user(x, likes):
"""x is number of hours since need was posted"""
if (x-(likes/60)) < 24 and x >= 0:
return (75000+likes)/15
elif (x-(likes/60)) >= 24:
return (75000+likes)/(x-9-(likes/60))
return 0
def priority_info_group(x, likes):
if (x-(likes/40)) < 24 and x >= 0:
return ((3060000/41)+(3*likes))/(24-(384/41))
elif (x-(likes/40)) >= 24:
return ((3060000/41)+(3*likes))/(x-(384/41)-(likes/40))
return 0
#=====================
# ERROR-PAGES
#=====================
def bad_request(request):
return render(request, 'basics/404.html', {'content': "400 - Bad Request"})
def permission_denied(request):
return render(request, 'basics/404.html', {'content': "403 - Permission denied"})
def page_not_found(request):
return render(request, 'basics/404.html', {'content': "404 - Page not found"})
def server_error(request):
return render(request, 'basics/404.html', {'content': "500 - Server-Error"})
| {
"repo_name": "actofgoods/actofgoods",
"path": "basics/views.py",
"copies": "1",
"size": "70821",
"license": "mit",
"hash": -6743720333300642000,
"line_mean": 44.6870967742,
"line_max": 254,
"alpha_frac": 0.5925157099,
"autogenerated": false,
"ratio": 3.8937152911420245,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49862310010420247,
"avg_score": null,
"num_lines": null
} |
from .forms import *
from .models import *
from django.contrib import admin
from django.core.exceptions import ValidationError
from django.forms import BaseInlineFormSet
from django.utils.translation import ugettext_lazy as _
admin.site.register(Type)
class InlineValidationDate(BaseInlineFormSet):
def clean(self):
super(InlineValidationDate, self).clean()
if any(self.errors):
return
previous_date = False
for form in self.forms:
start_date = form.cleaned_data.pop('departure', None)
end_date = form.cleaned_data.pop('arrival', None)
if previous_date and start_date and previous_date > start_date:
raise ValidationError(_("The departure date must be greater than the arrival date of the previous "
"route."))
previous_date = end_date
if start_date and end_date and start_date > end_date:
raise ValidationError(_("The arrival date can not be earlier than the departure date."))
class RouteInline(admin.TabularInline):
model = Route
extra = 1
form = RouteForm
formset = InlineValidationDate
verbose_name = _('Route')
verbose_name_plural = _('Routes')
class ScientificMissionAdmin(admin.ModelAdmin):
fields = ['person', 'amount_paid', 'mission', 'project_activity', 'destination_city']
list_display = ('id', 'person', 'value', 'mission', 'destination_city')
list_display_links = ('id',)
search_fields = ['person__full_name', 'mission__mission', 'project_activity__title']
inlines = (RouteInline,)
form = ScientificMissionForm
admin.site.register(ScientificMission, ScientificMissionAdmin)
| {
"repo_name": "neuromat/nira",
"path": "scientific_mission/admin.py",
"copies": "1",
"size": "1729",
"license": "mpl-2.0",
"hash": 1312383110231070000,
"line_mean": 33.58,
"line_max": 115,
"alpha_frac": 0.6622325043,
"autogenerated": false,
"ratio": 4.227383863080685,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0011272916243857739,
"num_lines": 50
} |
from forms import ParameterTypes
import sqlite3
DEF_SQLITE_TYPES = {
ParameterTypes.INTEGER : "INT",
ParameterTypes.FLOAT : "REAL",
ParameterTypes.BOOLEAN: "INT",
ParameterTypes.STRING: "TEXT",
ParameterTypes.LABEL: "TEXT",
ParameterTypes.URL: "TEXT",
ParameterTypes.ENUM: "INT",
}
def get_sqlite_term(info):
get_type = DEF_SQLITE_TYPES.get(info['kind'], 'TEXT')
return '"%s" %s' % (info['name'], get_type)
def format_location(tup):
from hn_utils.sequence_store import ucsc_browser_name_for_sequence_id
return "%s:%d-%d" % (ucsc_browser_name_for_sequence_id(tup[0]),tup[1], tup[2])
def format_html_url(s):
if "|" in s:
label, link = s.split('|',1)
else:
label = "Link"
link = s
return "<a target='_blank' href='%s'>%s</a>" % (link, label)
FORMATTERS = dict(location=format_location,
html_url=format_html_url)
class ResultTableVisibility(object):
VISIBLE = 0
HIDDEN = 10
LIMITED = 20 # Stuff already in the normal description
CHOICES = (
(VISIBLE, "Visible"),
(HIDDEN, "Hidden"),
(LIMITED, "Limited"),
)
class ResultTableIndex(object):
NONE = 0
NON_UNIQUE = 5
UNIQUE = 10
CHOICES = (
(NONE, "None"),
(NON_UNIQUE, "Non Unique"),
(UNIQUE, "Unique"),
)
class ResultInterface(object):
def _setup_access(self):
pass
def __init__(self, file_path, headers):
self.headers = [dict(name='rowid',
visibility=ResultTableVisibility.HIDDEN,
display_name='Row ID',
kind = ParameterTypes.INTEGER)]
self.headers.extend(headers)
self.file_path = file_path
self.view_info = None
self.header_dict = dict(rowid=self.headers[0])
self.header_indicies = dict(rowid=0)
for idx, x in enumerate(self.headers):
self.header_dict[x['name']] = x
self.header_indicies[x['name']] = idx
self.db = sqlite3.connect(self.file_path)
self.cur = self.db.cursor()
self._setup_access()
def get_display_headers(self):
def get_display_name(v):
if 'display_name' in v:
return v['display_name']
return self.header_dict[v['name']]['display_name']
if not self.view_info:
return [(x['name'],x['display_name']) for x in self.headers if x.get('visibility',-1) != ResultTableVisibility.HIDDEN]
else:
return [(x['name'], get_display_name(x)) for x in self.view_info]
def close(self):
self.cur.close()
self.db.commit()
self.db.close()
OP_OP_DICT = dict(GE='>=', LE='<=', EQ='=', IN='IN')
ESCAPED_TYPES = [ParameterTypes.STRING, ParameterTypes.URL, ParameterTypes.URL]
class ResultReadInterface(ResultInterface):
def _setup_access(self):
self.filters = []
self.filter_clause = ""
def _get_all_headers(self):
return ",".join([x['name'] for x in self.headers])
def _tuple_to_dict(self, tup, show_all=False):
dd = {}
for idx, h in enumerate(self.headers):
if show_all or self.headers[idx].get('visibility',0) != ResultTableVisibility.HIDDEN:
dd[str(h['name'])] = tup[idx]
return dd
def _interpret_term(self, term,idx, for_csv):
if self.headers[idx]['kind'] == ParameterTypes.ENUM:
term = dict(self.headers[idx]['enum_labels'])[int(term)]
if self.headers[idx]['kind'] == ParameterTypes.URL:
if "|" in term:
label, link = term.split('|',1)
else:
label = "Link"
link = term
term = "<a target='_blank' href='%s'>%s</a>" % (link, label) if not for_csv else link
return term
def _get_filter_for_ops(self, p, escape_value=True):
if escape_value:
return '"%s" %s \'%s\'' % (p[0], OP_OP_DICT[p[1]], str(p[2]))
else:
return '"%s" %s %s' % (p[0], OP_OP_DICT[p[1]], str(p[2]))
def add_filter(self, filter_def):
field, op , value = filter_def.split('~') if type(filter_def) in [str, unicode] else filter_def
if field in self.header_dict:
self.filters.append((field, op, value))
needs_escape = self.header_dict[field]['kind'] in ESCAPED_TYPES
self.filter_clause = "WHERE %s" % " AND ".join([self._get_filter_for_ops(f, escape_value=needs_escape) for f in self.filters])
def clear_filters(self):
self.filters = []
self.filter_clause = ""
def get_result_tuples(self, sort_terms=(), offset=0, limit=0):
sort_clause = ""
if sort_terms:
sort_clause = "ORDER BY " + ", ".join(['"%s" %s' % term for term in sort_terms])
if limit:
sort_clause += " LIMIT %d" % limit
if offset:
sort_clause += " OFFSET %d" % offset
full_clause = "SELECT rowid,* from RESULT %s %s;" % (self.filter_clause, sort_clause)
try:
self.cur.execute(full_clause)
return self.cur.fetchall()
except:
return ()
def get_dict_for_tuple(self, tup):
return self._tuple_to_dict(tup, show_all=True)
def get_item_count(self):
try:
sql= "SELECT COUNT(*) from RESULT %s;" % self.filter_clause
self.cur.execute(sql)
return self.cur.fetchone()[0]
except:
return 0
def get_result_tuple(self, item_index):
sql= "SELECT rowid,* FROM RESULT WHERE rowid=?"
self.cur.execute(sql,(item_index,))
return self.cur.fetchone()
def get_result_dict(self, item_index):
return self._tuple_to_dict(self.get_result_tuple(item_index))
def get_result_info_at_index(self, item_index):
tup = self.get_result_tuple(item_index)
rval = []
for idx,item in enumerate(tup):
if self.headers[idx].get('visibility',0) != ResultTableVisibility.VISIBLE:
continue
rval.append((self.headers[idx]['display_name'], self._interpret_term(tup[idx], idx, False)))
return rval
def set_view_info(self, view_info):
self.view_info = view_info
def _get_formatted_item(self, x, value, for_csv=False):
if x.get('format', None):
fmt = x['format']
if fmt in FORMATTERS:
term = FORMATTERS[fmt](value)
elif callable(fmt):
term = fmt(value)
else:
term = fmt % value
return term
elif x['kind'] == ParameterTypes.BOOLEAN:
return "Y" if int(value) else "N"
elif x['kind'] == ParameterTypes.ENUM:
return dict(x['enum_labels'])[int(value)]
elif x['kind'] == ParameterTypes.URL:
if "|" in value:
label, link = value.split('|',1)
else:
label = "Link"
link = value
return "<a target='_blank' href='%s'>%s</a>" % (link, label) if not for_csv else link
return unicode(value)
def interpret_tuple(self, tup, for_csv=False, show_hidden=False):
l = []
#
# Allow for a fancier interpretation of the data than normal
#
if self.view_info:
for view_item in self.view_info:
if view_item.get('group', None):
# assemble the group items
items = tuple([tup[self.header_indicies[term]] for term in view_item['group']])
else:
items = tup[self.header_indicies[view_item['name']]]
# combine info from the view and the data description to get the control info
info = dict(self.header_dict.get(view_item['name'],{}).items() + view_item.items())
term = self._get_formatted_item(info, items)
l.append(term)
else:
for idx, term in enumerate(tup):
if not show_hidden and self.headers[idx].get('visibility',0) == ResultTableVisibility.HIDDEN:
continue
term = self._get_formatted_item(self.headers[idx], term, for_csv )
l.append(term)
return tuple(l)
def get_result_dicts(self, sort_terms=(), offset=0, limit=0):
return [self._tuple_to_dict(x) for x in self.get_result_tuples(sort_terms=sort_terms, offset=offset, limit=limit)]
class ResultWriteInterface(ResultInterface):
def _setup_access(self):
sql = "CREATE TABLE RESULT( %s );" % ", ".join([get_sqlite_term(x) for x in self.headers[1:]])
self.cur.execute(sql)
for x in self.headers:
if x.get('index', ResultTableIndex.NONE) != ResultTableIndex.NONE:
unique = "UNIQUE" if x['index'] == ResultTableIndex.UNIQUE else ""
sql = "CREATE %s INDEX %s_idx on RESULT (%s)" % (unique, x['name'], x['name'])
self.cur.execute(sql)
fields = ", ".join(["'%s'" % x['name'] for x in self.headers[1:]])
values = ", ".join([':%s' % x['name'] for x in self.headers[1:]])
self.sql_insert = "INSERT INTO RESULT(%s) VALUES (%s);" % (fields, values)
def add_result(self, info_dict):
self.cur.execute(self.sql_insert, info_dict)
return self.cur.lastrowid
def flush(self):
self.db.commit()
def create_result_writer(file_path, headers):
return ResultWriteInterface(file_path, headers)
def create_result_reader(file_path, headers):
return ResultReadInterface(file_path, headers)
| {
"repo_name": "bricetebbs/dj_extras",
"path": "result_table.py",
"copies": "1",
"size": "9695",
"license": "mit",
"hash": 7626261537869089000,
"line_mean": 30.5798045603,
"line_max": 138,
"alpha_frac": 0.5565755544,
"autogenerated": false,
"ratio": 3.613492359299292,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4670067913699292,
"avg_score": null,
"num_lines": null
} |
from .forms import ParticipantForm
from misc.views import AbstractEditView, AbstractDeleteView
from django.shortcuts import render, redirect
from .models import Participation
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
import logging
log = logging.getLogger('participation.views')
@login_required
def show_participations(request):
present_participations = Participation.objects.present_with_req(request)
user = request.user
conf = request.conference
old_participations = None
if request.user.last_conference is None:
user.last_conference = conf
user.save()
elif user.last_conference.id != conf.id:
old_participations = Participation.objects.old_with_req(request)
if len(old_participations) == 0:
user.last_conference = conf
user.save()
return render(request, "panel/participation/show.html", {
'old_participations': old_participations,
'participations': present_participations.all()
})
@login_required
def restore_participations(request, is_true):
user = request.user
conf = request.conference
user.last_conference = conf
user.save()
if is_true == "yes":
Participation.objects\
.old_participations(request).update(conference=conf)
return redirect("participation:show")
class ParticipationView(object):
model_class = Participation
redirect_url = "participation:show"
def get_obj(self, request, pk, *args, **kwargs):
if pk:
obj = self.model_class.objects.present_with_req(request).get(pk=pk)
return obj.participant
else:
return None
class EditParticipationView(ParticipationView, AbstractEditView):
form_class = ParticipantForm
template_name = "panel/participation/edit.html"
def save(self, request, form, *args, **kwargs):
participant = form.instance
if participant.pk is None:
participant.user = request.user
participant.save()
participation = Participation.objects.create(
participant=participant,
conference=request.conference
)
participation.save()
else:
form.save()
def generate_successful_msg(self, request, obj, *args, **kwargs):
if obj.pk is None:
msg = _("New participant '%s' was addded")
else:
msg = _("Participant '%s' was changed")
return msg % obj.full_name
edit_participation = EditParticipationView.as_view()
class DeleteParticipationView(ParticipationView, AbstractDeleteView):
template_name = "panel/participation/delete.html"
def generate_successful_msg(self, request, obj, *args, **kwargs):
return _("Participant '%s' was deleted") % obj.full_name
delete_participation = DeleteParticipationView.as_view()
| {
"repo_name": "firemark/yellowjuice",
"path": "participation/views.py",
"copies": "1",
"size": "2937",
"license": "mit",
"hash": -7863975877307466000,
"line_mean": 28.37,
"line_max": 79,
"alpha_frac": 0.669731018,
"autogenerated": false,
"ratio": 3.74140127388535,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9909311702676479,
"avg_score": 0.0003641178417742469,
"num_lines": 100
} |
from ..forms import PostForm, CommentForm
from ..database import db, Extension, Post, Comment, Tag
from flask_login import current_user, current_app, login_required
from flask import Blueprint, render_template, redirect, url_for, flash, \
request, abort, make_response
blueprint = Blueprint('posts', __name__, url_prefix='/posts')
@blueprint.route('/')
def index():
show_followed = False
if current_user.is_authenticated:
show_followed = bool(request.cookies.get('show_followed', ''))
if show_followed:
query = current_user.followed_posts
else:
query = Post.query
page = request.args.get('page', default=1, type=int)
per_page = current_app.config['POSTS_PER_PAGE']
posts = query.order_by(Post.pub_time.desc())
pagination = posts.paginate(page, per_page, error_out=False)
posts = pagination.items
return render_template('posts/index.html', show_followed=show_followed,
posts=posts, pagination=pagination)
@blueprint.route('/new', methods=['GET', 'POST'])
@login_required
def add_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data,
body=form.body.data,
author=current_user._get_current_object())
for name in form.tags.data.replace(' ', '').split(','):
tag = Tag.query.filter_by(name=name).first() or Tag(name)
post.tags.append(tag)
db.session.add(post)
flash('New post added successfully!', 'success')
return redirect(url_for('.index'))
posts = Post.query.order_by(Post.pub_time.desc()).all()
return render_template('posts/new.html', form=form, posts=posts)
@blueprint.route('/<int:post_id>', methods=['GET', 'POST'])
def show_post(post_id):
post = Post.query.get_or_404(post_id)
form = CommentForm()
if form.validate_on_submit():
if current_user.is_anonymous:
flash('Please log in to write comments.', 'info')
# TODO: Save user input before redirect
# return redirect(url_for('auth.login', next=request.url))
else:
comment = Comment(body=form.body.data,
post_id=post.id,
author=current_user._get_current_object())
db.session.add(comment)
return redirect(url_for('.show_post', post_id=post.id, page=-1))
page = request.args.get('page', 1, type=int)
per_page = current_app.config['COMMENTS_PER_PAGE']
if page == -1:
page = (post.comments.count() - 1) // per_page + 1
comments = post.comments.order_by(Comment.pub_time.desc())
pagination = comments.paginate(page, per_page, error_out=False)
comments = pagination.items
tags = post.tags.all()
return render_template('posts/post.html', post=post, form=form, tags=tags,
page=page, comments=comments, pagination=pagination)
@blueprint.route('/<int:post_id>/edit', methods=['GET', 'POST'])
@login_required
def edit_post(post_id):
post = Post.query.get_or_404(post_id)
if current_user != post.author:
abort(403)
form = PostForm()
if form.validate_on_submit():
post.title = form.title.data
post.body = form.body.data
db.session.add(post)
flash('Post updated successfully!', 'success')
return redirect(url_for('.show_post', post_id=post_id))
form.title.data = post.title
form.body.data = post.body
form.tags.data = post.tags.all()
return render_template('posts/edit.html', form=form)
@blueprint.route('/all_posts')
@login_required
def show_all_posts():
resp = make_response(redirect(url_for('.index')))
resp.set_cookie('show_followed', '', 30*24*60*60)
return resp
@blueprint.route('/followed_posts')
@login_required
def show_followed_posts():
resp = make_response(redirect(url_for('.index')))
resp.set_cookie('show_followed', '1', 30*24*60*60)
return resp
@blueprint.route('/tag=<tag_name>')
def filter_by_tag(tag_name):
tag = Tag.query.filter_by(name=tag_name).first_or_404()
posts = tag.posts.all()
extension = Extension.query.filter_by(name=tag_name).first()
return render_template('posts/tag.html', tag=tag, posts=posts,
extension=extension)
@blueprint.route('/delete/<int:post_id>')
@login_required
def delete_post(post_id):
post = Post.query.get_or_404(post_id)
if current_user != post.author:
abort(403)
db.session.delete(post)
return redirect(url_for('posts.index'))
@blueprint.route('/tag_posts/<tag_name>')
def tag_posts(tag_name):
tag = Tag.query.filter_by(name=tag_name).first_or_404()
posts = tag.posts.all()
count = tag.posts.count()
return render_template('posts/tag_posts.html', tag=tag, posts=posts,
count=count)
@blueprint.route('/all_tags')
def show_all_tags():
tags = Tag.query.order_by(Tag.id.desc())
return render_template('posts/all_tags.html', tags=tags)
| {
"repo_name": "john-wei/flaskr",
"path": "package/views/posts.py",
"copies": "1",
"size": "5057",
"license": "mit",
"hash": 3908592658347787000,
"line_mean": 35.1214285714,
"line_max": 79,
"alpha_frac": 0.6288313229,
"autogenerated": false,
"ratio": 3.463698630136986,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.45925299530369856,
"avg_score": null,
"num_lines": null
} |
from .forms import ProfileForm
from .models import Profile
from django.db.models import Count
from app_forum.models import Forum, Comment
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
def author_single_view(request, slug):
"""
Render Single User
:param request:
:param slug:
:return:
"""
author = get_object_or_404(Profile, slug=slug)
author_forum_list = Forum.objects.filter(forum_author=author.id).order_by("-is_created")[:10]
author_comments = Comment.objects.filter(comment_author=author.id).order_by("-is_created")[:10]
total_forums = Forum.objects.filter(forum_author=author.id).annotate(num_comments=Count('forum_author'))
total_comments = Comment.objects.filter(comment_author=author.id).annotate(num_comments=Count('comment_author'))
template = 'app_author/author_single.html'
context = {
'author': author,
'author_forum_list': author_forum_list,
'author_comments': author_comments,
'total_forums': total_forums,
'total_comments': total_comments
}
return render(request, template, context)
@login_required
def author_edit_view(request, slug):
"""
Render User Edit Form
:param request:
:param slug:
:return:
"""
author = get_object_or_404(Profile, slug=slug)
if request.method == "POST":
form = ProfileForm(request.POST, request.FILES, instance=author)
if form.is_valid():
author = form.save(commit=False)
author.save()
return redirect('author:author_single', slug=slug)
elif request.user != author.user:
return redirect('forum:forum_list')
else:
form = ProfileForm(instance=author)
return render(request, 'app_author/author_edit.html', {'author': author, 'form': form})
| {
"repo_name": "django-id/website",
"path": "app_author/views.py",
"copies": "1",
"size": "1872",
"license": "mit",
"hash": 5377842436916510000,
"line_mean": 35.7058823529,
"line_max": 116,
"alpha_frac": 0.6741452991,
"autogenerated": false,
"ratio": 3.6923076923076925,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9861669171081844,
"avg_score": 0.0009567640651697729,
"num_lines": 51
} |
from .forms import RegisterForm, LoginForm, PasswordResetForm, \
PasswordChangeForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, \
login as django_login, logout as django_logout
from .models import PasswordResetToken
import uuid
from django.contrib import messages
from django.utils.translation import ugettext as _
def register(request):
form = RegisterForm()
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
data = form.cleaned_data
user = User.objects.create_user(username=data["username"],
email=data.get("email", ""),
password=data["password1"])
auth_user = authenticate(username=data["username"],
password=data["password1"])
django_login(request, auth_user)
return HttpResponseRedirect(reverse("dashboard"))
return render_to_response("accounts/register.html",
{"form": form},
context_instance=RequestContext(request))
def login(request):
form = LoginForm()
if request.method == "POST":
form = LoginForm(request.POST)
if form.is_valid():
data = form.cleaned_data
auth_user = authenticate(username=data["username"],
password=data["password"])
django_login(request, auth_user)
return HttpResponseRedirect(reverse("dashboard"))
return render_to_response("accounts/login.html", {"form": form},
context_instance=RequestContext(request))
def logout(request):
django_logout(request)
return HttpResponseRedirect(reverse("accounts_login"))
def password_reset(request):
form = PasswordResetForm()
if request.method == "POST":
form = PasswordResetForm(request.POST)
if form.is_valid():
user = User.objects.get(email=form.cleaned_data["email"])
PasswordResetToken.objects.create(user=user, token=str(uuid.uuid4()))
messages.add_message(request, messages.SUCCESS,
_("Password reset email has been sent successfully"))
return render_to_response("accounts/password_reset.html", {"form": form},
context_instance=RequestContext(request))
def password_reset_confirm(request, token=None):
if not token:
messages.add_message(request, messages.ERROR,
_("Invalid Token"))
return HttpResponseRedirect(reverse("accounts_login"))
try:
token = PasswordResetToken.objects.get(token=token)
except PasswordResetToken.DoesNotExist:
messages.add_message(request, messages.ERROR,
_("Invalid Token"))
return HttpResponseRedirect(reverse("accounts_login"))
form = PasswordChangeForm(initial={"token": token.token})
if request.method == "POST":
form = PasswordChangeForm(request.POST)
if form.is_valid():
token.user.set_password(form.cleaned_data["password1"])
token.user.save()
token.delete()
messages.add_message(request, messages.SUCCESS,
_("Password has been successfully changed."))
return HttpResponseRedirect(reverse("accounts_login"))
return render_to_response("accounts/password_reset_form.html",
{"form": form,
"password_token": token.token},
context_instance=RequestContext(request))
| {
"repo_name": "theju/f1oracle",
"path": "accounts/views.py",
"copies": "1",
"size": "3911",
"license": "bsd-3-clause",
"hash": -7807126261808822000,
"line_mean": 45.0117647059,
"line_max": 86,
"alpha_frac": 0.6090513935,
"autogenerated": false,
"ratio": 4.938131313131313,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002584442414110486,
"num_lines": 85
} |
from forms import RegistrationForm
from app import app, db
from models import User
from flask import render_template, jsonify
@app.route('/', methods=['GET'])
@app.route('/index', methods=['GET'])
def index():
form = RegistrationForm()
return render_template('register.html',
title='Home',
form=form
)
@app.route('/register', methods=['POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit():
user = User(
first_name = form.first_name.data,
last_name = form.last_name.data,
email = form.email.data,
password = form.password.data
)
user.hash_password()
db.session.add(user)
db.session.commit()
return jsonify({ 'code' : 200, 'status' : 'success' , 'data' : 'Registration Successfull.' })
form_errors = {}
for field, errors in form.errors.items():
for error in errors:
title = getattr(form, field).label.text
form_errors[title] = error
return jsonify({ 'code' : 400, 'status' : 'failure' , 'data' : form_errors })
| {
"repo_name": "ibrahim12/challeng_demo",
"path": "app/views.py",
"copies": "1",
"size": "1157",
"license": "mit",
"hash": -1172043712740388900,
"line_mean": 28.6666666667,
"line_max": 101,
"alpha_frac": 0.5738980121,
"autogenerated": false,
"ratio": 4.031358885017422,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.014979902817563095,
"num_lines": 39
} |
from .forms import RegistrationForm
from django.contrib.auth.decorators import login_required # helps wrap views with login_required
from django.contrib.auth import logout # to allow views logout functionality
from django.views.decorators.csrf import csrf_protect # protect forms with csrf tokens
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render
from django.contrib.auth.models import User
from admins.models import AvailableProject
### register/01: View to display and handle registering a new user
@csrf_protect
def register(request):
# display view depending on whether
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid(): # check form validity using check username/pw
# Create a user object using django authentication
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email'],
)
return HttpResponseRedirect('accounts/success/')
else:
form = RegistrationForm()
return render(request, 'accounts/register.html', {'form': form})
### register/02: show registration success
def register_success(request):
return render(request, 'accounts/success.html')
### 01: show initial landing page for logged in users
@login_required
def home(request):
projects = AvailableProject.objects.all().order_by('-published_date')
return render(request, 'accounts/home.html', {'user': request.user,
'projects': projects}) | {
"repo_name": "adam2392/smile",
"path": "smile/accounts/views.py",
"copies": "1",
"size": "1565",
"license": "apache-2.0",
"hash": -6123291430369172000,
"line_mean": 34.5909090909,
"line_max": 96,
"alpha_frac": 0.7610223642,
"autogenerated": false,
"ratio": 4.05440414507772,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.026178868153575133,
"num_lines": 44
} |
from .forms import SchoolFilterForm, LimitedDistictFilterForm,\
RolesFilterForm, ReporterFreeSearchForm, SchoolDistictFilterForm, FreeSearchSchoolsForm, MassTextForm
from .models import EmisReporter, School
from .reports import messages, othermessages, reporters, all_schools
from .sorters import LatestSubmissionSorter
from .views import *
from water_polls_views import schedule_water_polls, detail_water_view, district_water_view
from violence_view import detailed_violence_view
from contact.forms import\
FreeSearchTextForm, DistictFilterMessageForm, HandledByForm, ReplyTextForm
from django.conf.urls.defaults import *
from generic.sorters import SimpleSorter
from generic.views import generic, generic_row
from rapidsms_httprouter.models import Message
from django.contrib.auth.views import login_required
from django.contrib.auth.models import User
from .views import ReporterDetailView
urlpatterns = patterns('',
url(r'^edtrac/messages/$', login_required(generic), {
'model':Message,
'queryset':messages,
'filter_forms':[FreeSearchTextForm, DistictFilterMessageForm,LastReportingDateFilterForm,PollFilterForm],
'action_forms':[ReplyTextForm],
'objects_per_page':25,
'partial_row' : 'education/partials/messages/message_row.html',
'partial_header':'education/partials/messages/message_partial_header.html',
'base_template':'education/partials/contact_message_base.html',
# 'paginator_template' : 'education/partials/pagination.html',
'title' : 'Messages',
'columns':[('Incoming Text', True, 'text', SimpleSorter()),
('Reporter', True, 'connection__contact__name', SimpleSorter(),),
('Number', True, 'connection__identity', SimpleSorter()),
('Poll', True, 'poll_responses.all()[0].poll', SimpleSorter(),),
('School',False,'connection__contact__emisreporter__schools',None,),
('District',True,'connection__contact__reporting_location',SimpleSorter(),),
('Reporting Date', True, 'date', SimpleSorter(),),
],
'sort_column':'date',
'sort_ascending':False,
'management_for': 'messages'
}, name="emis-messagelog"),
url(r'^edtrac/error_messages/$', login_required(error_messages_as_json), name="error_messages"),
url(r'^edtrac/other-messages/$', login_required(generic), {
'model':Message,
'queryset':othermessages,
'filter_forms':[FreeSearchTextForm, DistictFilterMessageForm, HandledByForm],
'action_forms':[ReplyTextForm],
'objects_per_page':25,
'partial_row' : 'education/partials/messages/message_row.html',
'base_template':'education/partials/contact_message_base.html',
'paginator_template' : 'education/partials/pagination.html',
'title' : 'Messages',
'columns':[('Text', True, 'text', SimpleSorter()),
('Contact Information', True, 'connection__contact__name', SimpleSorter(),),
('Date', True, 'date', SimpleSorter(),),
('Type', True, 'application', SimpleSorter(),),
('Response', False, 'response', None,),
],
'sort_column':'date',
'sort_ascending':False,
}, name="emis-other-messages"),
url(r'^edtrac/messagelog/(?P<error_msgs>\d+)/', login_required(generic), {
'model':Message,
'queryset':messages,
'filter_forms':[FreeSearchTextForm, DistictFilterMessageForm, HandledByForm],
'action_forms':[ReplyTextForm],
'objects_per_page':25,
'partial_row':'education/partials/message_row.html',
'base_template':'education/messages_base.html',
'columns':[('Text', True, 'text', SimpleSorter()),
('Contact Information', True, 'connection__contact__name', SimpleSorter(),),
('Date', True, 'date', SimpleSorter(),),
('Type', True, 'application', SimpleSorter(),),
('Response', False, 'response', None,),
],
'sort_column':'date',
'sort_ascending':False,
}, name="emis-messagelog"),
url(r'^edtrac/control-panel/$',control_panel,name="control-panel"),
url(r'^edtrac/quitters/$',quitters, name="quitters"),
url(r'^edtrac/audit-trail/$', audit_trail, name="emis-audittrail"), #AuditTrail.as_view(), name="emis-audittrail"),
#reporters
url(r'^edtrac/reporter/$', login_required(generic), {
'model':EmisReporter,
'queryset':reporters,
'filter_forms':[ReporterFreeSearchForm, RolesFilterForm, LimitedDistictFilterForm, SchoolFilterForm,LastReportingDateFilterForm],
'action_forms':[MassTextForm],
'objects_per_page':25,
'title' : 'Reporters',
'partial_row':'education/partials/reporters/reporter_row.html',
'partial_header':'education/partials/reporters/reporter_partial_header.html',
'base_template':'education/partials/contact_message_base.html',
'results_title':'Reporters',
'columns':[('Name', True, 'name', SimpleSorter()),
('Number', True, 'connection__identity', SimpleSorter()),
('Grade', True, 'grade', SimpleSorter()),
('Gender', True, 'gender', SimpleSorter()),
('Role(s)', True, 'groups__name', SimpleSorter(),),
('District', False, 'district', None,),
('Last Reporting Date', True, 'latest_submission_date', LatestSubmissionSorter(),),
('School(s)', True, 'schools__name', SimpleSorter(),),
# ('Location', True, 'reporting_location__name', SimpleSorter(),),
('', False, '', None,)],
'management_for': 'reporters'
}, name="emis-contact"),
url(r'^edtrac/scripts-special/$', emis_scripts_special, name='emis-special-scripts'),
url(r'^edtrac/new-comment/$', new_comment, name='new-comment'),
url(r'^edtrac/comments/$', comments, name='comments'),
url(r'^edtrac/reporter/(\d+)/edit/', edit_reporter, name='edit-reporter'),
url(r'^edtrac/reporter/(\d+)/delete/', delete_reporter, name='delete-reporter'),
url(r'^edtrac/reporter/(?P<pk>\d+)/$', ReporterDetailView.as_view(), name="reporter-detail"),
url(r'^edtrac/reporter/(?P<pk>\d+)/show', generic_row, {'model':EmisReporter, 'partial_row':'education/partials/reporters/reporter_row.html'}),
url(r'^edtrac/ht_attendance/$', htattendance, {}, name='ht-attendance-stats'),
url(r'^edtrac/ht_attendance/(?P<start_date>[0-9\-]+)/(?P<end_date>[0-9\-]+)$', htattendance, {}, name='ht-attendance-stats'),
url(r'^edtrac/gemht_attendance/$', gem_htattendance, {}, name='gemht-attendance-stats'),
url(r'^edtrac/gemht_attendance/(?P<start_date>[0-9\-]+)/(?P<end_date>[0-9\-]+)$', gem_htattendance, {}, name='gemht-attendance-stats'),
url(r'^edtrac/meals/$', meals, {}, name='meals-stats'),
url(r'^$', dashboard, name='rapidsms-dashboard'),
url(r'^emis/whitelist/', whitelist),
url(r'^connections/add/', add_connection),
url(r'^connections/(\d+)/delete/', delete_connection),
url(r'^edtrac/deo_dashboard/', login_required(deo_dashboard), {}, name='deo-dashboard'),
url(r'^edtrac/school/$', login_required(generic), {
'model':School,
'queryset':all_schools,
'filter_forms':[FreeSearchSchoolsForm, SchoolDistictFilterForm],
'objects_per_page':25,
'partial_row':'education/partials/school_row.html',
'partial_header':'education/partials/school_partial_header.html',
'base_template':'education/schools_base.html',
'results_title':'Schools',
'columns':[('Name', True, 'name', SimpleSorter()),
('District', True, 'location__name', None,),
# ('School ID', False, 'emis_id', None,),
('Head Teacher', False, 'emisreporter', None,),
('Contact Number', True, 'emisreporter__identity', SimpleSorter()),
('Reporters', False, 'emisreporter', None,),
('', False, '', None,)
],
'sort_column':'date',
'sort_ascending':False,
'management_for': 'schools'
}, name="emis-schools"),
url(r'^edtrac/(\d+)/district-detail-boysp3/', boysp3_district_attd_detail, {}, name="boysp3-district-attd-detail"),
url(r'^edtrac/(\d+)/district-detail-boysp6/', boysp6_district_attd_detail, {}, name="boysp6-district-attd-detail"),
url(r'^edtrac/(\d+)/district-detail-girlsp3/', girlsp3_district_attd_detail, {}, name="girlsp3-district-attd-detail"),
url(r'^edtrac/(\d+)/district-detail-girlsp6/', girlsp6_district_attd_detail, {}, name="girlsp6-district-attd-detail"),
url(r'^edtrac/(\d+)/district-detail-female-teachers/', female_t_district_attd_detail, {}, name="female-teacher-district-attd-detail"),
url(r'^edtrac/(\d+)/district-detail-male-teachers/', male_t_district_attd_detail, {}, name="male-teacher-district-attd-detail"),
url(r'^edtrac/(\d+)/school_detail/', school_detail, {}, name='school-detail'),
url(r'^edtrac/add_schools/', login_required(add_schools), {}, name='add-schools'),
url(r'^edtrac/school/(\d+)/edit/', edit_school, name='edit-school'),
url(r'^edtrac/school/(?P<pk>\d+)/delete/', delete_school, name='delete-school'),
url(r'^edtrac/school/(?P<pk>\d+)/show', generic_row, {'model':School, 'partial_row':'education/partials/school_row.html'}, name='show-school'),
url(r'^edtrac/attd/boys-p3/$', time_range_boysp3, name='boys-p3-range' ),
url(r'^edtrac/attd/boys-p6/$', time_range_boysp6, name="boys-p6-range"),
url(r'^edtrac/attd/girls-p3/$', time_range_girlsp3, name="girls-p3-range"),
url(r'^edtrac/attd/girls-p6/$', time_range_girlsp6, name="girls-p6-range"),
url(r'^edtrac/attd/m-teachers/$', time_range_teachers_m, name="m-teachers-range"),
url(r'^edtrac/attd/f-teachers/$', time_range_teachers_f, name="f-teachers-range"),
url(r'^edtrac/attd/head-teachers/$', time_range_head_teachers, name="head-teachers-range"),
url(r'^edtrac/othermessages/$', login_required(generic), {
'model':Message,
'queryset':othermessages,
'filter_forms':[FreeSearchTextForm, DistictFilterMessageForm, HandledByForm],
'action_forms':[ReplyTextForm],
'objects_per_page':25,
'partial_row':'education/partials/other_message_row.html',
'base_template':'education/messages_base.html',
'columns':[('Text', True, 'text', SimpleSorter()),
('Contact Information', True, 'connection__contact__name', SimpleSorter(),),
('Date', True, 'date', SimpleSorter(),),
],
'sort_column':'date',
'sort_ascending':False,
}, name="emis-othermessages"),
# Excel Reports
url(r'^edtrac/excelreports/$',excel_reports),
url(r'^edtrac/system-report/$', system_report, name="system-report"),
#users and permissions
url(r'^edtrac/toexcel/$',to_excel, name="to-excel"),
# url(r'edtrac/schoolexcel/$', base.RedirectView(url='/static/reporters.xls'), name="school_report_excel"),
url(r'^edtrac/schoolexcel/$', school_reporters_to_excel, name="school_report_excel"),
url(r'^edtrac/toexcel/(?P<start_date>[0-9\-]+)/(?P<end_date>[0-9\-]+)$',to_excel, name="to-excel"),
url(r'^edtrac/users/(\d+)/edit/', edit_user, name='edit_user'),
url(r'^edtac/users/add/', edit_user, name='add_user'),
#user alerts
url(r'^edtrac/alert-messages/$', alert_messages, name='alert-messages'),
url(r'^edtrac/user/$', login_required(generic), {
'model':User,
'objects_per_page':25,
'partial_row':'education/partials/user_row.html',
'partial_header':'education/partials/user_partial_header.html',
'base_template':'education/users_base.html',
'results_title':'Managed Users',
'user_form':UserForm(),
'columns':[('Username', True, 'username', SimpleSorter()),
('Email', True, 'email', None,),
('Name', False, 'first_name', None,),
('Role', False, 'profile__role', None,),
('Location', False, 'profile__location', None,),
('Action', False, '', None,),
],
'sort_column':'date',
'sort_ascending':False,
'management_for': 'users',
}, name="emis-users"),
#Admin Dashboard
#TODO protect views here...
url(r'^edtrac/dash_map/$', dash_map, {}, name="emis-dash-map"),
url(r'^edtrac/dash_attdance/$', dash_attdance, {}, name="emis-dash-attdance"),
# attendance views for all roles ---> data prepopulated by location
url(r'^edtrac/dash/boys-p3/attendance/$', boys_p3_attendance, {}, name="boys-p3"),
url(r'^edtrac/dash/boys-p6/attendance/$', boys_p6_attendance, {}, name="boys-p6"),
url(r'^edtrac/dash/girls-p3/attendance/$', girls_p3_attendance, {}, name="girls-p3"),
url(r'^edtrac/dash/girls-p6/attendance/$', girls_p6_attendance, {}, name="girls-p6"),
url(r'^edtrac/dash/teacher-female/attendance/$', female_teacher_attendance, {}, name="f-teachers"),
url(r'^edtrac/dash/teacher-male/attendance/$', male_teacher_attendance, {}, name="m-teachers"),
url(r'^edtrac/dash/head-teacher-male/attendance/$', male_head_teacher_attendance, {}, name="m-h-teachers"),
url(r'^edtrac/dash/head-teacher-female/attendance/$', female_head_teacher_attendance, {}, name="f-h-teachers"),
# end attendance views
url(r'^edtrac/dash-admin-meetings/$', dash_admin_meetings, {}, name="emis-dash-admin-meetings"),
url(r'^edtrac/dash-district-meetings/(?P<district_name>\w+)/$', dash_district_meetings, {}, name="emis-district-meetings"),
url(r'^edtrac/dash_ministry_map/$', dash_ministry_map, {}, name="emis-ministry-dash-map"),
url(r'^edtrac/dash-admin-progress/$', curriculum_progress, name="emis-admin-curriculum-progress"),
url(r'^edtrac/dash-admin-progress/district/(?P<district_pk>\d+)/$', curriculum_progress,
name="emis-admin-curriculum-progress-district"),
url(r'^edtrac/violence-admin-details/$', violence_details_dash, name="violence-admin-details"),
url(r'^edtrac/attendance-admin-details/$', AttendanceAdminDetails.as_view(), name="attendance-admin-details"),
# to find out about violence in a district
url(r'^edtrac/violence/district/(?P<pk>\d+)/$', DistrictViolenceDetails.as_view(), name="district-violence"),
url(r'^edtrac/violence-community/district/(?P<pk>\d+)/$', DistrictViolenceCommunityDetails.as_view(template_name =\
"education/dashboard/district_violence_community_detail.html"), name="district-violence-community"),
url(r'^edtrac/violence_deo_details/$', ViolenceDeoDetails.as_view(), name="violence-deo-details"),
url(r'^edtrac/dash_ministry_attdance/$', dash_attdance, {}, name="emis-ministry-dash-attdance"),
#DEO dashboard
url(r'^edtrac/dash_deo_map/$', dash_ministry_map, {}, name="emis-deo-dash-map"),
url(r'^edtrac/dash_deo_attdance/$', dash_attdance, {}, name="emis-deo-dash-attdance"),
#National statistics
url(r'^edtrac/national-stats/$', login_required(NationalStatistics.as_view()), name="emis-national-stats"),
url(r'^edtrac/capitation-grants(?:/(?P<term>[a-zA-Z]+))?/$',
login_required(CapitationGrants.as_view(template_name='education/admin/capitation_grants.html', poll_name='edtrac_upe_grant',
restrict_group='Head Teachers')), name="emis-grants"),
url(r'^edtrac/smc-capitation-grants/$',
login_required(CapitationGrants.as_view(template_name='education/admin/smc_capitation_grants.html',
poll_name='edtrac_smc_upe_grant', restrict_group='SMC')), name="emis-smc-grants"),
#PROGRESS views
url('^edtrac/progress/district/(?P<pk>\d+)/$', DistrictProgressDetails.as_view(template_name=\
"education/dashboard/district_progress_detail.html"), name="district-progress"),
url(r'^edtrac/dash-admin-progress-details/$', ProgressAdminDetails.as_view(), name="admin-progress-details"),
url(r'^edtrac/dash-admin-meals-details/$', MealsAdminDetails.as_view(), name="admin-meals-details"),
# to find out about the meals in a district
url(r'^edtrac/meals/district/(?P<name>\w+)/$', DistrictMealsDetails.as_view(), name="district-meal"),
url(r'^edtrac/reporters/$', EdtracReporter.as_view()), #/page(?P<page>[0-9]+)/$', ListView.as_view(
# url(r'^edtrac/reporters/create/$', EdtracReporterCreateView.as_view()),
# url(r'^edtrac/reporters/connection/create/$', EdtracReporterCreateConnection.as_view(), name="new-connection"),
# url(r'^emis/attendance/$', include(AttendanceReport().as_urlpatterns(name='emis-attendance'))),
url(r'^edtrac/scripts/', edit_scripts, name='emis-scripts'),
url(r'^edtrac/reshedule_scripts/(?P<script_slug>[a-z0-9_]+)/$', reschedule_scripts, name='emis-reschedule-scripts'),
url(r'^edtrac/attdmap/$', attendance_visualization, name="attendance-visualization"),
url(r'^edtrac/detail-attd/$', detail_attd, name="detail-attend-visualization"),
url(r'^edtrac/detail-dash/$', report_dashboard, name="detail-attendance-visualization"),
url(r'^edtrac/district-report/$', report_district_dashboard, name="district-visualization"),
url(r'^edtrac/term-dash/$', term_dashboard, name="term-dash-visualization"),
url(r'^edtrac/filter-dash/$', time_range_dashboard, name="time-range-dash-visualization"),
url(r'^edtrac/filter-dash-district/$', time_range_district_dashboard, name="time-range-dash-visualization"),
url(r'^edtrac/detail-attd/(?P<district>\w+)/$', detail_attd, name="detail-attendance-visualization"),
url(r'^edtrac/detail-attd-school/(?P<location>\w+)/$', detail_attd_school, name="detail-attendance-school"),
url(r'^edtrac/detail-water-source/$', detail_water_view, name="detail-water-view"),
url(r'^edtrac/detail-water-source/(?P<district>\d+)/$', detail_water_view, name="detail-water-view"),
url(r'edtrac/district-water-source/', district_water_view, name="district-water-view"),
url(r"^edtrac/export/$", edtrac_export_poll_responses, name="export-poll-responses"),
url(r"^edtrac/sub-county-reporters/$", edit_sub_county_reporters),
url(r"^edtrac/export-sub-county-reporters/$", export_sub_county_reporters, name="export-sub-county-reporters"),
url(r"^edtrac/schedule_water_polls/$", schedule_water_polls, name="schedule-water-polls"),
url(r"^edtrac/api/dashReport/$", dash_report_api, name="json-report-data-request"),
url(r'^edtrac/api/dashReport/params/$',dash_report_params, name="dash_report_params"),
url(r"^edtrac/api/dashReport/term/$", dash_report_term, name="json-report-term-data-request"),
url(r"^edtrac/api/district-report/$", dash_report_district, name="json-report-term-data-request"),
# the urls for violence views that I am testing
# url(r'^edtrac/violence-cases/$', violence_cases_view, name="violence-cases-view"),
# url(r'^edtrac/violence-cases/(?P<district>\d+)/$', violence_cases_view, name="violence-cases-view"),
#more violence views being tested
url(r'^edtrac/violence-detail/$', detailed_violence_view, name="violence-detail-visualization"),
url(r'^edtrac/violence-detail/(?P<district>\w+)/$', detailed_violence_view, name="violence-detail-visualization"),
url(r'^get_schools/$', get_schools),
url(r'^export_error_messages/$', edtrac_export_error_messages),
# url(r'^edtrac/violence-detail-school/(?P<location>\w+)/$', violence_detail_school, name="violence-detail-school"),
)
| {
"repo_name": "unicefuganda/edtrac",
"path": "edtrac_project/rapidsms_edtrac/education/urls.py",
"copies": "1",
"size": "19421",
"license": "bsd-3-clause",
"hash": 6681795958778536000,
"line_mean": 60.653968254,
"line_max": 147,
"alpha_frac": 0.6544977087,
"autogenerated": false,
"ratio": 3.2569176588965285,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.44114153675965284,
"avg_score": null,
"num_lines": null
} |
from .forms import SearchForm
from .models import Profile, Debtor
from django.shortcuts import render
from django.contrib import messages
from django.views.generic import ListView
from django.views.generic.edit import FormMixin
from django.db.models import Q
from django.template.defaultfilters import pluralize
from django.http import HttpResponse
from django.contrib.auth.decorators import user_passes_test, permission_required
from django.utils.decorators import method_decorator
import re
import openpyxl
class SearchDebtorListView(ListView, FormMixin):
"""A ListView of Debt information together with a search form.
Inherits from ListView and FormMixin.
"""
model = Profile
template_name = 'debtinfo/search_debtor.html'
context_object_name = 'debtors'
form_class = SearchForm
def get_queryset(self):
"""Check if query exists, return objects matching query else return None.
Override ListView.get_queryset().
"""
if 'q' in self.request.GET and self.request.GET['q'].strip():
search_query = self.request.GET['q'].strip()
field_list = ['id_number', 'cell']
obj = search_fields(search_query, field_list, model=self.model)
if obj.count() == 0:
messages.error(
self.request, 'Customer with ID or Contact number "%s" NOT found.' % search_query)
else:
result_count = obj.count()
messages.info(self.request, "{0} {1} found for search '{2}'".format(
result_count, counter(result_count, 'result', 'results'), search_query))
else:
obj = self.model.objects.none()
messages.info(
self.request, 'Search for a Customer by national ID or Contact numbers.')
return obj
def get(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
return ListView.get(self, request, *args, **kwargs)
def post(self, request, *args, **kwargs):
"""Validate form data and save to database, return response else return form."""
self.object = None
self.form = self.get_form(self.form_class)
if self.form.is_valid():
obj = self.form.save(commit=False)
self.object = obj.save()
messages.success(request, 'Query successful! ')
return HttpResponseRedirect(reverse_lazy('debtinfo:search_debtors'))
return self.get(request, *args, **kwargs)
def get_success_url(self):
return HttpResponseRedirect(reverse_lazy('debtinfo:search_debtors'))
class ViewDebtorsListView(ListView):
"""A ListView of Debtor information."""
model = Debtor
context_object_name = 'debtors'
template_name = 'debtinfo/view_debtors.html'
@method_decorator(user_passes_test(lambda u: u.is_staff))
def dispatch(self, request, *args, **kwargs):
return super(ViewDebtorsListView, self).dispatch(request, *args, **kwargs)
@user_passes_test(lambda u: u.is_staff)
def download_table(request):
"""Create Debtors list xlsx file, return download response."""
debtors = Debtor.objects.all()
wb = openpyxl.Workbook(write_only=True)
debtors_sheet = 'Debtors'
wb.create_sheet(debtors_sheet)
sheet = wb.get_sheet_by_name(debtors_sheet)
sheet.append(['First Name', 'Last Name', 'ID', 'Contact'])
for details in debtors:
sheet.append([details.debtor.first_name,
details.debtor.last_name, details.id_number, details.cell])
response = HttpResponse(
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=debtors.xlsx'
wb.save(response)
wb.close()
return response
def counter(count, singular, plural):
"""Return the appropriate plural term with regard to the count."""
return pluralize(count, singular + ',' + plural)
# Search snippet
def search_fields(query_string, field_list, model):
"""Initialise database search of the query provided."""
entry_query = get_query(query_string, field_list)
found_entries = model.objects.filter(entry_query)
return found_entries
def normalize_query(query_string,
findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
normspace=re.compile(r'\s{2,}').sub):
"""Split query into individual keywords, group quoted words, return list of terms.Example:
>>> normalize_query(' some random words "with quotes " and spaces')
['some', 'random', 'words', 'with quotes', 'and', 'spaces']
"""
return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]
def get_query(query_string, search_fields):
""" Return a query that is a combination of Q objects.
That combination aims to search keywords within a model
by testing the given search fields.
"""
query = None # Query to search for every search term
terms = normalize_query(query_string)
for term in terms:
or_query = None # Query to search for a given term in each field
for field_name in search_fields:
q = Q(**{"%s__iexact" % field_name: term})
if or_query is None:
or_query = q
else:
or_query = or_query | q
if query is None:
query = or_query
else:
query = query & or_query
return query
| {
"repo_name": "giantas/remoteref",
"path": "debtinfo/views.py",
"copies": "1",
"size": "5516",
"license": "mit",
"hash": -4628867350228083000,
"line_mean": 34.5870967742,
"line_max": 102,
"alpha_frac": 0.6424945613,
"autogenerated": false,
"ratio": 3.8573426573426572,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4999837218642657,
"avg_score": null,
"num_lines": null
} |
from .forms import SubmissionForm
from django.views.generic.edit import CreateView
#for MakeView
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
import pafy
from gtool import models
from gtool.models import Gfy
from urllib2 import URLError
class SubmissionCreateView(CreateView):
template_name = 'main.html'
form_class = SubmissionForm
success_url = '/'
def form_valid(self, form):
#form.send_email()
return super(SubmissionCreateView, self).form_valid(form)
def make_it(request, v='DGPbHUZQ-VE', g='MeanRevolvingCockerspaniel', st=0):
'''takes request + two arguments, returns gfysound URL
v = Youtube video ID
g = gfycat ID (AdjAdjAnimal)'''
# get context from request
context = RequestContext(request)
#if http method is POST...
if request.method == 'POST':
form = SubmissionForm(request.POST)
if form.is_valid():
try:
video = pafy.new(form.cleaned_data['yt_url'])
videoid = video.videoid
except URLError:
video = "http://www.youtube.com/watch?v=nz7sxt9xeJE"
videoid = "nz7sxt9xeJE"
g = Gfy(gfycat_url=form.cleaned_data['gfycat_url'])
#gfyurl = Gfy.get_id(form.cleaned_data['gfycat_url'])
gfycat = g.get_id()
starttime = form.cleaned_data['starttime']
mydictionary = {
'video': video,
'gfycat': gfycat,
'form': form,
'starttime': starttime
}
newurl = '/%s&%d/%s' % (videoid, starttime, gfycat)
# print "video: %s \ngfycat: http://www.gfycat.com/%s\n" % (video.watchv_url, gfycat)
return redirect(newurl)
else:
print "form is not valid\n"
print form.errors
else:
form = SubmissionForm()
print v
try:
video = pafy.new(v)
videoid = video.videoid
except URLError:
print "URLError..."
video = "http://www.youtube.com/watch?v=nz7sxt9xeJE"
videoid = "nz7sxt9xeJE"
gfycat = 'http://www.gfycat.com/%s' % g
print "request is GET"
mydictionary = {
'form': form,
'gfycat': g,
'video': videoid,
'yt_url': video.watchv_url,
'gfycat_url': gfycat,
'starttime': st,
}
return render_to_response('main3.html',
mydictionary,
context_instance=context)
| {
"repo_name": "alex-jerez/gfysound",
"path": "gfysound/gfysound/views.py",
"copies": "1",
"size": "2627",
"license": "mit",
"hash": -6298142298248783000,
"line_mean": 33.5657894737,
"line_max": 96,
"alpha_frac": 0.5591929958,
"autogenerated": false,
"ratio": 3.6385041551246537,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4697697150924654,
"avg_score": null,
"num_lines": null
} |
from .forms import TaskForm, TaskPrototypeNameForm, TaskPrototypeForm, \
GenerateTaskForm, RestOfTheTaskPrototypeForm
from .models import Task, TaskProgeny, Verb, TaskPrototype, TaskPrototypeProgeny, \
TaskOwnership, TaskResolution, TaskAccessPrototype, TaskAccess, Protocol
from django import forms
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group
from django.contrib.contenttypes.models import ContentType
from django.db.models import Max, Count, Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect, get_object_or_404
from django.template import loader, Context, Template, RequestContext
from django.utils import simplejson
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.cache import never_cache
from what_apps.presence.models import SessionInfo
from taggit.models import Tag
from twilio.util import TwilioCapability
from what_apps.utility.forms import AutoCompleteField
from what_apps.mellon.models import Privilege, get_privileges_for_user
from what_apps.people.models import GenericParty
from what_apps.social.forms import DrawAttentionAjaxForm, MessageForm
from what_apps.social.models import TopLevelMessage
from what_apps.social.views import post_top_level_message
import stomp
import json
#from twilio.Utils import token
T = ContentType.objects.get_for_model(Task)
@login_required
def landing(request):
tasks = Task.objects.can_be_seen_by_user(request.user).order_by('-created')
manual_tasks = tasks.filter(ownership__isnull = True).exclude(creator__username = "AutoTaskCreator")[:10]
task_messages = TopLevelMessage.objects.filter(content_type = T).order_by('-created')[:7]
return render(request, 'do/do_landing.html', locals())
def public_list(request):
'''
Displays tasks that are viewable with the privilege "Anybody in <group_name>"
'''
if not request.user.is_authenticated():
try:
group_name = request.GET['group']
except MultiValueDictKeyError:
return HttpResponseRedirect('/presence/login?next=/do/public_list/')
group = Group.objects.get(name=group_name)
privilege = get_object_or_404(Privilege, prototype__name="Anybody", jurisdiction=group)
access_objects = TaskAccess.objects.filter(prototype__privilege = privilege)
verbs = Verb.objects.filter(prototypes__instances__resolutions__isnull = True).annotate(num_tasks=Count('prototypes__instances')).order_by('-num_tasks')
else:
verbs = Verb.objects.filter(prototypes__instances__resolutions__isnull = True).annotate(num_tasks=Count('prototypes__instances')).order_by('-num_tasks')
tags = Tag.objects.filter(taggit_taggeditem_items__content_type = T).distinct() #TODO: Privileges
return render(request,
'do/three_column_task_list.html',
locals()
)
@never_cache
@login_required
def big_feed(request):
'''
Look at the big board! They're gettin' ready to clobber us!
'''
user_privileges = get_privileges_for_user(request.user)
tasks = Task.objects.filter(access_requirements__prototype__privilege__in = user_privileges, resolutions__isnull = True).order_by('-created')[:10]
ownerships = list(TaskOwnership.objects.filter(task__resolutions__isnull=True).order_by('-created')[:10])
task_messages = list(TopLevelMessage.objects.filter(content_type = T))
task_resolutions = list(TaskResolution.objects.order_by('-created')[:10])
sessions = list(SessionInfo.objects.order_by('-created')[:10])
task_activity = task_messages + task_resolutions + ownerships + sessions
sorted_task_activity = sorted(task_activity, key=lambda item: item.created, reverse=True)[:10]
activity_list = []
for item in sorted_task_activity:
activity_list.append((item, str(item._meta).split('.')[1]))
return render(request,
'do/do_news_feed.html',
locals()
)
#def three_column_task_list(request):
#
# verbs = Verb.objects.annotate(tasks = Count('prototypes__instances')).order_by('-tasks')
#
# return render(request,
# 'do/three_column_task_list.html',
# locals()
# )
@login_required
def task_profile(request, task_id):
task = get_object_or_404(Task, id = task_id)
#It wasn't bad enough that the actual create form was wet and silly. Now this too. TODO: FIX THIS FUCKER.
user_can_make_new_prototypes = True #TODO: Turn this into an actual privilege assessment
task_prototype_name_form = TaskPrototypeNameForm()
task_prototype_name_form.fields['name'].widget.attrs['class'] = "topLevel" #So that we can recognize it later via autocomplete.
rest_of_the_task_prototype_form = RestOfTheTaskPrototypeForm()
user_privileges = get_privileges_for_user(request.user)
#Wet and silly. TODO: Fix
class SimpleChildForm(forms.Form):
child = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
class SimpleParentForm(forms.Form):
parent = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
task_prototype_form = TaskPrototypeForm()
task_prototype_parent_form = SimpleParentForm()
task_prototype_child_form = SimpleChildForm()
draw_attention_ajax_form = DrawAttentionAjaxForm()
if task.prototype.id == 251 or task.prototype.id == 7:
has_outgoing_call = True
disable_incoming_calls = True
account_sid = "AC260e405c96ce1eddffbddeee43a13004"
auth_token = "fd219130e257e25e78613adc6c003d1a"
capability = TwilioCapability(account_sid, auth_token)
capability.allow_client_outgoing("APd13a42e60c91095f3b8683a77ee2dd05")
#The text of the call recipient will be the name of the person in the case of a tech job. It will be the output of the unicode method of the PhoneNumber in the case of a PhoneCall resolution.
if task.prototype.id == 251:
call_to_name = task.related_objects.all()[0].object.get_full_name()
related_user = task.related_objects.all()[0].object
phone_numbers = task.related_objects.all()[0].object.userprofile.contact_info.phone_numbers.all()
if task.prototype.id == 7:
phone_numbers = [task.related_objects.all()[0].object.from_number]
if task.related_objects.all()[0].object.from_number.owner:
call_to_name = task.related_objects.all()[0].object.from_number.owner
else:
call_to_name = "Phone Number #%s" % (str(task.related_objects.all()[0].object.id))
return render(request,
'do/task_profile.html',
locals()
)
@login_required
def task_prototype_profile(request, task_prototype_id):
'''
Profile page for Task Prototypes.
Allows editing, adding of children or parents, merging / evolving, etc.
'''
tp = get_object_or_404(TaskPrototype, id = task_prototype_id)
task_prototype_form = TaskPrototypeForm(instance=tp)
generate_form = GenerateTaskForm()
return render(request, 'do/task_prototype_profile.html', locals())
#TODO: Security
def own_task(request, task_id):
task = Task.objects.get(id=task_id)
ownership, newly_owned = task.ownership.get_or_create(owner=request.user)
t = loader.get_template('do/task_box.html')
c = RequestContext(request, {'task':task})
if not task.access_requirements.exists(): #We only want to push publically viewable tasks.
#Pushy Stuff
conn = stomp.Connection()
conn.start()
conn.connect()
task_box_dict = {
'verb_id': task.prototype.type.id,
'task_id': task.id,
'box': t.render(c),
}
conn.send(simplejson.dumps(task_box_dict), destination="/do/new_tasks")
response_json = { 'success': 1, 'newly_owned':newly_owned, 'task_id': task.id, 'box': t.render(c) }
return HttpResponse( json.dumps(response_json) )
def get_taskbox_toot_court(request, task_id):
task = Task.objects.get(id=task_id)
return render(request, 'do/task_box.html', locals())
#TODO: Ensure permissions
def create_task(request):
'''
This is one of the worst views I have ever written. -Justin
'''
user_can_make_new_prototypes = True #TODO: Turn this into an actual privilege assessment
task_prototype_name_form = TaskPrototypeNameForm()
task_prototype_name_form.fields['name'].widget.attrs['class'] = "topLevel" #So that we can recognize it later via autocomplete. TODO: DO this in the form object.
rest_of_the_task_prototype_form = RestOfTheTaskPrototypeForm() #TODO: Can we please. please. please make this one object.
#Wet and silly. TODO: Fix
class SimpleChildForm(forms.Form):
child = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
class SimpleParentForm(forms.Form):
parent = AutoCompleteField(models = (TaskPrototype,), name_visible_field=True)
task_prototype_form = TaskPrototypeForm()
task_prototype_parent_form = SimpleParentForm()
task_prototype_child_form = SimpleChildForm()
user_privileges = get_privileges_for_user(request.user)
try: #WHAT ON GODS GREEN FUCKING SERVER IS HAPPENING HERE
task_prototype_form.fields['name'].initial = request.GET['name']
except:
pass
return render(request, 'do/create_task_prototype.html', locals())
def task_form_handler(request):
'''
Deal with the task form. There's a lot of stuff that needs tweaking in here.
'''
task_prototype_name_form = TaskPrototypeNameForm()
name = request.POST['lookup_name'] #Set the name to the actual lookup field TODO: Yeah... have we checked that this form is valid? Do we care?
#Now let's figure out if they are trying to create a new prototype or just a new task.
try:
this_tp = TaskPrototype.objects.get(name=name)
new = False
except TaskPrototype.DoesNotExist:
verb = Verb.objects.get(id=request.POST['type'])
this_tp = TaskPrototype.objects.create(name=name, type=verb, creator=request.user)
new = True
if not new:
#If this TaskPrototype is not new, all we're going to do is generate its task.
task = this_tp.instantiate(request.user) #Generate the task with the current user as the creator
if new:
#Figure out the relations that were entered. We'll only do that for existing TaskPrototypes.
relations = ['parent', 'child']
for relation in relations:
counter = 1
suffix = relation #For the first iteration, we need it to just say "parent"
while True:
try:
if request.POST['lookup_' + suffix]:
autocompleted_object = task_prototype_name_form.fields['name'].to_python(request.POST[suffix]) #Use the autocopmlete field's to_python method to grab the object
if autocompleted_object:
related_object = autocompleted_object
else: #They didn't successfully autocomplete; looks like we're making an object up unless the name happens to be an exact match.
what_they_typed = request.POST['lookup_' + suffix]
related_object, is_new = TaskPrototype.objects.get_or_create(name = what_they_typed, defaults={'type': this_tp.type, 'creator': request.user})
#At this point in the function, we now know for sure what the related object is. Either they autocompleted, typed a name that matched but didn't autocopmlete, or they're making a new one.
if relation == "child":
parent = this_tp
child = related_object
priority = (counter * 5)
if relation == "parent":
parent = related_object
child = this_tp
current_max_priority_ag = related_object.children.all().aggregate(Max('priority'))
current_max_priority = current_max_priority_ag['priority__max']
try:
priority = int(current_max_priority) + 5 #Try setting the priority to the highest priority plus 5
except TypeError:
priority = 5 #Fuck it, there is no priority at all; we'll start it at 5
TaskPrototypeProgeny.objects.create(parent = parent, child = child, priority = priority )
else:
break
except MultiValueDictKeyError:
break
counter += 1
suffix = relation + str(counter) #Preparing for the second iteration, it says "parent1"
try:
if request.POST['no_generate']: #They clicked 'prototype only,' so they don't want us to run .instantiate()
pass
except: #They didn't click "prototype only," thus they want the Task to be generated.
task = this_tp.instantiate(request.user) #Generate the task with the current user as the creator
#Now we'll deal with the access requirements.
privilege = Privilege.objects.get(id = request.POST['access_requirement'])
task_access_prototype = TaskAccessPrototype.objects.get_or_create(privilege = privilege, type=5)[0] #Hardcoded 5 - this ought to be an option in the form
task_access = TaskAccess.objects.create(prototype=task_access_prototype, task = task)
#I mean, seriously, shouldn't this be a post-save hook?
if task:
messages.success(request, 'You created <a href="%s">%s</a>.' % (task.get_absolute_url(), this_tp.name)) #TODO: Distinguish messages between creation of TaskPrototype and Task objects.
else:
messages.success(request, 'You created %s.' % this_tp.name) #TODO: Distinguish messages between creation of TaskPrototype and Task objects.
#We may have arrived here from the Task Profile form or some other place where at least one parent is certain. Let's find out.
try:
parent_ipso_facto_id = request.POST['parentIdIpsoFacto']
parent_task = Task.objects.get(id=parent_ipso_facto_id) #By jove, it's tru! Our new task already has a parent Task.
current_max_priority_ag = parent_task.children.all().aggregate(Max('priority'))
current_max_priority = current_max_priority_ag['priority__max']
try: #TODO: Boy, it's started to feel like we need a max_priority method, eh?
priority = int(current_max_priority) + 5 #Try setting the priority to the highest priority plus 5
except TypeError:
priority = 5 #Fuck it, there is no priority at all; we'll start it at 5
task_progeny = TaskProgeny.objects.create(parent=parent_task, child=task, priority = priority)
return HttpResponseRedirect(parent_task.get_absolute_url())
except MultiValueDictKeyError:
pass #Nope, guess not.
return HttpResponseRedirect('/do/create_task') #TODO: Dehydrate this using the reverse of the create task view.
@login_required
def new_child_ajax_handler(request):
form = TaskForm(request.POST)
if form.is_valid():
#First create the child task.
new_child_task = form.save()
#Now create the relationship to the parent.
try:
parent_id = request.POST['parent_id']
parent_task = Task.objects.get(id = parent_id)
siblings = parent_task.children.all() #Siblings of the task we just created
highest_order_rank = siblings.aggregate(Max('order_rank'))['order_rank__max']
if highest_order_rank:
new_order_rank = highest_order_rank + 1
else:
new_order_rank = 1
hierarchy = TaskProgeny.objects.create(child = new_child_task, parent = parent_task, order_rank = new_order_rank)
return HttpResponse(1)
except IndexError:
raise RuntimeError('The Parent ID got yanked from the form. Not cool.')
else:
#TODO: This is an exact repeat of the invalid handler in utility.views.submit_generic. DRY it up.
errors = []
for error in form.errors:
errors.append(error)
dumps = simplejson.dumps(errors)
return HttpResponse(dumps)
#TODO: Check that the user has proper authority
def task_family_as_checklist_template(request):
'''
Takes a Task or TaskPrototype and returns the children as a checklist template.
I don't love this function. It can be far more generic and helpful with a little tinkering. -Justin
'''
is_prototype = request.GET['is_prototype'] #Are we looking for a Task or a TaskPrototype?
id = request.GET['id']
try:
number_to_show = request.GET['limit'] #Maybe they specified a number of children to list....
except KeyError:
number_to_show = False #....maybe they didn't.
task_maybe_prototype_model = TaskPrototype if is_prototype else Task
task_maybe_prototype = task_maybe_prototype_model.objects.get(id=id)
model_name = task_maybe_prototype_model.__name__
progeny_objects = task_maybe_prototype.children.all()
if number_to_show:
progeny_objects = progeny_objects.limit(number_to_show)
return render(request, 'do/children_checklist.html', locals())
def task_prototype_list(request):
task_prototypes = TaskPrototype.objects.all()
return render(request, 'do/task_prototype_list.html', locals())
def get_people_for_verb_as_html(request, verb_id):
'''
Shows peoples' names in the public list page.
'''
verb = Verb.objects.get(id=verb_id)
people = verb.users_who_have_completed_tasks()
return render(request, 'do/people_list.html', locals() )
def get_tasks_as_html(request, object_id, by_verb=True, mix_progeny=False):
'''
Ajax specialized method that returns, in HTML, all the tasks to which a user has access within a specific verb or tag.
If verb is true, get by task. Otherwise, by tag.
Typical use case is a refresh signal sent by the push module or a click on the "three columns" page.
'''
if not by_verb:
tag = Tag.objects.get(id=object_id)
tagged_tasks = tag.taggit_taggeditem_items.filter(content_type = T) #TODO: Apply privileges
if not request.user.is_authenticated():
group_name = request.GET['group']
group = Group.objects.get(name=group_name)
privilege = get_object_or_404(Privilege, prototype__name="Anybody", jurisdiction=group)
access_objects = TaskAccess.objects.filter(prototype__privilege = privilege)
access_tasks = Task.objects.filter(access_requirements__in = access_objects, resolutions__isnull=True).distinct()
if by_verb:
verb = Verb.objects.get(id=object_id)
tasks = access_tasks.filter(prototype__type = verb)
else:
tasks_from_tag = tagged_tasks.filter(task__access_requirements__in = access_objects, resolutions__isnull=True).distinct()
tasks = set()
for task_from_tag in tasks_from_tag:
tasks.add(task_from_tag.content_object)
else: #They're logged in.
if by_verb:
verb = Verb.objects.get(id=object_id)
tasks = verb.get_tasks_for_user(request.user)
else:
tasks_from_tag = tagged_tasks #TODO: Again, privileges
tasks = set()
for task_from_tag in tasks_from_tag:
if task_from_tag.content_object.resolutions.count() == 0:
tasks.add(task_from_tag.content_object)
if not mix_progeny:
#Let's make sure that no child task is listed alongside its parent.
tasks_to_remove = set()
for task in tasks:
for progeny in task.parents.all():
if progeny.parent in tasks:
tasks_to_remove.add(task)
task_set = set(tasks) - tasks_to_remove
tasks = task_set
return render(request, 'do/task_list.html', locals())
#TODO: Security
def mark_completed(request, task_id):
task = Task.objects.get(id=task_id)
resolution = TaskResolution.objects.create(task=task, type="C", creator=request.user)
return HttpResponse(1)
def mark_abandoned(request):
return HttpResponse(1)
def update_task(request, task_id):
task = Task.objects.get(id=task_id)
task.update_to_prototype(user=request.user)
return redirect(task.get_absolute_url())
@login_required
def post_task_message(request, task_id):
'''
Take a message about a task. See if the task is complete and mark it so if so.
If the message field is not blank, send it to the social view to handle the text of the message.
'''
task = Task.objects.get(id=task_id)
try:
if request.POST['completed']:
task.set_status(2, request.user)
except MultiValueDictKeyError:
pass #They didn't mark it completed, no need to think about it further.
if request.POST['message']:
post_top_level_message(request, 'do__task__%s' % (task_id))
return HttpResponseRedirect(task.get_absolute_url())
def protocols(request):
'''
SlashRoot's policies, procedures, and protocols listed here.
Perhaps this will be eliminated once we get the organization of tasks under better control since most of these will be tasks.
'''
protocols = Protocol.objects.all()
return render(request,'do/protocols.html',{'protocols':protocols})
def archives(request):
#completed_tasks = TaskResolution.objects.filter(type='C').order_by('-created')
tasks = SERVICE_PROTOTYPE.instances.filter(status__gt=1).all()
return render(request, 'do/archives.html', locals()) | {
"repo_name": "SlashRoot/WHAT",
"path": "what_apps/do/views.py",
"copies": "1",
"size": "23210",
"license": "mit",
"hash": 6919415892415682000,
"line_mean": 41.2786885246,
"line_max": 212,
"alpha_frac": 0.6308487721,
"autogenerated": false,
"ratio": 4.018351800554017,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9932991567955891,
"avg_score": 0.0432418009396253,
"num_lines": 549
} |
from .forms import UserAddForm, UserUpdateForm, CustomerAddForm, CustomerUpdateForm, PersonnelAddForm, PersonnelUpdateForm
# # # Dictionaries # # #
user_add_modal = {'id': 'User-Add-Modal',
'aria_label': 'User-Add-Modal',
'title_id': 'User-Add-Modal',
'title': 'Add User',
'form_id': UserAddForm.form_id}
user_update_modal = {'id': 'User-Update-Modal',
'aria_label': 'User-Update-Modal',
'title_id': 'User-Update-Modal',
'title': 'Update User',
'form_id': UserUpdateForm.form_id}
customer_add_modal = {'id': 'Customer-Add-Modal',
'aria_label': 'Customer-Add-Modal',
'title_id': 'Customer-Add-Modal',
'title': 'Add Customer',
'form_id': CustomerAddForm.form_id}
customer_update_modal = {'id': 'Customer-Update-Modal',
'aria_label': 'Customer-Update-Modal',
'title_id': 'Customer-Update-Modal',
'title': 'Update Customer',
'form_id': CustomerUpdateForm.form_id}
personnel_add_modal = {'id': 'Personnel-Add-Modal',
'aria_label': 'Personnel-Add-Modal',
'title_id': 'Personnel-Add-Modal',
'title': 'Add Personnel',
'form_id': PersonnelAddForm.form_id}
personnel_update_modal = {'id': 'Personnel-Update-Modal',
'aria_label': 'Personnel-Update-Modal',
'title_id': 'Personnel-Update-Modal',
'title': 'Update Personnel',
'form_id': PersonnelUpdateForm.form_id}
user_csv_upload_modal = {'id': 'User-CSV-Upload-Modal',
'aria_label': 'User-CSV-Upload-Modal',
'title_id': 'User-CSV-Upload-Modal',
'title': 'Upload Users',
# 'form_id': UserCsvUploadForm.form_id}
'form_id': 'User-CSV-Upload-Form',
'submit_value': 'User-CSV-Upload-Submit'}
customer_csv_upload_modal = {'id': 'Customer-CSV-Upload-Modal',
'aria_label': 'Customer-CSV-Upload-Modal',
'title_id': 'Customer-CSV-Upload-Modal',
'title': 'Upload Customers',
# 'form_id': CustomerCsvUploadForm.form_id}
'form_id': 'Customer-CSV-Upload-Form',
'submit_value': 'Customer-CSV-Upload-Submit'}
personnel_csv_upload_modal = {'id': 'Personnel-CSV-Upload-Modal',
'aria_label': 'Personnel-CSV-Upload-Modal',
'title_id': 'Personnel-CSV-Upload-Modal',
'title': 'Upload Personnel',
# 'form_id': PersonnelCsvUploadForm.form_id}
'form_id': 'Personnel-CSV-Upload-Form',
'submit_value': 'Personnel-CSV-Upload-Submit'}
violations_csv_upload_modal = {'id': 'Violations-CSV-Upload-Modal',
'aria_label': 'Violations-CSV-Upload-Modal',
'title_id': 'Violations-CSV-Upload-Modal',
'title': 'Upload Violations',
# 'form_id': CustomerCsvUploadForm.form_id}
'form_id': 'Violations-CSV-Upload-Form',
'submit_value': 'Violations-CSV-Upload-Submit'}
### Classes ###
# - Work in progress. -Joe Flack, 03/31/2016
class UserAddModal:
id = 'User-Add-Modal'
aria_label = 'User-Add-Modal'
title_id = 'User-Add-Modal'
title = 'Add New User'
class UserUpdateModal:
id = 'User-Update-Modal'
aria_label = 'User-Update-Modal'
title_id = 'User-Update-Modal'
title = 'Update User'
def __init__(self, id, aria_label, title_id, title):
self.id = id
self.aria_label = aria_label
self.title_id = title_id
self.title = title
def __repr__(self):
return '<id {}>'.format(self.id)
| {
"repo_name": "joeflack4/vanillerp",
"path": "app/modals.py",
"copies": "1",
"size": "4220",
"license": "mit",
"hash": 1257431110113656300,
"line_mean": 42.5051546392,
"line_max": 122,
"alpha_frac": 0.4985781991,
"autogenerated": false,
"ratio": 3.8858195211786373,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4884397720278637,
"avg_score": null,
"num_lines": null
} |
from .forms import UserChangeForm, UserCreationForm
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from .models import CustUser
class CustUserAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'is_admin')
# list_display = ('email', 'date_of_birth', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
# ('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
# Now register the new UserAdmin...
admin.site.register(CustUser, CustUserAdmin)
# ... and, since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
| {
"repo_name": "jimbeaudoin/django-custuser",
"path": "custuser/admin.py",
"copies": "1",
"size": "1432",
"license": "mit",
"hash": 2547807356209655000,
"line_mean": 33.9268292683,
"line_max": 73,
"alpha_frac": 0.655027933,
"autogenerated": false,
"ratio": 3.934065934065934,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5089093867065934,
"avg_score": null,
"num_lines": null
} |
from .forms import UserContactForm, UserContactInfoForm, UserProfileForm, \
handle_user_profile_form, PhoneNumberForm
from .models import ContactInfo, Message, DialList, DialListParticipation, \
PhoneNumber, BICYCLE_DAY
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.forms import ModelForm
from django.http import HttpResponseRedirect as redirect, HttpResponse, Http404
from django.shortcuts import render
from django.template import RequestContext
from django.utils.datastructures import MultiValueDictKeyError
from what_apps.utility.forms import GenericPartyField, SimplePartyLookup
from what_apps.people.models import UserProfile
from what_apps.utility.functions import daily_crypt
import datetime
class ContactForm(ModelForm):
class Meta:
model = Message
def contact_form(request):
form=ContactForm()
return render(request, 'contact_form.html', locals())
@login_required
def contact_list(request):
people = User.objects.all().order_by('last_name')
return render(request, 'contact/contact_list.html', locals())
def contact_profile(request, contact_id=None, username=None):
if contact_id:
contact = ContactInfo.objects.get(id=contact_id)
if username:
contact = User.objects.get(first_name=username) #TODO: Turn into actual username, un-fuckify
contact_info = contact.__dict__.items()
return render(request, 'contact/contact_profile.html', locals())
@login_required
def new_contact(request):
'''
Adds or modifies a contact.
Makes a User object (and a UserProfile and ContactInfo) for them.
'''
#We're going to have two lists of forms; one for the three objects, and one for phone numbers.
contact_forms = []
phone_forms = []
blank_phone_form = PhoneNumberForm(prefix="phone_new")
if request.POST: #Are we posting new information?
#First let's figure out if we are dealing with an existing user or adding a new one.
try:
referenced_user = User.objects.get(id=request.POST['user_id'])
except MultiValueDictKeyError:
referenced_user = False #We didn't get a user passed in via POST.
user_form = UserContactForm(request.POST, prefix="user")
contact_form = UserContactInfoForm(request.POST, prefix="contact")
profile_form = UserProfileForm(request.POST, prefix="profile")
#Now we need to traverse the dict to pick out the phone forms.
#They may come in three types:
#phone_n, where n is the id of a PhoneNumber object - these are existing PhoneNumber objects
#phone_new - these are phone number objects added with the "add phone" button
#phone_get - this is the phone number passed into the form originally (used if you click "new contact" from a PhoneCall Task page.)
populated_phone_forms = []
for item, value in request.POST.items():
#Take note: item will be something like phone_new-number-2
if item.split('_')[0] == "phone":
#Look for phone items, but only branch off once per phone (ie, only on the "number," not the "type")
if item.split('_')[1].split('-')[1] == "number":
try:
entry = item.split('_')[1].split('-')[2] #Which entry is this? There might be more than one number.
type_string = str(item.split('-')[0]) + "-type-" + entry
except IndexError: #This is not a numbered entry.
type_string = str(item.split('-')[0]) + "-type"
type = request.POST[type_string]
number = value
if not(not number and not type): #We only want cases where both number and type are not blank. If either is filled in, we'll proceed.
case_indicator = item.split('_')[1].split('-')[0] #This will be either n, "new", or "get" as per above.
if case_indicator == "new" or case_indicator == "get" or 0:
try:
phone_number_object = PhoneNumber.objects.get(number=number)
populated_phone_forms.append(PhoneNumberForm({'number':number, 'type':type}, instance=phone_number_object))
except PhoneNumber.DoesNotExist:
populated_phone_forms.append(PhoneNumberForm({'number':number, 'type':type}))
else: #Assume that it's the n case
phone_number_object = PhoneNumber.objects.get(id=case_indicator)
populated_phone_forms.append(PhoneNumberForm({'number':number, 'type':type}, instance=phone_number_object))
#Send the forms to the handler for processing.
invalid = handle_user_profile_form(user_form, contact_form, profile_form, populated_phone_forms, user = referenced_user) #Returns forms tuple if forms are invalid; False otherwise
if not invalid: #Here we'll do something special if the handling went as we hoped.
'''
SUCCESS!
'''
if 'profile-birthday_month' in request.POST:
profile_form.instance.birth_month = request.POST['profile-birthday_month']
profile_form.instance.birth_day = request.POST['profile-birthday_day']
profile_form.instance.save()
#If wasn't working here. strange. TODO: Change from try block to if. :-)
try: #TODO: Justin and Kieran say: do this with sessions
role = request.GET['role']
if role == 'donor':
#Not good here - I want direct access to the user object by now. REFORM! (People like that reform, pappy)
encrypted_user_id = daily_crypt(user_form.instance.id) #Get the user id, encrypt it.
return redirect('/accounting/record_donation/?donor=' + encrypted_user_id)
except LookupError: #Probably ought to be some different branching here - they don't ALWAYS need to go to watch calls.
#Oh, and BTW, this is SUCCESS.
return redirect(contact_form.instance.get_absolute_url()) #Send them to the contact page.
else: #Not valid - let's tell them so.
contact_forms, phone_forms = invalid
return render(request, 'contact/new_contact.html', locals())
else: #No POST - this is a brand new form.
contact_forms = [UserContactForm(prefix="user"), UserContactInfoForm(prefix="contact"), UserProfileForm(prefix="profile")]
#We want email, first name, and last name to be required for all submissions.
contact_forms[0].fields['email'].required = True
contact_forms[0].fields['first_name'].required = True
contact_forms[0].fields['last_name'].required = True
try: #This might be a "new contact from phone number" request. Let's find out.
phone_forms.append(PhoneNumberForm(initial = {'number': request.GET['phone_number']}, prefix="phone_get")) #Yes it is! Put the phone number in the field.
except MultiValueDictKeyError:
pass #No, it isn't. Move along. Nothing to see here.
#Either we don't have POST (meaning this is a brand new form) or something is invalid.
#In either case, let's set the fields to required and give them the template again.
initial_lookup_form = SimplePartyLookup()
return render(request, 'contact/new_contact.html', locals())
@login_required #TODO: More security
def contact_forms_for_person(request):
contact_forms = []
phone_forms = []
referenced_user = User.objects.get(id=request.GET['user_id'])
user_form = UserContactForm(prefix="user", instance=referenced_user)
contact_forms.append(user_form)
blank_phone_form = PhoneNumberForm(prefix="phone_new")
try:
userprofile = referenced_user.userprofile
profile_form = UserProfileForm(prefix="profile", instance=userprofile)
try:
contact_info = userprofile.contact_info
contact_form = UserContactInfoForm(prefix="contact", instance=contact_info)
contact_forms.append(contact_form)
for phone_number in contact_info.phone_numbers.all():
phone_forms.append(PhoneNumberForm(instance=phone_number, prefix="phone_%s" % (phone_number.id)))
except ContactInfo.DoesNotExist:
contact_form = UserContactInfoForm(prefix="contact")
contact_forms.append(profile_form)
except UserProfile.DoesNotExist:
profile_form = UserProfileForm(request.POST, prefix="profile")
try:
phone_forms.append(PhoneNumberForm(initial = {'number': request.GET['phone_number']}, prefix="phone_get"))
except MultiValueDictKeyError:
pass
return render(request, 'contact/new_contact_inside_form.html', locals())
def toggle_dial_list(request, dial_list_id):
dial_list = DialList.objects.get(id=dial_list_id)
phone_number_id = request.POST['data']
phone_number_object = PhoneNumber.objects.get(id = phone_number_id)
active = False if request.POST['truthiness'] == 'false' else True
if active:
DialListParticipation.objects.create(
number = phone_number_object,
list = dial_list,
)
else:
try:
latest = DialListParticipation.objects.get(number = phone_number_object, list=dial_list, destroyed = BICYCLE_DAY)
latest.destroyed = datetime.datetime.now()
latest.save()
except DialListParticipation.DoesNotExist:
#Ummmm, they weren't on the list in the first place. No need to take them off it.
pass
return HttpResponse(1)
def phone_number_profile(request, phone_number_id):
phone_number = PhoneNumber.objects.get(id=phone_number_id)
if request.POST:
phone_number.spam = int(request.POST['spam'])
phone_number.save()
return render(request, 'contact/phone_number_profile.html', locals()) | {
"repo_name": "SlashRoot/WHAT",
"path": "what_apps/contact/views.py",
"copies": "1",
"size": "10747",
"license": "mit",
"hash": 4528284596592525000,
"line_mean": 46.3480176211,
"line_max": 187,
"alpha_frac": 0.6104029031,
"autogenerated": false,
"ratio": 4.358069748580697,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.03075698617043352,
"num_lines": 227
} |
from .forms import UserInGroupForm
from .models import Role, Group, RoleInGroup, UserInGroup
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
import json
@login_required
def who_am_i(request):
validating_user = {'username': request.user.username}
confirmation = json.dumps(validating_user)
return HttpResponse(confirmation)
@login_required
def role_form(request):
if request.method == 'POST':
user_in_group_form = UserInGroupForm(request.POST)
if user_in_group_form.is_valid():
user_in_group_form.save()
return HttpResponseRedirect('/people/awesome/')
else:
user_in_group_form = UserInGroupForm()
return render(request, 'people/role_form.html', locals())
def awesome_o(request):
return render(request, 'people/awesome.html', locals())
def membership_roles(request):
roles = Role.objects.all()
groups = Group.objects.all()
roles_in_groups = RoleInGroup.objects.filter(id=groups)
users_in_group_with_roles = UserInGroup.objects.filter(id=roles_in_groups)
return render(request, 'people/membership_roles.html', )
| {
"repo_name": "SlashRoot/WHAT",
"path": "what_apps/people/views.py",
"copies": "1",
"size": "1299",
"license": "mit",
"hash": -5741433544528143000,
"line_mean": 30.7073170732,
"line_max": 78,
"alpha_frac": 0.7051578137,
"autogenerated": false,
"ratio": 3.7982456140350878,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5003403427735088,
"avg_score": null,
"num_lines": null
} |
from formspree_test_case import FormspreeTestCase
from formspree.utils import next_url
class UtilsTest(FormspreeTestCase):
def test_next_url(self):
# thanks route should have the referrer as its 'next'
self.assertEqual('/thanks?next=http%3A%2F%2Ffun.io', next_url(referrer='http://fun.io'))
# No referrer and relative next url should result in proper relative next url.
self.assertEqual('/thank-you', next_url(next='/thank-you'))
# No referrer and absolute next url should result in proper absolute next url.
self.assertEqual('http://somesite.org/thank-you', next_url(next='http://somesite.org/thank-you'))
# Referrer set and relative next url should result in proper absolute next url.
self.assertEqual('http://fun.io/', next_url(referrer='http://fun.io', next='/'))
self.assertEqual('http://fun.io/thanks.html', next_url(referrer='http://fun.io', next='thanks.html'))
self.assertEqual('http://fun.io/thanks.html', next_url(referrer='http://fun.io', next='/thanks.html'))
# Referrer set and absolute next url should result in proper absolute next url.
self.assertEqual('https://morefun.net/awesome.php', next_url(referrer='https://fun.io', next='//morefun.net/awesome.php'))
self.assertEqual('http://morefun.net/awesome.php', next_url(referrer='http://fun.io', next='//morefun.net/awesome.php'))
| {
"repo_name": "OVERLOADROBOTICA/OVERLOADROBOTICA.github.io",
"path": "mail/formspree-master/tests/test_utils.py",
"copies": "1",
"size": "1412",
"license": "mit",
"hash": 31962804908058548,
"line_mean": 57.8333333333,
"line_max": 130,
"alpha_frac": 0.6862606232,
"autogenerated": false,
"ratio": 3.4188861985472156,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4605146821747216,
"avg_score": null,
"num_lines": null
} |
from .formSubmission import FormSubmission
from django.contrib.auth.models import User
from django.db import models
from django.template.defaultfilters import slugify
class Log(models.Model):
"""
Form Submission Log Database Model
Attributes:
* owner - user submitting the message
* submission - form submission associated
* timestamp - time of submission entry
* private - display to non-owners?
* message - log entry
* mtype - type of log entry
* 1 - user message (default)
* 2 - system action
* 3 - form status change
* 4 - attached file
* file - attached file entry
"""
owner = models.ForeignKey(User, blank=True, null=True)
submission = models.ForeignKey(FormSubmission)
timestamp = models.DateTimeField(auto_now_add=True)
private = models.BooleanField(default=False)
message = models.TextField(blank=True)
mtype = models.IntegerField(default=1)
file = models.FileField(upload_to='private/constellation_forms/log_files/')
class Meta:
db_table = "form_log"
ordering = ("timestamp",)
@property
def extension(self):
return self.file.name.split(".")[-1]
@property
def content_type(self):
if self.extension == "pdf":
return "application/pdf"
if self.extension == "txt":
return "text/plain"
if self.extension == "png":
return "image/png"
if self.extension == "jpeg" or self.extension == "jpg":
return "image/jpeg"
if self.extension == "gif":
return "image/gif"
return "application/force-download"
@property
def file_name(self):
return slugify("{0}_{1}_{2}".format(self.submission.form.name, self.pk,
self.owner.username)) + "." + \
self.extension
| {
"repo_name": "ConstellationApps/Forms",
"path": "constellation_forms/models/log.py",
"copies": "1",
"size": "1879",
"license": "isc",
"hash": -3831457609151334400,
"line_mean": 30.3166666667,
"line_max": 79,
"alpha_frac": 0.6146886642,
"autogenerated": false,
"ratio": 4.241534988713318,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0,
"num_lines": 60
} |
from formtools.preview import FormPreview
from django.views.generic import DetailView
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Article
from .forms import ArticleForm
class ArticlePreviewUsingRequest(FormPreview):
def done(self, request, cleaned_data):
# doneの時点ではModelの保存ができていないので、
# 自分で保存処理を実装する必要がある
f = ArticleForm(request.POST)
article = f.save(commit=False)
article.save()
f.save_m2m()
url = reverse('ns:article-detail', args=(article.id,))
return HttpResponseRedirect(url)
class ArticlePreviewUsingCleanedData(FormPreview):
def done(self, request, cleaned_data):
article = Article.objects.create(
title = cleaned_data['title'],
content = cleaned_data['content'],
)
article.categories.add(*cleaned_data['categories'])
url = reverse('ns:article-detail', args=(article.id,))
return HttpResponseRedirect(url)
class ArticleDetail(DetailView):
model = Article | {
"repo_name": "thinkAmi-sandbox/Django_form_preview_sample",
"path": "myapp/views.py",
"copies": "1",
"size": "1179",
"license": "unlicense",
"hash": 3661447012635966500,
"line_mean": 29.8333333333,
"line_max": 62,
"alpha_frac": 0.6717763751,
"autogenerated": false,
"ratio": 3.8912280701754387,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9938517455355755,
"avg_score": 0.02489739798393669,
"num_lines": 36
} |
from formtools.wizard.views import NamedUrlSessionWizardView
from django.shortcuts import redirect, render
from .emails import (
send_application_confirmation, send_application_notification)
from .forms import (
PreviousEventForm, ApplicationForm, WorkshopForm, OrganizersFormSet)
from .models import EventApplication
# ORGANIZE FORM #
FORMS = (("previous_event", PreviousEventForm),
("application", ApplicationForm),
("organizers", OrganizersFormSet),
("workshop", WorkshopForm))
TEMPLATES = {"previous_event": "organize/form/step1_previous_event.html",
"application": "organize/form/step2_application.html",
"organizers": "organize/form/step3_organizers.html",
"workshop": "organize/form/step4_workshop.html"}
class OrganizeFormWizard(NamedUrlSessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
# Process the date from the forms
data_dict = {}
for form in form_list:
data_dict.update(form.get_data_for_saving())
organizers_data = data_dict.pop('coorganizers', [])
application = EventApplication.objects.create(**data_dict)
for organizer in organizers_data:
application.coorganizers.create(**organizer)
send_application_confirmation(application)
send_application_notification(application)
return redirect('organize:form_thank_you')
def skip_application_if_organizer(wizard):
cleaned_data = wizard.get_cleaned_data_for_step('previous_event') or {}
return not cleaned_data.get('has_organized_before')
organize_form_wizard = OrganizeFormWizard.as_view(
FORMS,
condition_dict={'application': skip_application_if_organizer},
url_name='organize:form_step')
# ORGANIZE FORM #
def form_thank_you(request):
return render(request, 'organize/form/thank_you.html', {})
def index(request):
return render(request, 'organize/index.html', {})
def commitment(request):
return render(request, 'organize/commitment.html', {})
def prerequisites(request):
return render(request, 'organize/prerequisites.html', {})
| {
"repo_name": "patjouk/djangogirls",
"path": "organize/views.py",
"copies": "1",
"size": "2212",
"license": "bsd-3-clause",
"hash": 5988253227422147000,
"line_mean": 31.0579710145,
"line_max": 75,
"alpha_frac": 0.6993670886,
"autogenerated": false,
"ratio": 3.761904761904762,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49612718505047615,
"avg_score": null,
"num_lines": null
} |
from formtools.wizard.views import normalize_name
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.forms import widgets
from django.utils.encoding import force_str
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from cms.utils.helpers import classproperty
from djng.forms import fields, NgModelFormMixin, NgFormValidationMixin
from djng.styling.bootstrap3.forms import Bootstrap3Form, Bootstrap3ModelForm
class DialogFormMixin(NgModelFormMixin, NgFormValidationMixin):
required_css_class = 'djng-field-required'
def __init__(self, *args, **kwargs):
kwargs.pop('cart', None) # cart object must be removed, otherwise underlying methods complain
auto_name = self.form_name ## .replace('_form', '')
kwargs.setdefault('auto_id', '{}-%s'.format(auto_name))
super().__init__(*args, **kwargs)
@classproperty
def form_name(cls):
return normalize_name(cls.__name__)
def clean(self):
cleaned_data = dict(super().clean())
cleaned_data.pop('plugin_id', None)
if cleaned_data.pop('plugin_order', None) is None:
msg = "Field 'plugin_order' is a hidden but required field in each form inheriting from DialogFormMixin"
raise ValidationError(msg)
return cleaned_data
def as_text(self):
"""
Dialog Forms rendered as summary just display their values instead of input fields.
This is useful to render a summary of a previously filled out form.
"""
try:
return mark_safe(self.instance.as_text())
except (AttributeError, TypeError):
output = []
for name in self.fields.keys():
bound_field = self[name]
value = bound_field.value()
if bound_field.is_hidden:
continue
if isinstance(value, (list, tuple)):
line = []
cast_to = type(tuple(bound_field.field.choices)[0][0])
for v in value:
try:
line.append(dict(bound_field.field.choices)[cast_to(v)])
except (AttributeError, KeyError):
pass
output.append(force_str(', '.join(line)))
elif value:
try:
value = dict(bound_field.field.choices)[value]
except (AttributeError, KeyError):
pass
output.append(force_str(value))
return mark_safe('\n'.join(output))
def get_response_data(self):
"""
Hook to respond with an updated version of the form data. This response then shall
override the forms content.
"""
class DialogForm(DialogFormMixin, Bootstrap3Form):
"""
Base class for all dialog forms used with a DialogFormPlugin.
"""
label_css_classes = 'control-label font-weight-bold'
plugin_id = fields.CharField(
widget=widgets.HiddenInput,
required=False,
)
plugin_order = fields.CharField(
widget=widgets.HiddenInput,
)
class DialogModelForm(DialogFormMixin, Bootstrap3ModelForm):
"""
Base class for all dialog model forms used with a DialogFormPlugin.
"""
plugin_id = fields.CharField(
widget=widgets.HiddenInput,
required=False,
)
plugin_order = fields.CharField(widget=widgets.HiddenInput)
@cached_property
def field_css_classes(self):
css_classes = {'*': getattr(Bootstrap3ModelForm, 'field_css_classes')}
for name, field in self.fields.items():
if not field.widget.is_hidden:
css_classes[name] = [css_classes['*']]
css_classes[name].append('{}-{}'.format(self.scope_prefix, name))
return css_classes
class UniqueEmailValidationMixin:
"""
A mixin added to forms which have to validate for the uniqueness of email addresses.
"""
def clean_email(self):
if not self.cleaned_data['email']:
raise ValidationError(_("Please provide a valid e-mail address"))
# check for uniqueness of email address
if get_user_model().objects.filter(is_active=True, email=self.cleaned_data['email']).exists():
msg = _("A customer with the e-mail address '{email}' already exists.\n"
"If you have used this address previously, try to reset the password.")
raise ValidationError(msg.format(**self.cleaned_data))
return self.cleaned_data['email']
| {
"repo_name": "awesto/django-shop",
"path": "shop/forms/base.py",
"copies": "1",
"size": "4751",
"license": "bsd-3-clause",
"hash": 2410745361093306000,
"line_mean": 37.008,
"line_max": 116,
"alpha_frac": 0.6152388971,
"autogenerated": false,
"ratio": 4.407235621521336,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5522474518621336,
"avg_score": null,
"num_lines": null
} |
from formula.Formula import EMA
# MACD
class DATA():
def __init__(self, diff, dea):
self.Set(diff, dea)
def Set(self, diff, dea):
self.diff = diff;
self.dea = dea;
self.macd = 2 * (self.diff - self.dea);
def __str__(self):
return 'diff={0},dea={1},macd={2}'.format(self.diff, self.dea, self.macd);
class MACD():
def __init__(self, short=12, long=26, diff=9):
self.EMAShort = [];
self.EMALong = [];
self.DEA = [];
self.DIFF = [];
self.short = short;
self.diff = diff;
self.long = long;
def Input(self, klines):
prices = klines.prices;
EMA(klines.prices, self.EMAShort, self.short);
EMA(klines.prices, self.EMALong, self.long);
ld = len(self.DIFF);
lr = len(self.EMAShort);
for idx in range(ld, lr):
self.DIFF.append(self.EMAShort[idx] - self.EMALong[idx]);
EMA(self.DIFF, self.DEA, self.diff);
def Get(self, index):
return DATA(self.DIFF[index], self.DEA[index])
def __str__(self):
str = '';
l = len(self.EMAShort);
for k in range(0, l):
str = str + self.Get(indx).__str__() + '\n';
return str;
def __len__(self):
return len(self.DIFF); | {
"repo_name": "WaitGodot/peatio-client-python",
"path": "formula/MACD.py",
"copies": "1",
"size": "1349",
"license": "cc0-1.0",
"hash": -4094199780087416300,
"line_mean": 26.7446808511,
"line_max": 82,
"alpha_frac": 0.5033358043,
"autogenerated": false,
"ratio": 3.2427884615384617,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.912555468128321,
"avg_score": 0.024113916911050443,
"num_lines": 47
} |
from formulaic.errors import FormulaSyntaxError
from .types.ast_node import ASTNode
from .types.token import Token
def exc_for_token(token, message, errcls=FormulaSyntaxError):
token = __get_token_for_ast(token)
token_context = token.get_source_context(colorize=True)
if token_context:
return errcls(f"{message}\n\n{token_context}")
return errcls(message)
def exc_for_missing_operator(lhs, rhs, errcls=FormulaSyntaxError):
lhs_token, rhs_token, error_token = __get_tokens_for_gap(lhs, rhs)
raise exc_for_token(error_token, f"Missing operator between `{lhs_token.token}` and `{rhs_token.token}`.", errcls=errcls)
def __get_token_for_ast(ast):
if isinstance(ast, Token):
return ast
lhs_token = ast
while isinstance(lhs_token, ASTNode):
lhs_token = lhs_token.args[0]
rhs_token = ast
while isinstance(rhs_token, ASTNode):
rhs_token = rhs_token.args[-1]
return Token(
token=lhs_token.source[lhs_token.source_start:rhs_token.source_end + 1] if lhs_token.source else '',
source=lhs_token.source, source_start=lhs_token.source_start, source_end=rhs_token.source_end
)
def __get_tokens_for_gap(lhs, rhs):
lhs_token = lhs
while isinstance(lhs_token, ASTNode):
lhs_token = lhs_token.args[-1]
rhs_token = rhs or lhs
while isinstance(rhs_token, ASTNode):
rhs_token = rhs_token.args[0]
return lhs_token, rhs_token, Token(
lhs_token.source[lhs_token.source_start:rhs_token.source_end + 1] if lhs_token.source else '',
source=lhs_token.source, source_start=lhs_token.source_start, source_end=rhs_token.source_end
)
| {
"repo_name": "matthewwardrop/formulaic",
"path": "formulaic/parser/utils.py",
"copies": "1",
"size": "1663",
"license": "mit",
"hash": -4920134423319278000,
"line_mean": 36.7954545455,
"line_max": 125,
"alpha_frac": 0.6837041491,
"autogenerated": false,
"ratio": 3.235408560311284,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4419112709411284,
"avg_score": null,
"num_lines": null
} |
from formulaic.parser.types import Factor
class EvaluatedFactor:
def __init__(self, factor, values, kind=None, spans_intercept=False):
self.factor = factor
self.values = values
self.kind = kind
self.spans_intercept = spans_intercept
@property
def kind(self):
return self._kind
@kind.setter
def kind(self, kind):
if not kind or kind == 'unknown':
raise ValueError("`EvaluatedFactor` instances must have a known kind.")
self._kind = Factor.Kind(kind)
@property
def expr(self):
return self.factor.expr
@property
def metadata(self):
return self.factor.metadata
def __repr__(self):
return repr(self.factor)
def __eq__(self, other):
if isinstance(other, EvaluatedFactor):
return self.factor == other.factor
return NotImplemented
def __lt__(self, other):
if isinstance(other, EvaluatedFactor):
return self.factor < other.factor
return NotImplemented
| {
"repo_name": "matthewwardrop/formulaic",
"path": "formulaic/materializers/types/evaluated_factor.py",
"copies": "1",
"size": "1049",
"license": "mit",
"hash": -1140384252406677400,
"line_mean": 24.5853658537,
"line_max": 83,
"alpha_frac": 0.6139180172,
"autogenerated": false,
"ratio": 4.352697095435684,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00029036004645760743,
"num_lines": 41
} |
from formulaic.parser.types import Factor, Term
def differentiate_term(term, vars, use_sympy=False):
factors = term.factors
for var in vars:
affected_factors = set(
factor
for factor in factors
if var in _factor_symbols(factor, use_sympy=use_sympy)
)
if not affected_factors:
return Term({Factor('0', eval_method='literal')})
factors = factors.difference(affected_factors).union(_differentiate_factors(affected_factors, var, use_sympy=use_sympy))
return Term(factors or {Factor('1', eval_method='literal')})
def _factor_symbols(factor, use_sympy=False):
if use_sympy:
try:
import sympy
return {str(s) for s in sympy.S(factor.expr).free_symbols}
except ImportError: # pragma: no cover
raise ImportError("`sympy` is not available. Install it using `pip install formulaic[calculus]` or `pip install sympy`.")
return {factor.expr}
def _differentiate_factors(factors, var, use_sympy=False):
if use_sympy:
try:
import sympy
expr = sympy.S('(' + ') * ('.join(factor.expr for factor in factors) + ')').diff(var)
eval_method = 'python'
except ImportError: # pragma: no cover
raise ImportError("`sympy` is not available. Install it using `pip install formulaic[calculus]` or `pip install sympy`.")
else:
assert len(factors) == 1
expr = 1
eval_method = next(iter(factors)).eval_method
if expr == 1:
return set()
return {Factor(f'({str(expr)})', eval_method=eval_method)}
| {
"repo_name": "matthewwardrop/formulaic",
"path": "formulaic/utils/calculus.py",
"copies": "1",
"size": "1635",
"license": "mit",
"hash": -6776096500078764000,
"line_mean": 35.3333333333,
"line_max": 133,
"alpha_frac": 0.6152905199,
"autogenerated": false,
"ratio": 3.9397590361445785,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5055049556044579,
"avg_score": null,
"num_lines": null
} |
from .formulas import dbetadt as _a
import logging as _logging
import numpy as _np
import scipy.constants as _spc
import scisalt as _ss
import time as _time
_logger = _logging.getLogger(__name__)
__all__ = [
'SimFrame'
]
class SimFrame(object):
"""
Coordinates and steps through the simulation.
"""
def __init__(self, Drive, PlasmaE, PlasmaIons):
self._Drive = Drive
self._PlasmaE = PlasmaE
self._PlasmaIons = PlasmaIons
self._timestamp = None
def sim(self):
# ======================================
# Set up longitudinal coord
# ======================================
# dt = self.PlasmaE.dxi / _spc.speed_of_light
dt = self.PlasmaE.PlasmaParams.dt
_logger.info('Time step dt: {}'.format(dt))
PlasmaE = self.PlasmaE
# ======================================
# Push particles
# ======================================
with _ss.utils.progressbar(total=len(PlasmaE.PlasmaParams.xi_bubble), length=100) as myprog:
for i, xi in enumerate(PlasmaE.PlasmaParams.xi_bubble[0:-1]):
myprog.step = i+1
# ======================================
# Update positions
# ======================================
PlasmaE.x_coords[i+1, :] = PlasmaE.x_coords[i, :] + PlasmaE.bx_coords[i, :] * _spc.speed_of_light * dt
PlasmaE.y_coords[i+1, :] = PlasmaE.y_coords[i, :] + PlasmaE.by_coords[i, :] * _spc.speed_of_light * dt
# ======================================
# Get ion shape
# ======================================
self.PlasmaIons.add_ion_ellipse(PlasmaE.x_coords[i], PlasmaE.y_coords[i])
for j, (x, y, bx, by) in enumerate(zip(PlasmaE.x_coords[i, :], PlasmaE.y_coords[i, :], PlasmaE.bx_coords[i, :], PlasmaE.by_coords[i, :])):
# ======================================
# Get drive fields at particles
# ======================================
E = self.Drive.E_fields(x, y, xi) * self.Drive.gamma
# ======================================
# Get ion fields at particles
# ======================================
acc = _a(x, y, bx, by, E[0], E[1])
# ======================================
# Update velocities
# ======================================
PlasmaE.bx_coords[i+1, j] = PlasmaE.bx_coords[i, j] + acc[0] * dt
PlasmaE.by_coords[i+1, j] = PlasmaE.by_coords[i, j] + acc[1] * dt
self.PlasmaIons.add_ion_ellipse(PlasmaE.x_coords[-1], PlasmaE.y_coords[-1])
# ======================================
# Record completion timestamp
# ======================================
self._timestamp = _time.localtime()
self.PlasmaE._set_timestamp(self._timestamp)
self.PlasmaIons._set_timestamp(self._timestamp)
self.Drive._set_timestamp(self._timestamp)
@property
def PlasmaE(self):
"""
The plasma :class:`blowout.electrons.PlasmaE` used for the simulation.
"""
return self._PlasmaE
@property
def PlasmaIons(self):
"""
The plasma :class:`blowout.ions.PlasmaIons` used for the simulation.
"""
return self._PlasmaIons
@property
def Drive(self):
"""
The drive :class:`blowout.drive.Drive` used for the simulation.
"""
return self._Drive
def write(self, filename=None):
self.PlasmaE.PlasmaParams.write(filename=filename)
self.PlasmaIons.write(filename=filename)
self.PlasmaE.write(filename=filename)
self.Drive.write(filename=filename)
| {
"repo_name": "joelfrederico/Blowout",
"path": "blowout/simframework.py",
"copies": "1",
"size": "3950",
"license": "mit",
"hash": 932135096041423700,
"line_mean": 36.9807692308,
"line_max": 154,
"alpha_frac": 0.4455696203,
"autogenerated": false,
"ratio": 3.772683858643744,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47182534789437436,
"avg_score": null,
"num_lines": null
} |
from formulator.models import Form, FieldSet, Field
from django.utils.translation import ugettext_lazy as _
# FORM1
# =====
form_class = Form(name='adce jury registration')
form_class.save()
# Composition of a Fieldset
fieldset = FieldSet(form=form_class,
name='fieldset1',
legend='This is a legend')
fieldset.save()
# Composition of the fields
Field.objects.create( name="firstname",
field="CharField",
label=_('Your first name, ADCE jury?'),
formset=fieldset
)
Field.objects.create( name="lastname",
field="CharField",
label=_('Your last name, ADCE jury?:'),
formset=fieldset
)
Field.objects.create( name="country",
field="CharField",
attrs={"max_length":"30", "placeholder":"country here"},
formset=fieldset
)
# FORM2
# =====
form_class = Form(name='adce submitter registration')
form_class.save()
# Composition of a Fieldset
fieldset = FieldSet(form=form_class,
name='fieldset1',
legend='This is a legend')
fieldset.save()
# Composition of the fields
Field.objects.create( name="firstname",
field="CharField",
label=_('Your first name, ADCE submitter?'),
formset=fieldset
)
Field.objects.create( name="lastname",
field="CharField",
label=_('Your last name, ADCE submitter?:'),
formset=fieldset
)
| {
"repo_name": "Cahersan/SexySignOn",
"path": "multilogger/multilogger/register/factory.py",
"copies": "1",
"size": "1657",
"license": "bsd-3-clause",
"hash": -7222865718191314000,
"line_mean": 29.6851851852,
"line_max": 80,
"alpha_frac": 0.5334942667,
"autogenerated": false,
"ratio": 4.395225464190982,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5428719730890982,
"avg_score": null,
"num_lines": null
} |
from forseti.deployers.base import BaseDeployer
from forseti.models import GoldenEC2Instance
from forseti.utils import balloon_timer
class GoldenInstanceDeployer(BaseDeployer):
"""Deployer for ticketea's infrastructure"""
name = "golden_instances"
def __init__(self, application, configuration, command_args=None):
super(GoldenInstanceDeployer, self).__init__(application, configuration, command_args)
self.gold_instance = None
def create_ami_from_golden_instance(self):
"""
Create an AMI from a golden EC2 instance
"""
self.gold_instance = GoldenEC2Instance(
self.application,
self.configuration.get_gold_instance_configuration(self.application)
)
self.gold_instance.launch_and_wait()
self.gold_instance.provision(self.command_args)
ami_id = self.gold_instance.create_image()
self.gold_instance.terminate()
self.gold_instance = None
return ami_id
def generate_ami(self):
return self.create_ami_from_golden_instance()
def setup_autoscale(self, ami_id):
"""
Creates or updates the autoscale group, launch configuration, autoscaling
policies and CloudWatch alarms.
:param ami_id: AMI id used for the new autoscale system
"""
group = super(GoldenInstanceDeployer, self).setup_autoscale(ami_id)
print "Waiting until instances are up and running"
group.apply_launch_configuration_for_deployment()
print "All instances are running"
def deploy(self, ami_id=None):
"""
Do the code deployment in a golden instance and setup an autoscale group
with an AMI created from it.
:param ami_id: AMI id to be deployed. If it's `None`, a new one will be
created
"""
with balloon_timer("") as balloon:
if not ami_id:
ami_id = self.create_ami_from_golden_instance()
print "New AMI %s from golden instance" % ami_id
self.setup_autoscale(ami_id)
minutes, seconds = divmod(int(balloon.seconds_elapsed), 60)
print "Total deployment time: %02d:%02d" % (minutes, seconds)
| {
"repo_name": "ticketea/forseti",
"path": "forseti/deployers/golden_instance.py",
"copies": "1",
"size": "2238",
"license": "isc",
"hash": 4038913106673299500,
"line_mean": 34.5238095238,
"line_max": 94,
"alpha_frac": 0.6425379803,
"autogenerated": false,
"ratio": 4.129151291512915,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5271689271812915,
"avg_score": null,
"num_lines": null
} |
from fortdepend.units import FortranFile
from distutils import dir_util
import pytest
import os
class TestEmptyFortranFile:
def test_empty(self):
empty = FortranFile(filename='empty', readfile=False)
assert empty.filename == "empty"
assert empty.uses is None
assert empty.modules is None
assert empty.depends_on is None
class TestSimpleFortranFile:
@classmethod
def setup_class(cls):
cls.testfile = FortranFile(filename="file.f90", readfile=False)
def test_init(self):
assert self.testfile.filename == "file.f90"
def test_file_str(self):
assert str(self.testfile) == "file.f90"
def test_file_repr(self):
assert repr(self.testfile) == "FortranFile('file.f90')"
def test_get_empty_uses(self):
assert self.testfile.uses is None
assert self.testfile.get_uses() == []
def test_get_single_module(self):
contents = ['module modA',
'end module modA']
expected = {"modA": "FortranModule(module, 'moda', 'file.f90')"}
assert self.testfile.modules is None
module_list = self.testfile.get_modules(contents)
for key, value in expected.items():
assert key in module_list
assert repr(module_list[key]) == value
def test_get_multiple_modules(self):
contents = ['module modA',
'end module modA',
'module modB',
'end module modB']
expected = {"modA": "FortranModule(module, 'moda', 'file.f90')",
"modB": "FortranModule(module, 'modb', 'file.f90')"}
assert self.testfile.modules is None
module_list = self.testfile.get_modules(contents)
for key, value in expected.items():
assert key in module_list
assert repr(module_list[key]) == value
def test_module_with_module_procedure(self):
contents = ['module modA',
'module procedure foo',
'end module modA']
expected = {"modA": "FortranModule(module, 'moda', 'file.f90')"}
assert self.testfile.modules is None
module_list = self.testfile.get_modules(contents)
for key, value in expected.items():
assert key in module_list
assert repr(module_list[key]) == value
def test_get_program(self):
contents = ['program progA', 'end program progA']
expected = {"progA": "FortranModule(program, 'proga', 'file.f90')"}
assert self.testfile.modules is None
module_list = self.testfile.get_modules(contents)
for key, value in expected.items():
assert key in module_list
assert repr(module_list[key]) == value
def test_get_program_and_multiple_modules(self):
contents = ['program progA',
'end program progA',
'module modA',
'end module modA',
'module modB',
'end module modB']
expected = {"modA": "FortranModule(module, 'moda', 'file.f90')",
"modB": "FortranModule(module, 'modb', 'file.f90')",
"progA": "FortranModule(program, 'proga', 'file.f90')"}
assert self.testfile.modules is None
module_list = self.testfile.get_modules(contents)
for key, value in expected.items():
assert key in module_list
assert repr(module_list[key]) == value
def test_catch_unmatched_begin_end(self):
contents = ['module modA']
with pytest.raises(ValueError):
self.testfile.get_modules(contents)
def test_catch_unmatched_begin_end_2(self):
contents = ['module modA',
'end module',
'end module']
with pytest.raises(ValueError):
self.testfile.get_modules(contents)
@pytest.mark.usefixtures("datadir")
class TestReadFortranFile:
def test_empty_uses(self):
testfile = FortranFile(filename="moduleA.f90", readfile=True)
assert testfile.uses == []
def test_get_single_module(self):
testfile = FortranFile(filename="moduleA.f90", readfile=True)
expected = {"modA": "FortranModule(module, 'moda', 'moduleA.f90')"}
for key, value in expected.items():
assert key in testfile.modules
assert repr(testfile.modules[key]) == value
def test_get_program_and_multiple_modules(self):
testfile = FortranFile(filename="multiple_modules.f90", readfile=True)
expected = {"modA": "FortranModule(module, 'moda', 'multiple_modules.f90')",
"modB": "FortranModule(module, 'modb', 'multiple_modules.f90')",
"modC": "FortranModule(module, 'modc', 'multiple_modules.f90')",
"progA": "FortranModule(program, 'proga', 'multiple_modules.f90')"}
for key, value in expected.items():
assert key in testfile.modules
assert repr(testfile.modules[key]) == value
def test_single_uses(self):
testfile = FortranFile(filename="moduleB.f90", readfile=True)
assert testfile.uses == ['modA']
def test_multiple_uses(self):
testfile = FortranFile(filename="moduleC.f90", readfile=True)
assert set(testfile.uses) == set(['modA', 'modB'])
def test_multiple_uses_in_multiple_units(self):
testfile = FortranFile(filename="multiple_modules.f90", readfile=True)
assert set(testfile.uses) == set(['modA', 'modB', 'modC', 'iso_c_binding'])
def test_macro_replacement_dict(self):
testfile = FortranFile(filename="moduleC.f90", readfile=True,
macros={"modA": "module_A",
"modB": "module_B"})
assert sorted(testfile.uses) == sorted(["module_A", "module_B"])
def test_macro_replacement_list(self):
testfile = FortranFile(filename="moduleC.f90", readfile=True,
macros=["modA=module_A", "modB=module_B"])
assert sorted(testfile.uses) == sorted(["module_A", "module_B"])
def test_macro_replacement_single_value(self):
testfile = FortranFile(filename="moduleC.f90", readfile=True,
macros="modA=module_A")
assert sorted(testfile.uses) == sorted(["module_A", "modB"])
def test_conditional_include(self):
testfile = FortranFile(filename="preprocessor.f90", readfile=True,
macros=["FOO"])
assert testfile.uses == ['foo']
testfile2 = FortranFile(filename="preprocessor.f90", readfile=True)
assert sorted(testfile2.uses) == sorted(['bar', 'rawr'])
def test_no_preprocessor(self):
testfile = FortranFile(filename="preprocessor.f90", readfile=True,
macros=["FOO"], use_preprocessor=False)
assert sorted(testfile.uses) == sorted(['bar', 'foo', 'rawr'])
testfile2 = FortranFile(filename="preprocessor.f90", readfile=True,
use_preprocessor=False)
assert sorted(testfile2.uses) == sorted(['bar', 'foo', 'rawr'])
def test_include_file(self):
testfile = FortranFile(filename="preprocessor_include_file.F90", readfile=True,
macros=["CAT"], cpp_includes="some_include_dir")
assert testfile.uses == ['cat']
testfile2 = FortranFile(filename="preprocessor_include_file.F90", readfile=True)
assert sorted(testfile2.uses) == sorted(['dog', 'goat'])
| {
"repo_name": "ZedThree/fort_depend.py",
"path": "tests/test_fortranfile.py",
"copies": "1",
"size": "7607",
"license": "mit",
"hash": 430469125773238500,
"line_mean": 38.6197916667,
"line_max": 88,
"alpha_frac": 0.5906401998,
"autogenerated": false,
"ratio": 3.957856399583767,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.00042271930903788144,
"num_lines": 192
} |
from fort_dump import fort_dump
import yt
import numpy as np
from yt.units import parsec, Msun, gram, centimeter, second, Kelvin
from yt.fields.particle_fields import add_volume_weighted_smoothed_field
from astropy import units as u
from astropy import constants
def yt_from_jim(fname, n_ref=8):
"""
Load one of Jim's simulations into yt
Parameters
----------
n_ref : int
See http://yt-project.org/docs/3.0/examining/loading_data.html#indexing-criteria
It is the number of particles included per octree grid before refining that cell.
Higher numbers -> less noisy, lower numbers -> better resolution
"""
umassi,utimei,udisti,npart,gt,tkin,tgrav,tterm,escap,rho,poten,x,y,z,m,h,vx,vy,vz,u,iphase = fort_dump(fname)
# poten = potential energy of cloud [junk]
# escap = fraction of unbound mass (?)
# gt = global time
# tkin = total kinetic energy [code units]
# tgrav = total gravitational energy [code units]
# tterm = total t'ermal energy [code units]
# u = specific internal energy [ergs/g]
# Only keep the particles that are "turned on", or something like that
# (this is needed to remove the streaks from accreted particles that track
# the motion of the stars)
keep = iphase==0
ppx=x[keep]
ppy=y[keep]
ppz=z[keep]
ergpergram = udisti**2 / utimei**2
temperature = 2*ergpergram/constants.R.cgs.value*(2./3.)*u
# Temperatures above 1000 are ionized, therefore have smaller mean mol weight
temperature[temperature > 1000] /= 4.
data = {'particle_position_x': ppx,
'particle_position_y': ppy,
'particle_position_z': ppz,
'particle_velocity_x': vx[keep],
'particle_velocity_y': vy[keep],
'particle_velocity_z': vz[keep],
'particle_mass': m[keep],
'smoothing_length': h[keep],
'particle_temperature': temperature[keep]*Kelvin,
}
bbox = 1.1*np.array([[min(ppx), max(ppx)],
[min(ppy), max(ppy)],
[min(ppz), max(ppz)]])
ds = yt.load_particles(data,
length_unit=udisti*centimeter,
mass_unit=umassi*gram, n_ref=n_ref,
velocity_unit=udisti/utimei*centimeter/second,
time_unit=utimei*second,
sim_time=gt*utimei*second,
periodicity=(False,False,False),
bbox=bbox)
def _temperature(field, data):
ret = data[('all', "particle_temperature")] * Kelvin
return ret.in_units('K')
ds.add_field(('gas', "Temperature"), function=_temperature,
particle_type=True, units="K")
num_neighbors = 64
#fn = add_volume_weighted_smoothed_field('gas', "particle_position",
# "particle_mass",
# "smoothing_length", "density",
# "Temperature", ds, num_neighbors)
#ds.alias(("gas", "temperature"), fn[0])
return ds
| {
"repo_name": "keflavich/jimpy",
"path": "yt/to_yt.py",
"copies": "2",
"size": "3168",
"license": "bsd-2-clause",
"hash": -8348045228073967000,
"line_mean": 36.2705882353,
"line_max": 113,
"alpha_frac": 0.5729166667,
"autogenerated": false,
"ratio": 3.6164383561643834,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5189355022864383,
"avg_score": null,
"num_lines": null
} |
from fortpy.code import CodeParser
from . import builtin
import time
import re
import pyparsing
from . import rtupdate
#Time cache has expiration on the items inside that get used only
#temporarily during code completion
_time_caches = []
#This is our instance of the CodeParser. It handles the parsing
#of all the Fortran modules and has its own caching builtin.
_parsers = { "default": CodeParser() }
nester = pyparsing.nestedExpr("(",")")
#Get a generic module updater for doing real-time updates on
#source code sent from the emacs buffer.
def parser(key = "default"):
"""Returns the parser for the given key, (e.g. 'ssh')"""
#Make sure we have a parser for that key. If we don't, then set
#one up if we know what parameters to use; otherwise return the
#default parser.
if key not in _parsers:
if key == "ssh":
_parsers["ssh"] = CodeParser(True, False)
else:
key = "default"
return _parsers[key]
def clear_caches(delete_all=False):
"""Fortpy caches many things, that should be completed after each completion
finishes.
:param delete_all: Deletes also the cache that is normally not deleted,
like parser cache, which is important for faster parsing.
"""
global _time_caches
if delete_all:
_time_caches = []
_parser = { "default": CodeParser() }
else:
# normally just kill the expired entries, not all
for tc in _time_caches:
# check time_cache for expired entries
for key, (t, value) in list(tc.items()):
if t < time.time():
# delete expired entries
del tc[key]
def time_cache(time_add_setting):
""" This decorator works as follows: Call it with a setting and after that
use the function with a callable that returns the key.
But: This function is only called if the key is not available. After a
certain amount of time (`time_add_setting`) the cache is invalid.
"""
def _temp(key_func):
dct = {}
_time_caches.append(dct)
def wrapper(optional_callable, *args, **kwargs):
key = key_func(*args, **kwargs)
value = None
if key in dct:
expiry, value = dct[key]
if expiry > time.time():
return value
value = optional_callable()
time_add = getattr(settings, time_add_setting)
if key is not None:
dct[key] = time.time() + time_add, value
return value
return wrapper
return _temp
@time_cache("call_signatures_validity")
def cache_call_signatures(source, user_pos, stmt):
"""This function calculates the cache key."""
index = user_pos[0] - 1
lines = source.splitlines() or ['']
if source and source[-1] == '\n':
lines.append('')
before_cursor = lines[index][:user_pos[1]]
other_lines = lines[stmt.start_pos[0]:index]
whole = '\n'.join(other_lines + [before_cursor])
before_bracket = re.match(r'.*\(', whole, re.DOTALL)
module_path = stmt.get_parent_until().path
return None if module_path is None else (module_path, before_bracket, stmt.start_pos)
rt = rtupdate.ModuleUpdater()
#Setup and compile a bunch of regular expressions that we use
#every time the user context needs to be determined.
RE_COMMENTS = re.compile("\n\s*!")
_RX_MODULE = r"(\n|^)\s*module\s+(?P<name>[a-z0-9_]+)"
RE_MODULE = re.compile(_RX_MODULE, re.I)
_RX_TYPE = (r"\s+type(?P<modifiers>,\s+(public|private))?(\s+::)?"
"\s+(?P<name>[A-Za-z0-9_]+)")
RE_TYPE = re.compile(_RX_TYPE)
_RX_EXEC = r"\n\s*((?P<type>character|real|type|logical|integer)?" + \
r"(?P<kind>\([a-z0-9_]+\))?)?(,(?P<modifiers>[^\n]+?))?\s*" + \
r"(?P<codetype>subroutine|function)\s+(?P<name>[^(]+)" + \
r"\s*\((?P<parameters>[^)]+)\)"
RE_EXEC = re.compile(_RX_EXEC, re.I)
RE_MEMBERS = parser().modulep.vparser.RE_MEMBERS
_RX_DEPEND = r"^\s*(?P<sub>call\s+)?(?P<exec>[a-z0-9_%]+)\s*(?P<args>\([^\n]+)$"
RE_DEPEND = re.compile(_RX_DEPEND, re.M | re. I)
_RX_CURSOR = r"(?P<symbol>[^\s=,%(]+)"
RE_CURSOR = re.compile(_RX_CURSOR, re.I)
_RX_FULL_CURSOR = r"(?P<symbol>[^\s=,(]+)"
RE_FULL_CURSOR = re.compile(_RX_FULL_CURSOR, re.I)
#A list of all the function names that are 'builtin' in Fortran
builtin = builtin.load(_parsers["default"].modulep.docparser, _parsers["default"].serialize)
_common_builtin = [ "OPEN", "CLOSE", "PRESENT", "ABS", "DIM", "ALLOCATE", "SQRT"]
common_builtin = {}
for fun in _common_builtin:
common_builtin[fun.lower()] = fun
| {
"repo_name": "rosenbrockc/fortpy",
"path": "fortpy/isense/cache.py",
"copies": "1",
"size": "4648",
"license": "mit",
"hash": 1832346601850006500,
"line_mean": 36.7886178862,
"line_max": 92,
"alpha_frac": 0.6090791738,
"autogenerated": false,
"ratio": 3.445515196441809,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9525381478095225,
"avg_score": 0.005842578429316943,
"num_lines": 123
} |
from fortpy.elements import Function, Subroutine, CustomType, ValueElement
from fortpy.elements import Module, Executable, Interface
from fortpy.docelements import DocElement
from . import cache
from .classes import Completion
class Evaluator(object):
"""Uses the user context and code parsers to perform code
completion and definition lookups.
"""
def __init__(self, context, pos):
"""Create a new evaluator for the given context.
:arg context: an instance of UserContext for the given source
and position.
"""
self.context = context
self.line, self.column = pos
#Initialize the lazy variables
self._names = None
self._possible = None
@property
def element(self):
"""Finds the instance of the parsed element in the code parser
using the name given in the context."""
return self.context.element
@property
def names(self):
"""Returns a list of possible completions for the symbol under the
cursor in the current user context."""
#This is where the context information is extremely useful in
#limiting the extent of the search space we need to examine.
if self._names is None:
attribute = self.get_attribute()
if self.context.module is not None:
symbol = self.context.symbol
fullsymbol = self.context.full_symbol
self._names = self._complete_el(symbol, attribute, fullsymbol)
else:
self._names = []
return self._names
def bracket_complete(self):
"""Returns a function call signature for completion whenever
a bracket '(' is pressed."""
#The important thing to keep track of here is that '(' can be
#pushed in the following places:
# - in a subroutine/function definition
# - when calling a function or subroutine, this includes calls within
# the argument list of a function, e.g. function(a, fnb(c,d), e)
# - when specifying the dimensions of an array for element selection
# - inside of if/do/while blocks.
#If there is a \s immediately preceding the bracket, then short_symbol
#will be null string and we are most likely doing arithmetic of some
#sort or a block statement.
if self.context.short_symbol == "":
return {}
line = self.context.current_line.lower()[:self.context.pos[1]-1]
if "subroutine" in line or "function" in line:
#We are in the definition of the subroutine or function. They
#are choosing the parameter names so we don't offer any suggestions.
return {}
#Sometimes people do if() with the condition immediately after
#the keyword, this regex will catch that.
symbol = self.context.short_symbol.lower()
if symbol in ["if", "do", "while", "elseif", "case", "associate"]:
return {}
#All that should be left now are dimensions and legitimate function
#calls.
fullsymbol = self.context.short_full_symbol.lower()
return self._bracket_complete_sig(symbol, fullsymbol)
def _bracket_complete_sig(self, symbol, fullsymbol):
"""Returns the call signature and docstring for the executable
immediately preceding a bracket '(' that was typed."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be the signature of the member method.
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
if symbol in target.executables:
child = target.executables[symbol]
return self._compile_signature(child.target, child.name)
elif symbol in target.members:
#We are dealing with a dimension request on an array that
#is a member of the type.
child = target.members[symbol]
return self._bracket_dim_suggest(child)
else:
return {}
else:
#We must be dealing with a regular executable or builtin fxn
#or a regular variable dimension.
iexec = self._bracket_exact_exec(symbol)
if iexec is not None:
#It is indeed a function we are completing for.
return self._compile_signature(iexec, iexec.name)
else:
#We need to look at local and global variables to find the
#variable declaration and dimensionality.
ivar = self._bracket_exact_var(symbol)
return self._bracket_dim_suggest(ivar)
def _bracket_dim_suggest(self, variable):
"""Returns a dictionary of documentation for helping complete the
dimensions of a variable."""
if variable is not None:
#Look for <dimension> descriptors that are children of the variable
#in its docstrings.
dims = variable.doc_children("dimension", ["member", "parameter", "local"])
descript = str(variable)
if len(dims) > 0:
descript += " | " + " ".join([DocElement.format_dimension(d) for d in dims])
return dict(
params=[variable.dimension],
index=0,
call_name=variable.name,
description=descript,
)
else:
return []
def get_definition(self):
"""Checks variable and executable code elements based on the current
context for a code element whose name matches context.exact_match
perfectly.
"""
#Check the variables first, then the functions.
match = self._bracket_exact_var(self.context.exact_match)
if match is None:
match = self._bracket_exact_exec(self.context.exact_match)
return match
def _bracket_exact_var(self, symbol):
"""Checks local first and then module global variables for an exact
match to the specified symbol name."""
if isinstance(self.element, Executable):
if symbol in self.element.parameters:
return self.element.parameters[symbol]
if symbol in self.element.members:
return self.element.members[symbol]
if symbol in self.element.module.members:
return self.element.module.members[symbol]
return None
def _bracket_exact_exec(self, symbol):
"""Checks builtin, local and global executable collections for the
specified symbol and returns it as soon as it is found."""
if symbol in self.context.module.executables:
return self.context.module.executables[symbol]
if symbol in self.context.module.interfaces:
return self.context.module.interfaces[symbol]
if symbol in cache.builtin:
return cache.builtin[symbol]
#Loop through all the dependencies of the current module and see
#if one of them is the method we are looking for.
return self.context.module.get_dependency_element(symbol)
def _compile_signature(self, iexec, call_name):
"""Compiles the signature for the specified executable and returns
as a dictionary."""
if iexec is not None:
summary = iexec.summary
if isinstance(iexec, Function):
summary = iexec.returns + "| " + iexec.summary
elif isinstance(iexec, Subroutine) and len(iexec.modifiers) > 0:
summary = ", ".join(iexec.modifiers) + " | " + iexec.summary
elif isinstance(iexec, Interface):
summary = iexec.describe()
else:
summary = iexec.summary
#Add the name of the module who owns the method. Useful in case the
#same executable is defined in multiple modules, but only one is
#referenced in the current context.
if iexec.parent is not None:
summary += " | MODULE: {}".format(iexec.module.name)
else:
summary += " | BUILTIN"
return dict(
params=[p.name for p in iexec.ordered_parameters],
index=0,
call_name=call_name,
description=summary,
)
else:
return []
def in_function_call(self):
"""This function is called whenever the cursor/buffer goes idle for
a second. The real workhorse of the intellisense. Decides what kind
of intellisense is needed and returns the relevant response."""
#See if we are calling a function inside a module or other function.
result = []
if (self.context.el_section == "body" and
self.context.el_call in [ "sub", "fun" ]):
#Do a signature completion for the function/subroutine call.
result = self.signature()
if result == []:
return self.complete()
return result
def signature(self):
"""Gets completion or call signature information for the current cursor."""
#We can't really do anything sensible without the name of the function
#whose signature we are completing.
iexec, execmod = self.context.parser.tree_find(self.context.el_name,
self.context.module, "executables")
if iexec is None:
#Look in the interfaces next using a tree find as well
iexec, execmod = self.context.parser.tree_find(self.context.el_name, self.context.module,
"interfaces")
if iexec is None:
return []
return self._signature_index(iexec)
def _signature_index(self, iexec):
"""Determines where in the call signature the cursor is to decide which
parameter needs to have its information returned for the intellisense.
"""
#Find out where in the signature the cursor is at the moment.
call_index = self.context.call_arg_index
if call_index is not None:
#We found the index of the parameter whose docstring we want
#to return.
param = iexec.get_parameter(call_index)
paramlist = [ p.name for p in iexec.ordered_parameters ]
paramlist[call_index] = "*{}*".format(paramlist[call_index])
if not isinstance(param, list) and param is not None:
#Write a nice description that includes the parameter type and
#intent as well as dimension.
summary = "{} | {}".format(str(param), param.summary)
#We also want to determine if this parameter has its value changed
#by the function we are completing on.
changedby = iexec.changed(param.name)
if changedby is not None:
summary += " *MODIFIED*"
elif isinstance(param, list) and len(param) > 0:
act_type = []
for iparam in param:
if iparam is not None and iparam.strtype not in act_type:
act_type.append(iparam.strtype)
act_text = ', '.join(act_type)
summary = "SUMMARY: {} | ACCEPTS: {}".format(param[0].summary, act_text)
if iexec.changed(param[0].name):
summary += " | *MODIFIED*"
else:
summary = "No matching variable definition."
#Add the name of the module who owns the executable.
summary += " | MODULE: {}".format(iexec.module.name)
return dict(
params=paramlist,
index=call_index,
call_name=self.context.el_name,
description=summary,
)
else:
return result
def complete(self):
"""Gets a list of completion objects for the symbol under the cursor."""
if self._possible is None:
self._possible = []
for possible in self.names:
c = Completion(self.context, self.names[possible], len(self.context.symbol))
self._possible.append(c)
return self._possible
def _symbol_in(self, symbol, name):
"""Checks whether the specified symbol is part of the name for completion."""
lsymbol = symbol.lower()
lname = name.lower()
return lsymbol == lname[:len(symbol)] or "_" + lsymbol in lname
def _complete_el(self, symbol, attribute, fullsymbol):
"""Suggests a list of completions based on the el_* attributes
of the user_context."""
if symbol != fullsymbol:
#We have a sym%sym%... chain and the completion just needs to
#be a member variable or method of the type being referenced.
return self._complete_type_chain(symbol, fullsymbol)
if self.context.el_section == "params":
#They are in the process of defining a new executable and are
#picking the names themselves, return normal word complete.
return self._complete_word(symbol, attribute)
elif self.context.el_section == "body":
if self.context.el_call in ["sub", "fun"]:
return self._complete_sig(symbol, attribute)
else:
return self._complete_word(symbol, attribute)
else:
return self._complete_word(symbol, attribute)
def _get_chain_parent_symbol(self, symbol, fullsymbol):
"""Gets the code element object for the parent of the specified
symbol in the fullsymbol chain."""
#We are only interested in the type of the variable immediately preceding our symbol
#in the chain so we can list its members.
chain = fullsymbol.split("%")
#We assume that if symbol != fullsymbol, we have at least a % at the end that
#tricked the symbol regex.
if len(chain) < 2:
return ([], None)
previous = chain[-2].lower()
#Now we need to use the name of the variable to find the actual type name
target_name = ""
if previous in self.element.members:
target_name = self.element.members[previous].kind
#The contextual element could be a module, in which case it has no parameters
if hasattr(self.element, "parameters") and previous in self.element.parameters:
target_name = self.element.parameters[previous].kind
if target_name == "":
return (None, None)
return self.context.parser.tree_find(target_name, self.context.module, "types")
def _complete_type_chain(self, symbol, fullsymbol):
"""Suggests completion for the end of a type chain."""
target, targmod = self._get_chain_parent_symbol(symbol, fullsymbol)
if target is None:
return {}
result = {}
#We might know what kind of symbol to limit the completion by depending on whether
#it was preceded by a "call " for example. Check the context's el_call
if symbol != "":
if self.context.el_call != "sub":
for mkey in target.members:
if self._symbol_in(symbol, mkey):
result[mkey] = target.members[mkey]
for ekey in target.executables:
if (self._symbol_in(symbol, ekey)):
if self.context.el_call == "sub":
if (isinstance(target.executables[ekey], Subroutine)):
result[ekey] = target.executables[ekey]
else:
if (isinstance(target.executables[ekey], Function)):
result[ekey] = target.executables[ekey]
else:
if self.context.el_call != "sub":
result.update(target.members)
subdict = {k: target.executables[k] for k in target.executables
if isinstance(target.executables[k].target, Function)}
result.update(subdict)
else:
subdict = {k: target.executables[k] for k in target.executables
if isinstance(target.executables[k].target, Subroutine)}
result.update(subdict)
return result
def _complete_sig(self, symbol, attribute):
"""Suggests completion for calling a function or subroutine."""
#Return a list of valid parameters for the function being called
fncall = self.context.el_name
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables")
if iexec is None:
#Try the interfaces as a possible executable to complete.
iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "interfaces")
if iexec is not None:
if symbol == "":
return iexec.parameters
else:
result = {}
for ikey in iexec.parameters:
if self._symbol_in(symbol, ikey):
result[ikey] = iexec.parameters[ikey]
return result
else:
return self._complete_word(symbol, attribute)
def _complete_word(self, symbol, attribute):
"""Suggests context completions based exclusively on the word
preceding the cursor."""
#The cursor is after a %(,\s and the user is looking for a list
#of possibilities that is a bit smarter that regular AC.
if self.context.el_call in ["sub", "fun", "assign", "arith"]:
if symbol == "":
#The only possibilities are local vars, global vars or functions
#presented in that order of likelihood.
return self._complete_values()
else:
#It is also possible that subroutines are being called, but that
#the full name hasn't been entered yet.
return self._complete_values(symbol)
else:
return self.context.module.completions(symbol, attribute, True)
def _generic_filter_execs(self, module):
"""Filters the specified dict of executables to include only those that are not referenced
in a derived type or an interface.
:arg module: the module whose executables should be filtered.
"""
interface_execs = []
for ikey in module.interfaces:
interface_execs.extend(module.interfaces[ikey].procedures)
return {k: module.executables[k] for k in module.executables if
("{}.{}".format(module.name, k) not in interface_execs and
not module.executables[k].is_type_target)}
def _complete_values(self, symbol = ""):
"""Compiles a list of possible symbols that can hold a value in
place. These consist of local vars, global vars, and functions."""
result = {}
#Also add the subroutines from the module and its dependencies.
moddict = self._generic_filter_execs(self.context.module)
self._cond_update(result, moddict, symbol)
self._cond_update(result, self.context.module.interfaces, symbol)
for depend in self.context.module.dependencies:
if depend in self.context.module.parent.modules:
#We don't want to display executables that are part of an interface, or that are embedded in
#a derived type, since those will be called through the type or interface
filtdict = self._generic_filter_execs(self.context.module.parent.modules[depend])
self._cond_update(result, filtdict, symbol)
self._cond_update(result, self.context.module.parent.modules[depend].interfaces, symbol)
#Add all the local vars if we are in an executable
if (isinstance(self.context.element, Function) or
isinstance(self.context.element, Subroutine)):
self._cond_update(result, self.element.members, symbol)
#Next add the global variables from the module
if self.context.module is not None:
self._cond_update(result, self.context.module.members, symbol)
#Next add user defined functions to the mix
for execkey in self.context.module.executables:
iexec = self.context.module.executables[execkey]
if isinstance(iexec, Function) and self._symbol_in(symbol, iexec.name):
result[iexec.name] = iexec
#Finally add the builtin functions to the mix. We need to add support
#for these in a separate file so we have their call signatures.
if symbol == "":
#Use the abbreviated list of most common fortran builtins
self._cond_update(result, cache.common_builtin, symbol)
else:
#we can use the full list as there will probably not be that
#many left over.
self._cond_update(result, cache.builtin, symbol)
return result
def _cond_update(self, first, second, symbol, maxadd = -1):
"""Overwrites the keys and values in the first dictionary with those
of the second as long as the symbol matches part of the key.
:arg maxadd: specifies a limit on the number of entries from the second
dict that will be added to the first."""
if symbol != "":
added = 0
for key in second:
if self._symbol_in(symbol, key) and (maxadd == -1 or added <= maxadd):
first[key] = second[key]
added += 1
else:
first.update(second)
def get_attribute(self):
"""Gets the appropriate module attribute name for a collection
corresponding to the context's element type."""
attributes = ['dependencies', 'publics', 'members',
'types', 'executables']
#Find the correct attribute based on the type of the context
if self.context.el_type in [Function, Subroutine]:
attribute = attributes[4]
elif self.context.el_type == CustomType:
attribute = attributes[3]
else:
attribute = attributes[2]
return attribute
| {
"repo_name": "rosenbrockc/fortpy",
"path": "fortpy/isense/evaluator.py",
"copies": "1",
"size": "22589",
"license": "mit",
"hash": -2181635860780981200,
"line_mean": 43.8194444444,
"line_max": 108,
"alpha_frac": 0.591881004,
"autogenerated": false,
"ratio": 4.589394555058919,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5681275559058919,
"avg_score": null,
"num_lines": null
} |
from forwarder import OSCUDPServerForwarder
from collections import defaultdict
import reloading_tabview as t
import logging
logging.disable(logging.CRITICAL)
class OscDataPresenter:
def __init__(self, serverA, serverB):
self.serverA = serverA
self.serverB = serverB
def cols(self):
return ["Address", self.serverA.identifier, self.serverB.identifier]
def data(self):
d = defaultdict(lambda: list([None, None]))
for k,v in self.serverA.vals.items():
d[k][0] = v
for k,v in self.serverB.vals.items():
d[k][1] = v
data = [[k, d[k][0], d[k][1]] for k in sorted(d)]
data.insert(0, self.cols())
return data
controller_ip = "192.168.0.105"
server_ip = "0.0.0.0"
# Connect lemur outgoing to server_ip:9002, 9002 is arbitrary
# Messages from lemur will be forwarded to server_ip:8002
controller_to_server = OSCUDPServerForwarder("Lemur", (server_ip, 9002), (server_ip, 8002))
# Connect server outgoing to server_ip:8000
# Messages from server will be forwarded to controller_ip:8000
server_to_controller = OSCUDPServerForwarder("Resolume", (server_ip, 8000), (controller_ip, 8000))
controller_to_server.start()
server_to_controller.start()
presenter = OscDataPresenter(controller_to_server, server_to_controller)
t.view(presenter.data)
| {
"repo_name": "philipbjorge/osc-spy",
"path": "main.py",
"copies": "1",
"size": "1295",
"license": "mit",
"hash": 8717787018765786000,
"line_mean": 27.7777777778,
"line_max": 98,
"alpha_frac": 0.7150579151,
"autogenerated": false,
"ratio": 3.105515587529976,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9277381445760382,
"avg_score": 0.00863841137391862,
"num_lines": 45
} |
from ._forward import ForwardPasser
from ._pruning import PruningPasser, FEAT_IMP_CRITERIA
from ._util import ascii_table, apply_weights_2d, gcv
from ._types import BOOL
from sklearn.base import RegressorMixin, BaseEstimator, TransformerMixin
from sklearn.utils.validation import (assert_all_finite, check_is_fitted,
check_X_y)
import numpy as np
from scipy import sparse
from ._version import get_versions
__version__ = get_versions()['version']
class Earth(BaseEstimator, RegressorMixin, TransformerMixin):
"""
Multivariate Adaptive Regression Splines
A flexible regression method that automatically searches for interactions
and non-linear relationships. Earth models can be thought of as
linear models in a higher dimensional basis space
(specifically, a multivariate truncated power spline basis).
Each term in an Earth model is a product of so called "hinge functions".
A hinge function is a function that's equal to its argument where that
argument is greater than zero and is zero everywhere else.
The multivariate adaptive regression splines algorithm has two stages.
First, the forward pass searches for terms in the truncated power spline
basis that locally minimize the squared error loss of the training set.
Next, a pruning pass selects a subset of those terms that produces
a locally minimal generalized cross-validation (GCV) score. The GCV score
is not actually based on cross-validation, but rather is meant to
approximate a true cross-validation score by penalizing model complexity.
The final result is a set of terms that is nonlinear in the original
feature space, may include interactions, and is likely to generalize well.
The Earth class supports dense input only. Data structures from the
pandas and patsy modules are supported, but are copied into numpy arrays
for computation. No copy is made if the inputs are numpy float64 arrays.
Earth objects can be serialized using the pickle module and copied
using the copy module.
Parameters
----------
max_terms : int, optional (default=min(2 * n + m // 10, 400)),
where n is the number of features and m is the number
of rows)
The maximum number of terms generated by the forward pass. All memory is
allocated at the beginning of the forward pass, so setting max_terms to
a very high number on a system with insufficient memory may cause a
MemoryError at the start of the forward pass.
max_degree : int, optional (default=1)
The maximum degree of terms generated by the forward pass.
allow_missing : boolean, optional (default=False)
If True, use missing data method described in [3].
Use missing argument to determine missingness or,if X is a pandas
DataFrame, infer missingness from X.
penalty : float, optional (default=3.0)
A smoothing parameter used to calculate GCV and GRSQ.
Used during the pruning pass and to determine whether to add a hinge
or linear basis function during the forward pass.
See the d parameter in equation 32, Friedman, 1991.
endspan_alpha : float, optional, probability between 0 and 1 (default=0.05)
A parameter controlling the calculation of the endspan
parameter (below). The endspan parameter is calculated as
round(3 - log2(endspan_alpha/n)), where n is the number of features.
The endspan_alpha parameter represents the probability of a run of
positive or negative error values on either end of the data vector
of any feature in the data set. See equation 45, Friedman, 1991.
endspan : int, optional (default=-1)
The number of extreme data values of each feature not eligible
as knot locations. If endspan is set to -1 (default) then the
endspan parameter is calculated based on endspan_alpah (above).
If endspan is set to a positive integer then endspan_alpha is ignored.
minspan_alpha : float, optional, probability between 0 and 1 (default=0.05)
A parameter controlling the calculation of the minspan
parameter (below). The minspan parameter is calculated as
(int) -log2(-(1.0/(n*count))*log(1.0-minspan_alpha)) / 2.5
where n is the number of features and count is the number of points at
which the parent term is non-zero. The minspan_alpha parameter
represents the probability of a run of positive or negative error
values between adjacent knots separated by minspan intervening
data points. See equation 43, Friedman, 1991.
minspan : int, optional (default=-1)
The minimal number of data points between knots. If minspan is set
to -1 (default) then the minspan parameter is calculated based on
minspan_alpha (above). If minspan is set to a positive integer then
minspan_alpha is ignored.
thresh : float, optional (default=0.001)
Parameter used when evaluating stopping conditions for the forward
pass. If either RSQ > 1 - thresh or if RSQ increases by less than
thresh for a forward pass iteration then the forward pass is
terminated.
zero_tol : float, optional (default=1e-12)
Used when determining whether a floating point number is zero during
the forward pass. This is important in determining linear dependence
and in the fast update procedure. There should normally be no reason
to change zero_tol from its default. However, if nans are showing up
during the forward pass or the forward pass seems to be terminating
unexpectedly, consider adjusting zero_tol.
min_search_points : int, optional (default=100)
Used to calculate check_every (below). The minimum samples necessary
for check_every to be greater than 1. The check_every parameter
is calculated as
(int) m / min_search_points
if m > min_search_points, where m is the number of samples in the
training set. If m <= min_search_points then check_every is set to 1.
check_every : int, optional (default=-1)
If check_every > 0, only one of every check_every sorted data points
is considered as a candidate knot. If check_every is set to -1 then
the check_every parameter is calculated based on
min_search_points (above).
allow_linear : bool, optional (default=True)
If True, the forward pass will check the GCV of each new pair of terms
and, if it's not an improvement on a single term with no knot (called a
linear term, although it may actually be a product of a linear term
with some other parent term), then only that single, knotless term will
be used. If False, that behavior is disabled and all terms will have
knots except those with variables specified by the linvars argument
(see the fit method).
use_fast : bool, optional (default=False)
if True, use the approximation procedure defined in [2] to speed up the
forward pass. The procedure uses two hyper-parameters : fast_K
and fast_h. Check below for more details.
fast_K : int, optional (default=5)
Only used if use_fast is True. As defined in [2], section 3.0, it
defines the maximum number of basis functions to look at when
we search for a parent, that is we look at only the fast_K top
terms ranked by the mean squared error of the model the last time
the term was chosen as a parent. The smaller fast_K is, the more
gains in speed we get but the more approximate is the result.
If fast_K is the maximum number of terms and fast_h is 1,
the behavior is the same as in the normal case
(when use_fast is False).
fast_h : int, optional (default=1)
Only used if use_fast is True. As defined in [2], section 4.0, it
determines the number of iterations before repassing through all
the variables when searching for the variable to use for a
given parent term. Before reaching fast_h number of iterations
only the last chosen variable for the parent term is used. The
bigger fast_h is, the more speed gains we get, but the result
is more approximate.
smooth : bool, optional (default=False)
If True, the model will be smoothed such that it has continuous first
derivatives.
For details, see section 3.7, Friedman, 1991.
enable_pruning : bool, optional(default=True)
If False, the pruning pass will be skipped.
feature_importance_type: string or list of strings, optional (default=None)
Specify which kind of feature importance criteria to compute.
Currently three criteria are supported : 'gcv', 'rss' and 'nb_subsets'.
By default (when it is None), no feature importance is computed.
Feature importance is a measure of the effect of the features
on the outputs. For each feature, the values go from
0 to 1 and sum up to 1. A high value means the feature have in average
(over the population) a large effect on the outputs.
See [4], section 12.3 for more information about the criteria.
verbose : int, optional(default=0)
If verbose >= 1, print out progress information during fitting. If
verbose >= 2, also print out information on numerical difficulties
if encountered during fitting. If verbose >= 3, print even more
information that is probably only useful to the developers of py-earth.
Attributes
----------
`coef_` : array, shape = [pruned basis length, number of outputs]
The weights of the model terms that have not been pruned.
`basis_` : _basis.Basis
An object representing model terms. Each term is a product of
constant, linear, and hinge functions of the input features.
`mse_` : float
The mean squared error of the model after the final linear fit.
If sample_weight and/or output_weight are given, this score is
weighted appropriately.
`rsq_` : float
The generalized r^2 of the model after the final linear fit.
If sample_weight and/or output_weight are given, this score is
weighted appropriately.
`gcv_` : float
The generalized cross validation (GCV) score of the model after the
final linear fit. If sample_weight and/or output_weight are
given, this score is weighted appropriately.
`grsq_` : float
An r^2 like score based on the GCV. If sample_weight and/or
output_weight are given, this score is
weighted appropriately.
`forward_pass_record_` : _record.ForwardPassRecord
An object containing information about the forward pass, such as
training loss function values after each iteration and the final
stopping condition.
`pruning_pass_record_` : _record.PruningPassRecord
An object containing information about the pruning pass, such as
training loss function values after each iteration and the
selected optimal iteration.
`xlabels_` : list
List of column names for training predictors.
Defaults to ['x0','x1',....] if column names are not provided.
`allow_missing_` : list
List of booleans indicating whether each variable is allowed to
be missing. Set during training. A variable may be missing
only if fitting included missing data for that variable.
`feature_importances_`: array of shape [m] or dict
m is the number of features.
if one feature importance type is specified, it is an
array of shape m. If several feature importance types are
specified, then it is dict where each key is a feature importance type
name and its corresponding value is an array of shape m.
`_version`: string
The version of py-earth in which the Earth object was originally
created. This information may be useful when dealing with
serialized Earth objects.
References
----------
.. [1] Friedman, Jerome. Multivariate Adaptive Regression Splines.
Annals of Statistics. Volume 19, Number 1 (1991), 1-67.
.. [2] Fast MARS, Jerome H.Friedman, Technical Report No.110, May 1993.
.. [3] Estimating Functions of Mixed Ordinal and Categorical Variables
Using Adaptive Splines, Jerome H.Friedman, Technical Report
No.108, June 1991.
.. [4] http://www.milbo.org/doc/earth-notes.pdf
"""
forward_pass_arg_names = set([
'max_terms', 'max_degree', 'allow_missing', 'penalty',
'endspan_alpha', 'endspan',
'minspan_alpha', 'minspan',
'thresh', 'zero_tol', 'min_search_points',
'check_every', 'allow_linear',
'use_fast', 'fast_K', 'fast_h',
'feature_importance_type',
'verbose'
])
pruning_pass_arg_names = set([
'penalty',
'feature_importance_type',
'verbose'
])
def __init__(self, max_terms=None, max_degree=None, allow_missing=False,
penalty=None, endspan_alpha=None, endspan=None,
minspan_alpha=None, minspan=None,
thresh=None, zero_tol=None, min_search_points=None,
check_every=None,
allow_linear=None, use_fast=None, fast_K=None,
fast_h=None, smooth=None, enable_pruning=True,
feature_importance_type=None, verbose=0):
self.max_terms = max_terms
self.max_degree = max_degree
self.allow_missing = allow_missing
self.penalty = penalty
self.endspan_alpha = endspan_alpha
self.endspan = endspan
self.minspan_alpha = minspan_alpha
self.minspan = minspan
self.thresh = thresh
self.zero_tol = zero_tol
self.min_search_points = min_search_points
self.check_every = check_every
self.allow_linear = allow_linear
self.use_fast = use_fast
self.fast_K = fast_K
self.fast_h = fast_h
self.smooth = smooth
self.enable_pruning = enable_pruning
self.feature_importance_type = feature_importance_type
self.verbose = verbose
self._version = __version__
def __eq__(self, other):
if self.__class__ is not other.__class__:
return False
keys = set(self.__dict__.keys()) | set(other.__dict__.keys())
for k in keys:
try:
v_self = self.__dict__[k]
v_other = other.__dict__[k]
except KeyError:
return False
try:
if v_self != v_other:
return False
except ValueError: # Case of numpy arrays
if np.any(v_self != v_other):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def _pull_forward_args(self, **kwargs):
'''
Pull named arguments relevant to the forward pass.
'''
result = {}
for name in self.forward_pass_arg_names:
if name in kwargs and kwargs[name] is not None:
result[name] = kwargs[name]
return result
def _pull_pruning_args(self, **kwargs):
'''
Pull named arguments relevant to the pruning pass.
'''
result = {}
for name in self.pruning_pass_arg_names:
if name in kwargs and kwargs[name] is not None:
result[name] = kwargs[name]
return result
def _scrape_labels(self, X):
'''
Try to get labels from input data (for example, if X is a
pandas DataFrame). Return None if no labels can be extracted.
'''
try:
labels = list(X.columns)
except AttributeError:
try:
labels = list(X.design_info.column_names)
except AttributeError:
try:
labels = list(X.dtype.names)
except TypeError:
try:
labels = ['x%d' % i for i in range(X.shape[1])]
except IndexError:
labels = ['x%d' % i for i in range(1)]
# handle case where X is not np.array (e.g list)
except AttributeError:
X = np.array(X)
labels = ['x%d' % i for i in range(X.shape[1])]
return labels
def _scrub_x(self, X, missing, **kwargs):
'''
Sanitize input predictors and extract column names if appropriate.
'''
# Check for sparseness
if sparse.issparse(X):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use X.toarray() to convert to '
'dense.')
X = np.asarray(X, dtype=np.float64, order='F')
# Figure out missingness
missing_is_nan = False
if missing is None:
# Infer missingness
missing = np.isnan(X)
missing_is_nan = True
if not self.allow_missing:
try:
assert_all_finite(X)
except ValueError:
raise ValueError(
"Input contains NaN, infinity or a value that's too large."
"Did you mean to set allow_missing=True?")
if X.ndim == 1:
X = X[:, np.newaxis]
# Ensure correct number of columns
if hasattr(self, 'basis_') and self.basis_ is not None:
if X.shape[1] != self.basis_.num_variables:
raise ValueError('Wrong number of columns in X. Reshape your data.')
# Zero-out any missing spots in X
if np.any(missing):
if not self.allow_missing:
raise ValueError('Missing data requires allow_missing=True.')
if missing_is_nan or np.any(np.isnan(X)):
X = X.copy()
X[missing] = 0.
# Convert to internally used data type
missing = np.asarray(missing, dtype=BOOL, order='F')
assert_all_finite(missing)
if missing.ndim == 1:
missing = missing[:, np.newaxis]
return X, missing
def _scrub(self, X, y, sample_weight, output_weight, missing, **kwargs):
'''
Sanitize input data.
'''
# Check for sparseness
if sparse.issparse(y):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use y.toarray() to convert to '
'dense.')
if sparse.issparse(sample_weight):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use sample_weight.toarray()'
'to convert to dense.')
if sparse.issparse(output_weight):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use output_weight.toarray()'
'to convert to dense.')
# Check whether X is the output of patsy.dmatrices
if y is None and isinstance(X, tuple):
y, X = X
# Handle X separately
X, missing = self._scrub_x(X, missing, **kwargs)
# Convert y to internally used data type
y = np.asarray(y, dtype=np.float64)
assert_all_finite(y)
if len(y.shape) == 1:
y = y[:, np.newaxis]
# Deal with sample_weight
if sample_weight is None:
sample_weight = np.ones((y.shape[0], 1), dtype=y.dtype)
else:
sample_weight = np.asarray(sample_weight, dtype=np.float64)
assert_all_finite(sample_weight)
if len(sample_weight.shape) == 1:
sample_weight = sample_weight[:, np.newaxis]
# Deal with output_weight
if output_weight is not None:
output_weight = np.asarray(output_weight, dtype=np.float64)
assert_all_finite(output_weight)
# Make sure dimensions match
if y.shape[0] != X.shape[0]:
raise ValueError('X and y do not have compatible dimensions.')
if y.shape[0] != sample_weight.shape[0]:
raise ValueError(
'y and sample_weight do not have compatible dimensions.')
if output_weight is not None and y.shape[1] != output_weight.shape[0]:
raise ValueError(
'y and output_weight do not have compatible dimensions.')
if y.shape[1] > 1:
if sample_weight.shape[1] == 1 and output_weight is not None:
sample_weight = np.repeat(sample_weight, y.shape[1], axis=1)
if output_weight is not None:
sample_weight *= output_weight
# Make sure everything is finite (except X, which is allowed to have
# missing values)
assert_all_finite(missing)
assert_all_finite(y)
assert_all_finite(sample_weight)
assert_all_finite(output_weight)
# Make sure everything is consistent
check_X_y(X, y, accept_sparse=False, multi_output=True,
force_all_finite=False)
return X, y, sample_weight, None, missing
def fit(self, X, y=None,
sample_weight=None,
output_weight=None,
missing=None,
xlabels=None, linvars=[]):
'''
Fit an Earth model to the input data X and y.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features the training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as
output by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples The training response, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples.
Sample weights for training. Weights must be greater than or
equal to zero. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity.
In such cases, the weight should be proportional to the inverse of
the (known) variance.
output_weight : array-like, optional (default=None), shape = [p]
where p is the number of outputs.
Output weights for training. Weights must be greater than or equal
to zero. Output with zero weight do not contribute at all.
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
linvars : iterable of strings or ints, optional (empty by default)
Used to specify features that may only enter terms as linear basis
functions (without knots). Can include both column numbers and
column names (see xlabels, below). If left empty, some variables
may still enter linearly during the forward pass if no knot would
provide a reduction in GCV compared to the linear function.
Note that this feature differs from the R package earth.
xlabels : iterable of strings, optional (empty by default)
The xlabels argument can be used to assign names to data columns.
This argument is not generally needed, as names can be captured
automatically from most standard data structures.
If included, must have length n, where n is the number of features.
Note that column order is used to compute term values and make
predictions, not column names.
'''
# Format and label the data
if xlabels is None:
self.xlabels_ = self._scrape_labels(X)
else:
if len(xlabels) != X.shape[1]:
raise ValueError('The length of xlabels is not the '
'same as the number of columns of X')
self.xlabels_ = xlabels
if self.feature_importance_type is not None:
feature_importance_type = self.feature_importance_type
try:
is_str = isinstance(feature_importance_type, basestring)
except NameError:
is_str = isinstance(feature_importance_type, str)
if is_str:
feature_importance_type = [feature_importance_type]
for k in feature_importance_type:
if k not in FEAT_IMP_CRITERIA:
msg = ("'{}' is not valid value for feature_importance, "
"allowed critera are : {}".format(k, FEAT_IMP_CRITERIA))
raise ValueError(msg)
if len(feature_importance_type) > 0 and self.enable_pruning is False:
raise ValueError("Cannot compute feature importances because pruning is disabled,"
"please re-enable pruning by setting enable_pruning to True in order"
"to enable feature importance estimation")
self.linvars_ = linvars
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, sample_weight, output_weight, missing)
# Do the actual work
self.forward_pass(X, y,
sample_weight, output_weight, missing,
self.xlabels_, linvars, skip_scrub=True)
if self.enable_pruning is True:
self.pruning_pass(X, y,
sample_weight, output_weight, missing,
skip_scrub=True)
if hasattr(self, 'smooth') and self.smooth:
self.basis_ = self.basis_.smooth(X)
self.linear_fit(X, y, sample_weight, output_weight, missing,
skip_scrub=True)
return self
# def forward_pass2(self, X, y=None,
# sample_weight=None, output_weight=None,
# missing=None,
# xlabels=None, linvars=[]):
# # Label and format data
# if xlabels is None:
# self.xlabels_ = self._scrape_labels(X)
# else:
# self.xlabels_ = xlabels
# X, y, sample_weight, output_weight, missing = self._scrub(
# X, y, sample_weight, output_weight, missing)
#
# # Do the actual work
# args = self._pull_forward_args(**self.__dict__)
# forward_passer = ForwardPasser(
# X, missing, y, sample_weight, output_weight,
# xlabels=self.xlabels_, linvars=linvars, **args)
# # forward_passer.run()
# linvars_ = []
# self.forward_pass_record_, self.basis_ = forward_pass(X, missing, y,
# sample_weight, output_weight, xlabels=self.xlabels_, linvars=linvars)
# # self.basis_ = forward_passer.get_basis()
#
def forward_pass(self, X, y=None,
sample_weight=None, output_weight=None,
missing=None,
xlabels=None, linvars=[], skip_scrub=False):
'''
Perform the forward pass of the multivariate adaptive regression
splines algorithm. Users will normally want to call the fit method
instead, which performs the forward pass, the pruning pass,
and a linear fit to determine the final model coefficients.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples.
Sample weights for training. Weights must be greater than or
equal to zero. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
output_weight : array-like, optional (default=None), shape = [p]
where p is the number of outputs.
The total mean squared error (MSE) is a weighted sum of
mean squared errors (MSE) associated to each output, where
the weights are given by output_weight.
Output weights must be greater than or equal
to zero. Outputs with zero weight do not contribute at all
to the total mean squared error (MSE).
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
linvars : iterable of strings or ints, optional (empty by default)
Used to specify features that may only enter terms as linear basis
functions (without knots). Can include both column numbers and
column names (see xlabels, below).
xlabels : iterable of strings, optional (empty by default)
The xlabels argument can be used to assign names to data columns.
This argument is not generally needed, as names can be captured
automatically from most standard data structures.
If included, must have length n, where n is the number of features.
Note that column order is used to compute term values and make
predictions, not column names.
'''
# Label and format data
if xlabels is None:
self.xlabels_ = self._scrape_labels(X)
else:
self.xlabels_ = xlabels
if not skip_scrub:
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, sample_weight, output_weight, missing)
# Do the actual work
args = self._pull_forward_args(**self.__dict__)
forward_passer = ForwardPasser(
X, missing, y, sample_weight,
xlabels=self.xlabels_, linvars=linvars, **args)
forward_passer.run()
self.forward_pass_record_ = forward_passer.trace()
self.basis_ = forward_passer.get_basis()
def pruning_pass(self, X, y=None, sample_weight=None, output_weight=None,
missing=None, skip_scrub=False):
'''
Perform the pruning pass of the multivariate adaptive regression
splines algorithm. Users will normally want to call the fit
method instead, which performs the forward pass, the pruning
pass, and a linear fit to determine the final model coefficients.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples.
Sample weights for training. Weights must be greater than or
equal to zero. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
output_weight : array-like, optional (default=None), shape = [p]
where p is the number of outputs.
The total mean squared error (MSE) is a weighted sum of
mean squared errors (MSE) associated to each output, where
the weights are given by output_weight.
Output weights must be greater than or equal
to zero. Outputs with zero weight do not contribute at all
to the total mean squared error (MSE).
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
'''
# Format data
if not skip_scrub:
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, sample_weight, output_weight, missing)
# if sample_weight.shape[1] == 1 and y.shape[1] != 1:
# sample_weight = np.repeat(sample_weight,y.shape[1],axis=1)
# Pull arguments from self
args = self._pull_pruning_args(**self.__dict__)
# Do the actual work
pruning_passer = PruningPasser(
self.basis_, X, missing, y, sample_weight,
**args)
pruning_passer.run()
imp = pruning_passer.feature_importance
self._feature_importances_dict = imp
if len(imp) == 1: # if only one criterion then return it only
imp = imp[list(imp.keys())[0]]
elif len(imp) == 0:
imp = None
self.feature_importances_ = imp
self.pruning_pass_record_ = pruning_passer.trace()
# # Format data
# X, y, sample_weight, output_weight, missing = self._scrub(
# X, y, sample_weight, output_weight, missing)
#
# # Dimensions
# m, n = X.shape
# basis_size = len(self.basis_)
# pruned_basis_size = self.basis_.plen()
#
# self.pruning_pass_record_ = PruningPassRecord(m, n, args['penalty'], sst, pruned_basis_size)
#
#
#
# # Pull arguments from self
# args = self._pull_pruning_args(**self.__dict__)
# penalty = args.get('penalty', 3.0)
#
# # Compute prune sets
# prune_sets = [[basis_size - i for i in range(n)] for n in range(basis_size)]
#
# # Create the record object
# record = PruningPassRecord('gcv', basis_size)
#
# # Score each prune set to find the best
# best_prune_set = []
# best_score = float('inf')
# for prune_set in prune_sets:
# print 1
# print prune_set
# sys.stdout.flush()
# # Prune this prune set
# for idx in prune_set:
# self.basis_[idx].prune()
#
# print 2
# sys.stdout.flush()
# # Score this prune set
# self.linear_fit(X, y, sample_weight, output_weight, missing, skip_scrub=True)
# y_pred = self.predict(X, missing, skip_scrub=True)
# score = gcv(np.mean(((y - y_pred) * np.sqrt(sample_weight)) ** 2),
# basis_size - len(prune_set), m, penalty)
# r2 = self.score(X, y, sample_weight, output_weight, missing, skip_scrub=True)
#
# print 3
# sys.stdout.flush()
# # Minimizer
# if score < best_score:
# best_score = score
# best_prune_set = prune_set
#
# print 4
# sys.stdout.flush()
# # Unprune for next iteration
# for idx in prune_set:
# self.basis_[idx].unprune()
#
# print 5
# sys.stdout.flush()
# # Add to the record
# record.add(prune_set, score, r2)
#
# # Apply the best prune set
# for idx in best_prune_set:
# self.basis_[idx].prune()
#
# self.pruning_pass_record_ = record
def forward_trace(self):
'''Return information about the forward pass.'''
try:
return self.forward_pass_record_
except AttributeError:
return None
def pruning_trace(self):
'''Return information about the pruning pass.'''
try:
return self.pruning_pass_record_
except AttributeError:
return None
def trace(self):
'''Return information about the forward and pruning passes.'''
return EarthTrace(self.forward_trace(), self.pruning_trace())
def summary(self):
'''Return a string describing the model.'''
result = ''
if self.forward_trace() is None:
result += 'Untrained Earth Model'
return result
elif self.pruning_trace() is None:
result += 'Unpruned Earth Model\n'
else:
result += 'Earth Model\n'
header = ['Basis Function', 'Pruned']
if self.coef_.shape[0] > 1:
header += ['Coefficient %d' %
i for i in range(self.coef_.shape[0])]
else:
header += ['Coefficient']
data = []
i = 0
for bf in self.basis_:
data.append([str(bf), 'Yes' if bf.is_pruned() else 'No'] + [
'%g' % self.coef_[c, i] if not bf.is_pruned() else
'None' for c in range(self.coef_.shape[0])])
if not bf.is_pruned():
i += 1
result += ascii_table(header, data)
result += '\n'
result += 'MSE: %.4f, GCV: %.4f, RSQ: %.4f, GRSQ: %.4f' % (
self.mse_, self.gcv_, self.rsq_, self.grsq_)
return result
def summary_feature_importances(self, sort_by=None):
"""
Returns a string containing a printable summary of the estimated
feature importances.
Parameters
----------
sory_by : string, optional
it refers to a feature importance type name : 'gcv', 'rss'
or 'nb_subsets'.
In case it is provided, the features are sorted
according to the feature importance type corresponding
to `sort_by`. In case it is not provided, the features are
not sorted.
"""
result = ''
if self._feature_importances_dict:
max_label_length = max(map(len, self.xlabels_)) + 5
result += (max_label_length * ' ' +
' '.join(self._feature_importances_dict.keys()) + '\n')
labels = np.array(self.xlabels_)
if sort_by:
if sort_by not in self._feature_importances_dict.keys():
raise ValueError('Invalid feature importance type name '
'to sort with : %s, available : %s' % (
sort_by,
self._feature_importances_dict.keys()))
imp = self._feature_importances_dict[sort_by]
indices = np.argsort(imp)[::-1]
else:
indices = np.arange(len(labels))
labels = labels[indices]
for i, label in enumerate(labels):
result += label + ' ' * (max_label_length - len(label))
for crit_name, imp in self._feature_importances_dict.items():
imp = imp[indices]
result += '%.2f' % imp[i] + (len(crit_name) ) * ' '
result += '\n'
return result
def linear_fit(self, X, y=None, sample_weight=None, output_weight=None,
missing=None, skip_scrub=False):
'''
Solve the linear least squares problem to determine the coefficients
of the unpruned basis functions.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features The training predictors. The X parameter
can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples.
Sample weights for training. Weights must be greater than or
equal to zero. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
output_weight : array-like, optional (default=None), shape = [p]
where p is the number of outputs.
The total mean squared error (MSE) is a weighted sum of
mean squared errors (MSE) associated to each output, where
the weights are given by output_weight.
Output weights must be greater than or equal
to zero. Outputs with zero weight do not contribute at all
to the total mean squared error (MSE).
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
'''
# Format data
if not skip_scrub:
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, sample_weight, output_weight, missing)
# if sample_weight.shape[1]:
# sample_weight = np.repeat(sample_weight,y.shape[1],axis=1)
# Solve the linear least squares problem
self.coef_ = []
resid_ = []
total_weight = 0.
mse0 = 0.
for i in range(y.shape[1]):
# Figure out the weight column
if sample_weight.shape[1] > 1:
w = sample_weight[:, i]
else:
w = sample_weight[:, 0]
# Transform into basis space
B = self.transform(X, missing) # * w[:, None]
apply_weights_2d(B, w)
# Compute total weight
total_weight += np.sum(w)
# Apply weights to y
weighted_y = y.copy()
weighted_y *= np.sqrt(w[:, np.newaxis])
# Compute the mse0
mse0 += np.sum((weighted_y[:, i] -
np.average(weighted_y[:, i])) ** 2)
coef, resid = np.linalg.lstsq(B, weighted_y[:, i])[0:2]
self.coef_.append(coef)
if not resid:
resid = np.array(
[np.sum((np.dot(B, coef) - weighted_y[:, i]) ** 2)])
resid_.append(resid)
resid_ = np.array(resid_)
self.coef_ = np.array(self.coef_)
# Compute the final mse, gcv, rsq, and grsq (may be different from the
# pruning scores if the model has been smoothed)
self.mse_ = np.sum(resid_) / total_weight
mse0 = mse0 / total_weight
self.gcv_ = gcv(self.mse_,
coef.shape[0], X.shape[0],
self.get_penalty())
gcv0 = gcv(mse0,
1, X.shape[0],
self.get_penalty())
if mse0 != 0.:
self.rsq_ = 1.0 - (self.mse_ / mse0)
else:
self.rsq_ = 1.0
if gcv0 != 0.:
self.grsq_ = 1.0 - (self.gcv_ / gcv0)
else:
self.grsq_ = 1.0
#
#
#
# for p, coef in enumerate(self.coef_):
# mse_p = resid_[p].sum() / float(X.shape[0])
# gcv_[p] = gcv(mse_p,
# coef.shape[0], X.shape[0],
# self.get_penalty())
# self.gcv_ += gcv_[p] * output_weight[p]
# y_avg = np.average(y, weights=sample_weight if
# sample_weight.shape == y.shape else sample_weight.flatten(), axis=0)
# y_sqr = (y - y_avg[np.newaxis, :]) ** 2
#
# rsq_ = ((1 - resid_.sum(axis=1) / y_sqr.sum(axis=0)) * output_weight)
# self.rsq_ = rsq_.sum()
# gcv0 = np.empty(y.shape[1])
# for p in range(y.shape[1]):
# mse0_p = (y_sqr[:, p].sum()) / float(X.shape[0])
# gcv0[p] = gcv(mse0_p, 1, X.shape[0], self.get_penalty())
# self.grsq_ = ((1 - (gcv_ / gcv0)) * output_weight).sum()
def predict(self, X, missing=None, skip_scrub=False):
'''
Predict the response based on the input data X.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features
The training predictors. The X parameter can be a numpy
array, a pandas DataFrame, or a patsy DesignMatrix.
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
Returns
-------
y : array of shape = [m] or [m, p] where m is the number of samples
and p is the number of outputs
The predicted values.
'''
if not skip_scrub:
X, missing = self._scrub_x(X, missing)
B = self.transform(X, missing)
y = np.dot(B, self.coef_.T)
if y.shape[1] == 1:
return y[:, 0]
else:
return y
def predict_deriv(self, X, variables=None, missing=None):
'''
Predict the first derivatives of the response based on the input
data X.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features The training predictors. The X parameter
can be a numpy array, a pandas DataFrame, or a patsy DesignMatrix.
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
variables : list
The variables over which derivatives will be computed. Each column
in the resulting array corresponds to a variable. If not
specified, all variables are used (even if some are not relevant
to the final model and have derivatives that are identically zero).
Returns
-------
X_deriv : array of shape = [m, n, p] where m is the number of samples, n
is the number of features if 'variables' is not specified
otherwise it is len(variables) and p is the number of outputs.
For each sample, X_deriv represents the first derivative of
each response with respect to each variable.
'''
check_is_fitted(self, "basis_")
if type(variables) in (str, int):
variables = [variables]
if variables is None:
variables_of_interest = list(range(len(self.xlabels_)))
else:
variables_of_interest = []
for var in variables:
if isinstance(var, int):
variables_of_interest.append(var)
else:
variables_of_interest.append(self.xlabels_.index(var))
X, missing = self._scrub_x(X, missing)
J = np.zeros(shape=(X.shape[0],
len(variables_of_interest),
self.coef_.shape[0]))
b = np.empty(shape=X.shape[0])
j = np.empty(shape=X.shape[0])
self.basis_.transform_deriv(
X, missing, b, j, self.coef_, J, variables_of_interest, True)
return J
def score(self, X, y=None, sample_weight=None, output_weight=None,
missing=None, skip_scrub=False):
'''
Calculate the generalized r^2 of the model on data X and y.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples.
Sample weights for training. Weights must be greater than or
equal to zero. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
output_weight : array-like, optional (default=None), shape = [p]
where p is the number of outputs.
The total mean squared error (MSE) is a weighted sum of
mean squared errors (MSE) associated to each output, where
the weights are given by output_weight.
Output weights must be greater than or equal
to zero. Outputs with zero weight do not contribute at all
to the total mean squared error (MSE).
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
Returns
-------
score : float with a maximum value of 1 (it can be negative). The score
is the generalized r^2 of the model on data X and y, the higher
the score the better the fit is.
'''
check_is_fitted(self, "basis_")
if not skip_scrub:
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, sample_weight, output_weight, missing)
if sample_weight.shape[1] == 1 and y.shape[1] > 1:
sample_weight = np.repeat(sample_weight, y.shape[1], axis=1)
y_hat = self.predict(X)
if len(y_hat.shape) == 1:
y_hat = y_hat[:, None]
residual = y - y_hat
# total_weight = np.sum(sample_weight)
mse = np.sum(sample_weight * (residual ** 2))
y_avg = np.average(y, weights=sample_weight, axis=0)
mse0 = np.sum(sample_weight * ((y - y_avg) ** 2))
# mse0 = np.sum(y_sqr * output_weight) / m
return 1 - (mse / mse0)
def score_samples(self, X, y=None, missing=None):
'''
Calculate sample-wise fit scores.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m, p] where m is the
number of samples, p the number of outputs.
The y parameter can be a numpy array, a pandas DataFrame,
a Patsy DesignMatrix, or can be left as None (default) if X was
the output of a call to patsy.dmatrices (in which case, X contains
the response).
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
Returns
-------
scores : array of shape=[m, p] of floats with maximum value of 1
(it can be negative).
The scores represent how good each output of each example is
predicted, a perfect score would be 1
(the score can be negative).
'''
X, y, sample_weight, output_weight, missing = self._scrub(
X, y, None, None, missing)
y_hat = self.predict(X, missing=missing)
residual = 1 - (y - y_hat) ** 2 / y**2
return residual
def transform(self, X, missing=None):
'''
Transform X into the basis space. Normally, users will call the
predict method instead, which both transforms into basis space
calculates the weighted sum of basis terms to produce a prediction
of the response. Users may wish to call transform directly in some
cases. For example, users may wish to apply other statistical or
machine learning algorithms, such as generalized linear regression,
in basis space.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features
The training predictors. The X parameter can be a numpy array, a
pandas DataFrame, or a patsy DesignMatrix.
missing : array-like, shape = [m, n] where m is the number of samples
and n is the number of features.
The missing parameter can be a numpy array, a pandas DataFrame, or
a patsy DesignMatrix. All entries will be interpreted as boolean
values, with True indicating the corresponding entry in X should be
interpreted as missing. If the missing argument not used but the X
argument is a pandas DataFrame, missing will be inferred from X if
allow_missing is True.
Returns
-------
B: array of shape [m, nb_terms] where m is the number of samples and
nb_terms is the number of terms (or basis functions) obtained after
fitting (which is the number of elements of the attribute `basis_`).
B represents the values of the basis functions evaluated at each
sample.
'''
check_is_fitted(self, "basis_")
X, missing = self._scrub_x(X, missing)
B = np.empty(shape=(X.shape[0], self.basis_.plen()), order='F')
self.basis_.transform(X, missing, B)
return B
def get_penalty(self):
'''Get the penalty parameter being used. Default is 3.'''
if 'penalty' in self.__dict__ and self.penalty is not None:
return self.penalty
else:
return 3.0
class EarthTrace(object):
def __init__(self, forward_trace, pruning_trace):
self.forward_trace = forward_trace
self.pruning_trace = pruning_trace
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.forward_trace == other.forward_trace and
self.pruning_trace == other.pruning_trace)
def __str__(self):
result = ''
result += 'Forward Pass\n'
result += str(self.forward_trace)
result += '\n'
result += self.forward_trace.final_str()
result += '\n\n'
result += 'Pruning Pass\n'
result += str(self.pruning_trace)
result += '\n'
result += self.pruning_trace.final_str()
result += '\n'
return result
| {
"repo_name": "jcrudy/py-earth",
"path": "pyearth/earth.py",
"copies": "2",
"size": "59949",
"license": "bsd-3-clause",
"hash": 1921309059726507300,
"line_mean": 42.0050215208,
"line_max": 102,
"alpha_frac": 0.5904185224,
"autogenerated": false,
"ratio": 4.267744002278066,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5858162524678067,
"avg_score": null,
"num_lines": null
} |
from ._forward import ForwardPasser
from ._pruning import PruningPasser
from ._util import ascii_table, apply_weights_2d, apply_weights_1d, gcv
from sklearn.base import RegressorMixin, BaseEstimator, TransformerMixin
from sklearn.utils.validation import (assert_all_finite, check_is_fitted,
check_X_y)
import numpy as np
from scipy import sparse
class Earth(BaseEstimator, RegressorMixin, TransformerMixin):
"""
Multivariate Adaptive Regression Splines
A flexible regression method that automatically searches for interactions
and non-linear relationships. Earth models can be thought of as
linear models in a higher dimensional basis space
(specifically, a multivariate truncated power spline basis).
Each term in an Earth model is a product of so called "hinge functions".
A hinge function is a function that's equal to its argument where that
argument is greater than zero and is zero everywhere else.
The multivariate adaptive regression splines algorithm has two stages.
First, the forward pass searches for terms in the truncated power spline
basis that locally minimize the squared error loss of the training set.
Next, a pruning pass selects a subset of those terms that produces
a locally minimal generalized cross-validation (GCV) score. The GCV score
is not actually based on cross-validation, but rather is meant to
approximate a true cross-validation score by penalizing model complexity.
The final result is a set of terms that is nonlinear in the original
feature space, may include interactions, and is likely to generalize well.
The Earth class supports dense input only. Data structures from the
pandas and patsy modules are supported, but are copied into numpy arrays
for computation. No copy is made if the inputs are numpy float64 arrays.
Earth objects can be serialized using the pickle module and copied
using the copy module.
Parameters
----------
max_terms : int, optional (default=2*n + 10, where n is the
number of features)
The maximum number of terms generated by the forward pass.
max_degree : int, optional (default=1)
The maximum degree of terms generated by the forward pass.
penalty : float, optional (default=3.0)
A smoothing parameter used to calculate GCV and GRSQ.
Used during the pruning pass and to determine whether to add a hinge
or linear basis function during the forward pass.
See the d parameter in equation 32, Friedman, 1991.
endspan_alpha : float, optional, probability between 0 and 1 (default=0.05)
A parameter controlling the calculation of the endspan
parameter (below). The endspan parameter is calculated as
round(3 - log2(endspan_alpha/n)), where n is the number of features.
The endspan_alpha parameter represents the probability of a run of
positive or negative error values on either end of the data vector
of any feature in the data set. See equation 45, Friedman, 1991.
endspan : int, optional (default=-1)
The number of extreme data values of each feature not eligible
as knot locations. If endspan is set to -1 (default) then the
endspan parameter is calculated based on endspan_alpah (above).
If endspan is set to a positive integer then endspan_alpha is ignored.
minspan_alpha : float, optional, probability between 0 and 1 (default=0.05)
A parameter controlling the calculation of the minspan
parameter (below). The minspan parameter is calculated as
(int) -log2(-(1.0/(n*count))*log(1.0-minspan_alpha)) / 2.5
where n is the number of features and count is the number of points at
which the parent term is non-zero. The minspan_alpha parameter
represents the probability of a run of positive or negative error values
between adjacent knots separated by minspan intervening data points.
See equation 43, Friedman, 1991.
minspan : int, optional (default=-1)
The minimal number of data points between knots. If minspan is set
to -1 (default) then the minspan parameter is calculated based on
minspan_alpha (above). If minspan is set to a positive integer then
minspan_alpha is ignored.
thresh : float, optional (defaul=0.001)
Parameter used when evaluating stopping conditions for the forward
pass. If either RSQ > 1 - thresh or if RSQ increases by less than
thresh for a forward pass iteration then the forward pass is terminated.
min_search_points : int, optional (default=100)
Used to calculate check_every (below). The minimum samples necessary
for check_every to be greater than 1. The check_every parameter
is calculated as
(int) m / min_search_points
if m > min_search_points, where m is the number of samples in the
training set. If m <= min_search_points then check_every is set to 1.
check_every : int, optional (default=-1)
If check_every > 0, only one of every check_every sorted data points
is considered as a candidate knot. If check_every is set to -1 then
the check_every parameter is calculated based on
min_search_points (above).
allow_linear : bool, optional (default=True)
If True, the forward pass will check the GCV of each new pair of terms
and, if it's not an improvement on a single term with no knot
(called a linear term, although it may actually be a product of a linear
term with some other parent term), then only that single, knotless term
will be used. If False, that behavior is disabled and all terms
will have knots except those with variables specified by the linvars
argument (see the fit method).
smooth : bool, optional (default=False)
If True, the model will be smoothed such that it has continuous first
derivatives.
For details, see section 3.7, Friedman, 1991.
enable_pruning : bool, optional(default=True)
If False, the pruning pass will be skipped.
Attributes
----------
`coef_` : array, shape = [pruned basis length]
The weights of the model terms that have not been pruned.
`basis_` : _basis.Basis
An object representing model terms. Each term is a product of
constant, linear, and hinge functions of the input features.
`mse_` : float
The mean squared error of the model after the final linear fit.
If sample_weight is given, this score is weighted appropriately.
`rsq_` : float
The generalized r^2 of the model after the final linear fit.
If sample_weight is given, this score is weighted appropriately.
`gcv_` : float
The generalized cross validation (GCV) score of the model after the
final linear fit. If sample_weight is given, this score is
weighted appropriately.
`grsq_` : float
An r^2 like score based on the GCV. If sample_weight is given, this
score is weighted appropriately.
`forward_pass_record_` : _record.ForwardPassRecord
An object containing information about the forward pass, such as
training loss function values after each iteration and the final
stopping condition.
`pruning_pass_record_` : _record.PruningPassRecord
An object containing information about the pruning pass, such as
training loss function values after each iteration and the
selected optimal iteration.
`xlabels_` : list
List of column names for training predictors.
Defaults to ['x0','x1',....] if column names are not provided.
References
----------
.. [1] Friedman, Jerome. Multivariate Adaptive Regression Splines.
Annals of Statistics. Volume 19, Number 1 (1991), 1-67.
"""
forward_pass_arg_names = set([
'max_terms', 'max_degree', 'penalty',
'endspan_alpha', 'endspan',
'minspan_alpha', 'minspan',
'thresh', 'min_search_points', 'check_every',
'allow_linear'
])
pruning_pass_arg_names = set([
'penalty'
])
def __init__(self, max_terms=None, max_degree=None, penalty=None,
endspan_alpha=None, endspan=None,
minspan_alpha=None, minspan=None,
thresh=None, min_search_points=None, check_every=None,
allow_linear=None, smooth=None, enable_pruning=True):
kwargs = {}
call = locals()
for name in self._get_param_names():
if call[name] is not None:
kwargs[name] = call[name]
self.set_params(**kwargs)
def __eq__(self, other):
if self.__class__ is not other.__class__:
return False
keys = set(self.__dict__.keys()) | set(other.__dict__.keys())
for k in keys:
try:
v_self = self.__dict__[k]
v_other = other.__dict__[k]
except KeyError:
return False
try:
if v_self != v_other:
return False
except ValueError: # Case of numpy arrays
if np.any(v_self != v_other):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def _pull_forward_args(self, **kwargs):
'''
Pull named arguments relevant to the forward pass.
'''
result = {}
for name in self.forward_pass_arg_names:
if name in kwargs:
result[name] = kwargs[name]
return result
def _pull_pruning_args(self, **kwargs):
'''
Pull named arguments relevant to the pruning pass.
'''
result = {}
for name in self.pruning_pass_arg_names:
if name in kwargs:
result[name] = kwargs[name]
return result
def _scrape_labels(self, X):
'''
Try to get labels from input data (for example, if X is a
pandas DataFrame). Return None if no labels can be extracted.
'''
try:
labels = list(X.columns)
except AttributeError:
try:
labels = list(X.design_info.column_names)
except AttributeError:
try:
labels = list(X.dtype.names)
except TypeError:
try:
labels = ['x%d' % i for i in range(X.shape[1])]
except IndexError:
labels = ['x%d' % i for i in range(1)]
return labels
def _scrub_x(self, X, **kwargs):
'''
Sanitize input predictors and extract column names if appropriate.
'''
# Check for sparseness
if sparse.issparse(X):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use X.toarray() to convert to dense.')
# Convert to internally used data type
X = np.asarray(X, dtype=np.float64, order='F')
assert_all_finite(X)
if X.ndim == 1:
X = X[:, np.newaxis]
# Ensure correct number of columns
if hasattr(self, 'basis_') and self.basis_ is not None:
if X.shape[1] != self.basis_.num_variables:
raise ValueError('Wrong number of columns in X')
return X
def _scrub(self, X, y, sample_weight, **kwargs):
'''
Sanitize input data.
'''
# Check for sparseness
if sparse.issparse(y):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use y.toarray() to convert to dense.')
if sparse.issparse(sample_weight):
raise TypeError('A sparse matrix was passed, but dense data '
'is required. Use sample_weight.toarray()'
'to convert to dense.')
# Check whether X is the output of patsy.dmatrices
if y is None and isinstance(X, tuple):
y, X = X
# Handle X separately
X = self._scrub_x(X, **kwargs)
# Convert y to internally used data type
y = np.asarray(y, dtype=np.float64)
assert_all_finite(y)
y = y.reshape(y.shape[0])
# Deal with sample_weight
if sample_weight is None:
sample_weight = np.ones(y.shape[0], dtype=y.dtype)
else:
sample_weight = np.asarray(sample_weight)
assert_all_finite(sample_weight)
sample_weight = sample_weight.reshape(sample_weight.shape[0])
# Make sure dimensions match
if y.shape[0] != X.shape[0]:
raise ValueError('X and y do not have compatible dimensions.')
if y.shape != sample_weight.shape:
raise ValueError(
'y and sample_weight do not have compatible dimensions.')
# Make sure everything is finite
assert_all_finite(X)
assert_all_finite(y)
assert_all_finite(sample_weight)
return X, y, sample_weight
def fit(self, X, y=None, sample_weight=None, xlabels=None, linvars=[]):
'''
Fit an Earth model to the input data X and y.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as
output by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the
number of samples The training response. The y parameter can be
a numpy array, a pandas DataFrame with one column, a Patsy
DesignMatrix, or can be left as None (default) if X was the output
of a call to patsy.dmatrices (in which case, X contains the
response).
sample_weight : array-like, optional (default=None), shape = [m] where
m is the number of samples
Sample weights for training. Weights must be greater than or equal
to zero. Rows with greater weights contribute more strongly to the
fitted model. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
linvars : iterable of strings or ints, optional (empty by default)
Used to specify features that may only enter terms as linear basis
functions (without knots). Can include both column numbers and
column names (see xlabels, below). If left empty, some variables
may still enter linearly during the forward pass if no knot would
provide a reduction in GCV compared to the linear function.
Note that this feature differs from the R package earth.
xlabels : iterable of strings, optional (empty by default)
The xlabels argument can be used to assign names to data columns.
This argument is not generally needed, as names can be captured
automatically from most standard data structures.
If included, must have length n, where n is the number of features.
Note that column order is used to compute term values and make
predictions, not column names.
'''
check_X_y(X, y, accept_sparse=None, multi_output=True)
# Format and label the data
if xlabels is None:
self.xlabels_ = self._scrape_labels(X)
else:
if len(xlabels) != X.shape[1]:
raise ValueError('The length of xlabels is not the '
'same as the number of columns of X')
self.xlabels_ = xlabels
self.linvars_ = linvars
X, y, sample_weight = self._scrub(X, y, sample_weight)
# Do the actual work
self.__forward_pass(X, y, sample_weight, self.xlabels_, linvars)
if self.enable_pruning is True:
self.__pruning_pass(X, y, sample_weight)
if hasattr(self, 'smooth') and self.smooth:
self.basis_ = self.basis_.smooth(X)
self.__linear_fit(X, y, sample_weight)
return self
def __forward_pass(
self, X, y=None, sample_weight=None, xlabels=None, linvars=[]):
'''
Perform the forward pass of the multivariate adaptive regression
splines algorithm. Users will normally want to call the fit method
instead, which performs the forward pass, the pruning pass,
and a linear fit to determine the final model coefficients.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n is
the number of features The training predictors. The X parameter can
be a numpy array, a pandas DataFrame, a patsy DesignMatrix, or a
tuple of patsy DesignMatrix objects as output by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the
number of samples The training response. The y parameter can be
a numpy array, a pandas DataFrame with one column, a Patsy
DesignMatrix, or can be left as None (default) if X was the output
of a call to patsy.dmatrices (in which case, X contains the
response).
sample_weight : array-like, optional (default=None), shape = [m] where m
is the number of samples
Sample weights for training. Weights must be greater than or
equal to zero. Rows with greater weights contribute more strongly
to the fitted model. Rows with zero weight do not contribute at
all. Weights are useful when dealing with heteroscedasticity.
In such cases, the weight should be proportional to the inverse
of the (known) variance.
linvars : iterable of strings or ints, optional (empty by default)
Used to specify features that may only enter terms as linear basis
functions (without knots). Can include both column numbers an
column names (see xlabels, below).
xlabels : iterable of strings, optional (empty by default)
The xlabels argument can be used to assign names to data columns.
This argument is not generally needed, as names can be captured
automatically from most standard data structures. If included, must
have length n, where n is the number of features. Note that column
order is used to compute term values and make predictions, not
column names.
'''
# Label and format data
if xlabels is None:
self.xlabels_ = self._scrape_labels(X)
else:
self.xlabels_ = xlabels
X, y, sample_weight = self._scrub(X, y, sample_weight)
# Do the actual work
args = self._pull_forward_args(**self.__dict__)
forward_passer = ForwardPasser(
X, y, sample_weight, xlabels=self.xlabels_, linvars=linvars, **args)
forward_passer.run()
self.forward_pass_record_ = forward_passer.trace()
self.basis_ = forward_passer.get_basis()
def __pruning_pass(self, X, y=None, sample_weight=None):
'''
Perform the pruning pass of the multivariate adaptive regression
splines algorithm. Users will normally want to call the fit
method instead, which performs the forward pass, the pruning
pass, and a linear fit to determine the final model coefficients.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the
number of samples The training response. The y parameter can be
a numpy array, a pandas DataFrame with one column, a Patsy
DesignMatrix, or can be left as None (default) if X was the output
of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m]
where m is the number of samples
Sample weights for training. Weights must be greater than or
equal to zero. Rows with greater weights contribute more strongly
to the fitted model. Rows with zero weight do not contribute at
all. Weights are useful when dealing with heteroscedasticity.
In such cases, the weight should be proportional to the inverse
of the (known) variance.
'''
# Format data
X, y, sample_weight = self._scrub(X, y, sample_weight)
# Pull arguments from self
args = self._pull_pruning_args(**self.__dict__)
# Do the actual work
pruning_passer = PruningPasser(
self.basis_, X, y, sample_weight, **args)
pruning_passer.run()
self.pruning_pass_record_ = pruning_passer.trace()
def forward_trace(self):
'''Return information about the forward pass.'''
try:
return self.forward_pass_record_
except AttributeError:
return None
def pruning_trace(self):
'''Return information about the pruning pass.'''
try:
return self.pruning_pass_record_
except AttributeError:
return None
def trace(self):
'''Return information about the forward and pruning passes.'''
return EarthTrace(self.forward_trace(), self.pruning_trace())
def summary(self):
'''Return a string describing the model.'''
result = ''
if self.forward_trace() is None:
result += 'Untrained Earth Model'
return result
elif self.pruning_trace() is None:
result += 'Unpruned Earth Model\n'
else:
result += 'Earth Model\n'
header = ['Basis Function', 'Pruned', 'Coefficient']
data = []
i = 0
for bf in self.basis_:
data.append([str(bf), 'Yes' if bf.is_pruned() else 'No', '%g' %
self.coef_[i] if not bf.is_pruned() else 'None'])
if not bf.is_pruned():
i += 1
result += ascii_table(header, data)
if self.pruning_trace() is not None:
record = self.pruning_trace()
selection = record.get_selected()
else:
record = self.forward_trace()
selection = len(record) - 1
result += '\n'
result += 'MSE: %.4f, GCV: %.4f, RSQ: %.4f, GRSQ: %.4f' % (
self.mse_, self.gcv_, self.rsq_, self.grsq_)
return result
def __linear_fit(self, X, y=None, sample_weight=None):
'''
Solve the linear least squares problem to determine the coefficients
of the unpruned basis functions.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features The training predictors. The X parameter
can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the
number of samples The training response. The y parameter can be
a numpy array, a pandas DataFrame with one column, a Patsy
DesignMatrix, or can be left as None (default) if X was the output
of a call to patsy.dmatrices (in which case, X contains the
response).
sample_weight : array-like, optional (default=None), shape = [m] where
m is the number of samples
Sample weights for training. Weights must be greater than or equal
to zero. Rows with greater weights contribute more strongly to
the fitted model. Rows with zero weight do not contribute at all.
Weights are useful when dealing with heteroscedasticity. In such
cases, the weight should be proportional to the inverse of the
(known) variance.
'''
# Format data
X, y, sample_weight = self._scrub(X, y, sample_weight)
# Transform into basis space
B = self.transform(X)
# Apply weights to B
apply_weights_2d(B, sample_weight)
# Apply weights to y
weighted_y = y.copy()
apply_weights_1d(weighted_y, sample_weight)
# Solve the linear least squares problem
self.coef_, resid = np.linalg.lstsq(B, weighted_y)[0:2]
# Compute the final mse, gcv, rsq, and grsq (may be different from the
# pruning scores if the model has been smoothed)
self.mse_ = np.sum(resid) / float(X.shape[0])
self.gcv_ = gcv(
self.mse_, self.coef_.shape[0], X.shape[0], self.get_penalty())
y_avg = np.average(y, weights=sample_weight)
y_sqr = sample_weight * (y - y_avg) ** 2
mse0 = np.sum(y_sqr) / float(X.shape[0])
gcv0 = gcv(mse0, 1, X.shape[0], self.get_penalty())
self.rsq_ = 1.0 - (self.mse_ / mse0)
self.grsq_ = 1.0 - (self.gcv_ / gcv0)
def predict(self, X):
'''
Predict the response based on the input data X.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features
The training predictors. The X parameter can be a numpy
array, a pandas DataFrame, or a patsy DesignMatrix.
'''
X = self._scrub_x(X)
B = self.transform(X)
return np.dot(B, self.coef_)
def predict_deriv(self, X, variables=None):
'''
Predict the first derivatives of the response based on the input data X.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n is
the number of features The training predictors. The X parameter can
be a numpy array, a pandas DataFrame, or a patsy DesignMatrix.
variables : list
The variables over which derivatives will be computed. Each column
in the resulting array corresponds to a variable. If not
specified, all variables are used (even if some are not relevant
to the final model and have derivatives that are identically zero).
'''
check_is_fitted(self, "basis_")
if type(variables) in (str, int):
variables = [variables]
if variables is None:
variables_of_interest = list(range(len(self.xlabels_)))
else:
variables_of_interest = []
for var in variables:
if isinstance(var, int):
variables_of_interest.append(var)
else:
variables_of_interest.append(self.xlabels_.index(var))
X = self._scrub_x(X)
J = np.zeros(shape=(X.shape[0], len(variables_of_interest)))
b = np.empty(shape=X.shape[0])
j = np.empty(shape=X.shape[0])
self.basis_.transform_deriv(
X, b, j, self.coef_, J, variables_of_interest, True)
return J
def score(self, X, y=None, sample_weight=None):
'''
Calculate the generalized r^2 of the model on data X and y.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples
and n is the number of features The training predictors.
The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output
by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the
number of samples The training response. The y parameter can be
a numpy array, a pandas DataFrame with one column, a Patsy
DesignMatrix, or can be left as None (default) if X was the
output of a call to patsy.dmatrices (in which case, X contains
the response).
sample_weight : array-like, optional (default=None), shape = [m] where
m is the number of samples
Sample weights for training. Weights must be greater than or
equal to zero. Rows with greater weights contribute more strongly
to the fitted model. Rows with zero weight do not contribute at
all. Weights are useful when dealing with heteroscedasticity.
In such cases, the weight should be proportional to the inverse of
the (known) variance.
'''
check_is_fitted(self, "basis_")
X, y, sample_weight = self._scrub(X, y, sample_weight)
y_hat = self.predict(X)
m, _ = X.shape
residual = y - y_hat
mse = np.sum(sample_weight * (residual ** 2)) / m
y_avg = np.average(y, weights=sample_weight)
y_sqr = sample_weight * (y - y_avg) ** 2
mse0 = np.sum(y_sqr) / m
return 1 - (mse / mse0)
def transform(self, X):
'''
Transform X into the basis space. Normally, users will call the
predict method instead, which both transforms into basis space
calculates the weighted sum of basis terms to produce a prediction
of the response. Users may wish to call transform directly in some
cases. For example, users may wish to apply other statistical or
machine learning algorithms, such as generalized linear regression,
in basis space.
Parameters
----------
X : array-like, shape = [m, n] where m is the number of samples and n
is the number of features
The training predictors. The X parameter can be a numpy array, a
pandas DataFrame, or a patsy DesignMatrix.
'''
check_is_fitted(self, "basis_")
X = self._scrub_x(X)
B = np.empty(shape=(X.shape[0], self.basis_.plen()), order='F')
self.basis_.transform(X, B)
return B
def get_penalty(self):
'''Get the penalty parameter being used. Default is 3.'''
if 'penalty' in self.__dict__ and self.penalty is not None:
return self.penalty
else:
return 3.0
class EarthTrace(object):
def __init__(self, forward_trace, pruning_trace):
self.forward_trace = forward_trace
self.pruning_trace = pruning_trace
def __eq__(self, other):
return (self.__class__ is other.__class__ and
self.forward_trace == other.forward_trace and
self.pruning_trace == other.pruning_trace)
def __str__(self):
return str(self.forward_trace) + '\n' + str(self.pruning_trace)
| {
"repo_name": "DucQuang1/py-earth",
"path": "pyearth/earth.py",
"copies": "1",
"size": "31698",
"license": "bsd-3-clause",
"hash": 1924551613586762000,
"line_mean": 38.9219143577,
"line_max": 80,
"alpha_frac": 0.6086819358,
"autogenerated": false,
"ratio": 4.2910518478408015,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5399733783640801,
"avg_score": null,
"num_lines": null
} |
from .forwarding_rule import ForwardingRule
class Server(object):
"""Server.
:param id: Unique identifier for the server. Used as username for
SMTP/POP3 authentication.
:type id: str
:param password: SMTP/POP3 password.
:type password: str
:param name: A name used to identify the server.
:type name: str
:param users: Users (excluding administrators) who have access to the
server.
:type users: list[str]
:param messages: The number of messages currently in the server.
:type messages: int
:param forwarding_rules: The rules used to manage email forwarding for
this server.
:type forwarding_rules: list[~mailosaur.models.ForwardingRule]
"""
def __init__(self, data=None):
if data is None:
data = {}
self.id = data.get('id', None)
self.password = data.get('password', None)
self.name = data.get('name', None)
self.users = data.get('users', None)
self.messages = data.get('messages', None)
self.forwarding_rules = [ForwardingRule(i) for i in data.get('forwardingRules', [])]
| {
"repo_name": "mailosaurapp/mailosaur-python",
"path": "mailosaur/models/server.py",
"copies": "1",
"size": "1121",
"license": "mit",
"hash": 3094429550628373000,
"line_mean": 34.03125,
"line_max": 92,
"alpha_frac": 0.6485280999,
"autogenerated": false,
"ratio": 3.9195804195804196,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.506810851948042,
"avg_score": null,
"num_lines": null
} |
#from fos.actor.network import AttributeNetwork
from nose.tools import assert_true, assert_false, \
assert_equal, assert_raises
from numpy.testing import assert_array_equal, assert_array_almost_equal
import numpy as np
from fos.actor.network import NodeGLPrimitive
def test_nodeglprimitive_makecube():
node_position = np.array( [[0,0,0],
[1,1,1],
[10,10,10]], dtype = np.float32 )
node_size = np.array( [1.0, 1.0, 2.0], dtype = np.float32 )
prim = NodeGLPrimitive()
prim._make_cubes(node_position, node_size)
assert_equal(prim.vertices_nr, 24)
assert_equal(prim.indices_nr, 18)
assert_array_equal(prim.vertices[0,:], np.array( [[ -0.5, -0.5, -0.5]],
dtype = np.float32))
assert_array_equal(prim.vertices[24,:], np.array( [[ 11., 11., 11. ]],
dtype = np.float32))
if __name__ == '__main__':
test_nodeglprimitive_makecube() | {
"repo_name": "fos/fos-legacy",
"path": "fos/actor/tests/test_network.py",
"copies": "1",
"size": "1081",
"license": "bsd-3-clause",
"hash": -4323326238334294500,
"line_mean": 29.9142857143,
"line_max": 75,
"alpha_frac": 0.540240518,
"autogenerated": false,
"ratio": 3.5794701986754967,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4619710716675497,
"avg_score": null,
"num_lines": null
} |
from fos.core.actors import Actor
import numpy as np
class Empty(Actor):
def __init__(self):
pass
def init(self):
pass
def display(self):
print 'Near_pick', self.near_pick
print 'Far_pick', self.far_pick
def map_colors(object, colors):
''' Map colors for specific objects
Examples:
---------
>>> from fos.core import primitives
>>> primitives.map_colors([np.zeros((10,3)),np.ones((3,3))], (1,1,1,0))
[array([[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0]]),
array([[1, 1, 1, 0],
[1, 1, 1, 0],
[1, 1, 1, 0]])]
>>> primitives.map_colors([np.zeros((10,3)),np.ones((3,3))], np.array([[1,1,1],[0,1,0]]))
[array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]),
array([[0, 1, 0],
[0, 1, 0],
[0, 1, 0]])]
See Also:
---------
fos.core.tracks
'''
if hasattr(object,'insert'): #object is a list
if hasattr( object[0], 'shape') : #object is a list of arrays
if hasattr(colors, 'shape') : # colors is a numpy array
if colors.ndim == 1: # one color only for all objects
new_colors=[np.tile(colors,(len(arr),1)) for arr in object]
return new_colors
if colors.ndim == 2: # one color for every element of the list object
if len(colors) == len(object): # absolutely
# necessary check
new_colors=[np.tile(colors[i],(len(arr),1)) for (i,arr) in enumerate(object)]
return new_colors
raise ValueError('object len needs to be the same \
with colors len')
if isinstance(colors,list): # colors is a list object
if len(colors)==3 or len(colors)==4:
colors = np.array(colors)
new_colors=[np.tile(colors,(len(arr),1)) for arr in object]
return new_colors
else:
raise ValueError('colors can be one list of 3 or 4 \
values')
if isinstance(colors,tuple):
if len(colors)==3 or len(colors)==4:
colors = np.array(colors)
new_colors=[np.tile(colors,(len(arr),1)) for arr in object]
return new_colors
else:
raise ValueError('colors can be one tuple of 3 or 4 \
values')
else:
raise ValueError('Unknown object type')
if hasattr(object, 'shape'): # object is a numpy array
if object.ndim == 2: # 2d numpy array
pass
if object.ndim == 1: # 1d numpy array
return colors
pass
| {
"repo_name": "fos/fos-legacy",
"path": "scratch/very_scratch/core/primitives.py",
"copies": "1",
"size": "3187",
"license": "bsd-3-clause",
"hash": -5356462813848106000,
"line_mean": 21.2867132867,
"line_max": 101,
"alpha_frac": 0.436774396,
"autogenerated": false,
"ratio": 3.7760663507109005,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47128407467109,
"avg_score": null,
"num_lines": null
} |
from fos import *
import numpy as np
import sys
import h5py
f=h5py.File(sys.argv[1], 'r')
vertices_id = f['Microcircuit']['vertices']['id'].value
vertices_location = f['Microcircuit']['vertices']['location'].value
connectivity_id = f['Microcircuit']['connectivity']['id'].value
connectivity_skeletonid = f['Microcircuit']['connectivity']['skeletonid'].value
connectivity_type = f['Microcircuit']['connectivity']['type'].value
vertices_location = ((vertices_location - np.mean(vertices_location, axis=0))).astype(np.float32) / 100.
def map_vertices_id2index(vertices_id):
map_vertices_id2index = dict(zip(vertices_id,range(len(vertices_id))))
connectivity_indices = np.zeros( connectivity_id.shape, dtype=np.uint32 )
for i,c in enumerate(connectivity_id):
connectivity_indices[i,0]=map_vertices_id2index[connectivity_id[i,0]]
connectivity_indices[i,1]=map_vertices_id2index[connectivity_id[i,1]]
return connectivity_indices
conn_color_map = {
1 : np.array([[1.0, 1.0, 0.0, 1.0]]),
2 : np.array([[1.0, 0.0, 0.0, 1.0]]),
3 : np.array([[0.0, 0.0, 1.0, 1.0]])
}
# Because the range to encode the id as RGB is limited
miin=connectivity_skeletonid.min()
connectivity_skeletonid = connectivity_skeletonid-miin
w = Window( dynamic = True )
mytransform = Transform3D(np.eye(4))
mytransform.set_scale(-1, -1, 1)
#mytransform.set_scale(0.01, 0.01, 0.01)
scene = Scene( scenename = "Main", transform = mytransform)
act = Microcircuit(
name="Testcircuit",
vertices_location=vertices_location,
connectivity=map_vertices_id2index(vertices_id),
connectivity_ids=connectivity_skeletonid,
connectivity_label=connectivity_type,
connectivity_label_metadata=[
{ "name" : "skeleton", "value" : "1" },
{ "name" : "presynaptic", "value" : "2" },
{ "name" : "postsynaptic", "value" : "3" }
],
connectivity_colormap=conn_color_map,
skeleton_linewidth=3.0,
connector_size=1.0,
global_deselect_alpha=0.1
)
scene.add_actor( act )
scene.add_actor( Axes( name = "3 axes", linewidth = 5.0) )
#values = np.ones( (len(vertices_location)) ) * 0.1
#scene.add_actor( Scatter( "MySphere", vertices_location[:,0], vertices_location[:,1], vertices_location[:,2], values, iterations = 2 ) )
w.add_scene ( scene )
act.deselect_all()
act.select_skeleton( [17611396-miin] )
w.refocus_camera()
| {
"repo_name": "fos/fos",
"path": "examples/microcircuit_neurohdf.py",
"copies": "1",
"size": "2440",
"license": "bsd-3-clause",
"hash": -3637242942208257500,
"line_mean": 33.3661971831,
"line_max": 137,
"alpha_frac": 0.662295082,
"autogenerated": false,
"ratio": 3.1362467866323906,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9212996087746694,
"avg_score": 0.01710915617713936,
"num_lines": 71
} |
from fos import *
import numpy as np
# testcircuit from the microcircuit package
from microcircuit.dataset.testcircuit002 import testcircuit as tc
con_prob = {
"label" : { "data" : np.ones( (tc.vertices.shape[0],1), ),
"metadata" : {
"semantics" : [
{ "name" : "skeleton", "value" : "1" },
{ "name" : "presynaptic", "value" : "2" },
{ "name" : "postsynaptic", "value" : "3" }
]
}
},
"id" : { "data" : np.array(range(tc.vertices.shape[0])), "metadata" : { } }
}
w = Window( )
scene = Scene( scenename = "Main" )
act = Microcircuit(
name = "Testcircuit",
vertices = tc.vertices,
connectivity = tc.connectivity,
#vertices_properties = vertices_properties,
connectivity_properties = con_prob,
#connectivity_colormap = conn_color_map
)
scene.add_actor( act )
scene.add_actor( Axes( name = "3 axes", linewidth = 5.0) )
w.add_scene ( scene )
w.refocus_camera() | {
"repo_name": "fos/fos",
"path": "examples/microcircuit_testcircuit.py",
"copies": "1",
"size": "1049",
"license": "bsd-3-clause",
"hash": -1550712535635803400,
"line_mean": 28.1666666667,
"line_max": 79,
"alpha_frac": 0.5376549094,
"autogenerated": false,
"ratio": 3.394822006472492,
"config_test": false,
"has_no_keywords": true,
"few_assignments": false,
"quality_score": 0.4432476915872492,
"avg_score": null,
"num_lines": null
} |
from foundation.Bid import Bid
from foundation.ChannelClockServer import Channel_ClockServer
from foundation.ChannelMarketplace import Channel_Marketplace
from foundation.FoundationException import FoundationException
from foundation.Message import Message
from foundation.Service import Service
from multiprocessing import Process
from AgentType import AgentType
import random
import agent_properties
import asyncore
import logging
import re
import socket
import SocketServer
import threading
import time
import uuid
import xml.dom.minidom
import threading
logger = logging.getLogger('agent_server')
logger.setLevel(logging.INFO)
fh = logging.FileHandler('agent_server_logs.log', mode='w')
formatter = logging.Formatter('format="%(threadName)s:-%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
class AgentServerHandler(asyncore.dispatcher):
'''
The AgentServerHandler class implements methods to deal with the
agents basic operations.
'''
IDLE = 0
BID_PERMITED = 2
TO_BE_ACTIVED = 3
ACTIVATE = 4
TERMINATE = 5
def __init__(self, addr, sock, thread_sockets, lock, testThread, list_args, strings_received):
asyncore.dispatcher.__init__(self, sock=sock, map=thread_sockets)
self._list_args = list_args
self._addr_orig = addr
self._sock_orig = sock
self._strings_received = strings_received
self.lock = lock
self.testThread = testThread
logger.debug('Nbr sockets being track: %d', len(thread_sockets))
def end_period_process(self, message):
pass
def start_period_process(self, message):
pass
'''
This method activates the agent with all its parameters.
'''
def activate(self, message):
logger.debug('Activating the consumer: %s', str(self._list_args['Id']) )
self.lock.acquire()
try:
agent_type = self._list_args['Type']
if ( agent_type.getType() == AgentType.CONSUMER_TYPE):
parameters = {}
serviceId = message.getParameter("Service")
quantityStr = message.getParameter("Quantity")
period = int(message.getParameter("Period"))
parameters['service'] = serviceId
parameters['quantity'] = float(quantityStr)
# set the state to be active.
self._list_args['State'] = AgentServerHandler.TO_BE_ACTIVED
self._list_args['Parameters'] = parameters
self._list_args['Current_Period'] = period
if (agent_type.getType() == AgentType.PRESENTER_TYPE):
logger.info('Activating the Presenter: %s - Period %s',
str(self._list_args['Id']),
str(self._list_args['Current_Period']) )
self._list_args['State'] = AgentServerHandler.ACTIVATE
finally:
if self.testThread == True:
time.sleep(2)
self.lock.release()
'''
This method transform the object into XML.
'''
def getText(self, nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
'''
This method removes ilegal characters.
'''
def removeIlegalCharacters(self,xml):
RE_XML_ILLEGAL = u'([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])' + \
u'|' + \
u'([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])' % \
(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),
unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),
unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
xml = re.sub(RE_XML_ILLEGAL, " ", xml)
return xml
'''
This method addresses the offers from competitors.
'''
def handledCompetitorBid(self , bidCompetitor):
logger.debug('Initiating handle Competitor Bid')
idElement = bidCompetitor.getElementsByTagName("Id_C")[0]
bid_competior_id = self.getText(idElement.childNodes)
quantityElement = bidCompetitor.getElementsByTagName("Q_C")[0]
quantity_competitor = float(self.getText(quantityElement.childNodes))
return bid_competior_id, quantity_competitor
'''
This method handles the quantity of services sold by competitors,
aiming to share the market.
'''
def handlePurchaseCompetitorBids(self, bidPair, bidCompetitors):
logger.debug('Initiating handle Bid competitors')
for bidCompetitor in bidCompetitors:
bid_competior_id, quantity_competitor = self.handledCompetitorBid(bidCompetitor)
if bid_competior_id in bidPair:
bidPair[bid_competior_id] += quantity_competitor
else:
bidPair[bid_competior_id] = quantity_competitor
'''
This method checks if an offer was bought or not. If the offer
was not bought, the method tries to equal the competitor offer.
'''
def handleBid(self,period, bidNode):
logger.debug('Initiating handle Bid')
self.lock.acquire()
try:
idElement = bidNode.getElementsByTagName("Id")[0]
bidId = self.getText(idElement.childNodes)
quantityElement = bidNode.getElementsByTagName("Quantity")[0]
quantity = float(self.getText(quantityElement.childNodes))
bidCompetitors = bidNode.getElementsByTagName("Cmp_Bid")
logger.debug('handled Bid - loaded Id and quantity')
if (bidId in self._list_args['Bids_Usage']):
logger.debug('handled Bid - Bid found in bid usage')
if (period in (self._list_args['Bids_Usage'])[bidId]):
logger.debug('handled Bid - period found')
bidPair = ((self._list_args['Bids_Usage'])[bidId])[period]
if bidId in bidPair:
bidPair[bidId] += quantity
else:
bidPair[bidId] = quantity
self.handlePurchaseCompetitorBids( bidPair, bidCompetitors)
else:
logger.debug('handled Bid - period not found')
bidPair = {}
bidPair[bidId] = quantity
self.handlePurchaseCompetitorBids( bidPair, bidCompetitors)
((self._list_args['Bids_Usage'])[bidId])[period] = bidPair
else:
logger.debug('handled Bid - Bid not found in bid usage')
bidPair = {}
bidPair[bidId] = quantity
(self._list_args['Bids_Usage'])[bidId] = {}
logger.debug('handled Bid - Bid not found in bid usage')
self.handlePurchaseCompetitorBids( bidPair, bidCompetitors)
logger.debug('handled Bid - Bid not found in bid usage')
((self._list_args['Bids_Usage'])[bidId])[period] = bidPair
finally:
if self.testThread == True:
time.sleep(2)
self.lock.release()
'''
This method handles the purchase orders sent from the marketplace
once the offering period is open.
'''
def handleReceivePurchases(self,period, purchaseXmlNode):
logger.debug('Initiating Receive Purchases')
bids = purchaseXmlNode.getElementsByTagName("Bid")
for bid in bids:
self.handleBid(period, bid)
logger.debug('Ending Receive Purchases')
#print self._list_args['Bids_Usage']
'''
This method gets all related competitors offerings and store
in a list.
'''
def handleCompetitorBids(self, period, competitorsXmlNode):
bids = competitorsXmlNode.getElementsByTagName("Bid")
try:
agent_type = self._list_args['Type']
if ( agent_type.getType() == AgentType.PRESENTER_TYPE):
logger.debug('Handle competitor bids')
self._list_args['Current_Bids'] = {}
logger.debug('clear Handle competitor bids')
for bid in bids:
logger.debug('We are inside the bid loop')
competitor_bid = Bid()
competitor_bid.setFromXmlNode(bid)
if (competitor_bid.getProvider() != self._list_args['strId']):
if (competitor_bid.getService() == (self._list_args['serviceId'])):
if (competitor_bid.getId() in self._list_args['Related_Bids']):
# The bid must be replaced as the provider update it.
oldCompetitorBid = (self._list_args['Related_Bids'])[competitor_bid.getId()]
competitor_bid.setCreationPeriod(oldCompetitorBid.getCreationPeriod())
(self._list_args['Related_Bids'])[competitor_bid.getId()] = competitor_bid
else:
if (competitor_bid.isActive() == True):
competitor_bid.setCreationPeriod(period)
# Replace the parent bid, looking for the actual one already in the dictionary
if (competitor_bid.getParentBid() != None):
parentBidId = competitor_bid.getParentBid().getId()
if parentBidId not in self._list_args['Related_Bids']:
logger.error('Parent BidId %s not found in related bids', parentBidId)
else:
parentBid = (self._list_args['Related_Bids'])[parentBidId]
competitor_bid.insertParentBid(parentBid)
#logger.debug('Inserting competitor bid:' + competitor_bid.__str__())
(self._list_args['Related_Bids'])[competitor_bid.getId()] = competitor_bid
# Inserts on exchanged bids
if (agent_type.getType() == AgentType.PRESENTER_TYPE):
(self._list_args['Current_Bids'])[competitor_bid.getId()] = competitor_bid
if (agent_type.getType() == AgentType.PRESENTER_TYPE):
logger.debug('End Handle competitor bids - num exchanged:' + str(len(self._list_args['Current_Bids'])))
logger.debug('clear 3 Handle competitor bids')
logger.debug('Ending handled bid competitors for agent is:' + str(self._list_args['Id']))
except Exception as e:
raise FoundationException(str(e))
'''
This method receives the offer information from competitors
'''
def receive_bid_information(self, message):
self.lock.acquire()
if self.testThread == True:
logger.debug('Acquire the lock')
try:
logger.debug('Initiating competitor bid information - Agent:%s', str(self._list_args['Id']) )
agent_type = self._list_args['Type']
if (( agent_type.getType() == AgentType.PROVIDER_ISP) or
(agent_type.getType() == AgentType.PROVIDER_BACKHAUL) or
(agent_type.getType() == AgentType.PRESENTER_TYPE)):
period = int(message.getParameter("Period"))
period = period - 1 # The server sends the information tagged with the next period.
# TODO: Change the Market Place Server to send the correct period.
document = self.removeIlegalCharacters(message.getBody())
logger.info('Period' + str(period) + 'bid document' + str(document))
dom = xml.dom.minidom.parseString(document)
competitorsXmlNodes = dom.getElementsByTagName("New_Bids")
for competitorsXmlNode in competitorsXmlNodes:
self.handleCompetitorBids(period, competitorsXmlNode)
logger.debug('Competitor bids Loaded Agent: %s', str(self._list_args['Id']))
except Exception as e:
logger.debug('Exception raised' + str(e) )
raise FoundationException(str(e))
finally:
if self.testThread == True:
logger.info('Going to sleep')
time.sleep(2)
logger.info('After sleep')
self.lock.release()
'''
This method receives purchase statistics from providers. For each
offer we receive its neigborhood offers.
'''
def receive_purchase_feedback(self, message):
self.lock.acquire()
try:
logger.debug('Initiating Receive Purchase feedback Agent:%s', str(self._list_args['Id']))
agent_type = self._list_args['Type']
if (( agent_type.getType() == AgentType.PROVIDER_ISP)
or ( agent_type.getType() == AgentType.PROVIDER_BACKHAUL)
or ( agent_type.getType() == AgentType.PRESENTER_TYPE)):
period = int(message.getParameter("Period"))
self._list_args['Current_Period'] = period
document = self.removeIlegalCharacters(message.getBody())
#print document
dom = xml.dom.minidom.parseString(document)
# receive purchase statistics
purchaseXmlNodes = dom.getElementsByTagName("Receive_Purchases")
for purchaseXmlNode in purchaseXmlNodes:
self.handleReceivePurchases(period, purchaseXmlNode)
# After receiving the purchase information the provider can
# start to create new bids.
if (( agent_type.getType() == AgentType.PROVIDER_ISP)
or (agent_type.getType() == AgentType.PROVIDER_BACKHAUL)):
self._list_args['State'] = AgentServerHandler.BID_PERMITED
logger.debug('Receive Purchase feedback - Agent:%s Period: %s ', str(self._list_args['Id']), str(self._list_args['Current_Period'] ))
except Exception as e:
raise FoundationException(str(e))
finally:
if self.testThread == True:
time.sleep(2)
self.lock.release()
'''
This method terminates the agent processing state.
'''
def disconnect_process(self):
self.lock.acquire()
try:
self._list_args['State'] = AgentServerHandler.TERMINATE
logger.debug('Terminate processing, the state is now in: %s',
str(self._list_args['State']) )
finally:
self.lock.release()
def process_getUnitaryCost(self, message):
logger.debug('Initiating process GetUnitaryCost')
self.lock.acquire()
try:
bid = None
agent_type = self._list_args['Type']
if (( agent_type.getType() == AgentType.PROVIDER_ISP)
or ( agent_type.getType() == AgentType.PROVIDER_BACKHAUL)):
bidId = message.getParameter("BidId")
if bidId in self._list_args['Bids']:
bid = (self._list_args['Bids']).get(bidId)
if bidId in self._list_args['Inactive_Bids']:
bid = (self._list_args['Inactive_Bids']).get(bidId)
if (bid is not None):
unitary_cost = bid.getUnitaryCost()
message = Message('')
message.setMethod(Message.GET_UNITARY_COST)
message.setMessageStatusOk()
message.setParameter("UnitaryCost", str(unitary_cost))
else:
message = Message('')
message.setMethod(Message.GET_UNITARY_COST)
message.setParameter("Status_Code", "310")
messageResponse.setParameter("Status_Description", "Bid is not from the provider")
else:
message = Message('')
message.setMethod(Message.GET_UNITARY_COST)
message.setParameter("Status_Code", "330")
messageResponse.setParameter("Status_Description", "The agent is not a provider")
self.send(message.__str__())
logger.debug('Ending process GetUnitaryCost')
finally:
if self.testThread == True:
time.sleep(2)
self.lock.release()
'''
This method returns the message parameters.
'''
def getMessage(self, string_key):
foundIdx = (self._strings_received[string_key]).find("Method")
if (foundIdx == 0):
foundIdx2 = (self._strings_received[string_key]).find("Method", foundIdx + 1)
if (foundIdx2 != -1):
message = Message( (self._strings_received[string_key])[foundIdx : foundIdx2 - 1])
# Even that the message could have errors is complete
self._strings_received[string_key] = (self._strings_received[string_key])[foundIdx2 : ]
else:
message = Message((self._strings_received[string_key]))
try:
isComplete = message.isComplete( len(self._strings_received[string_key]) )
if (isComplete):
(self._strings_received[string_key]) = ''
else:
message = None
except FoundationException as e:
message = None
else:
if (len(self._strings_received[string_key]) == 0):
message = None
else:
# The message is not well formed, so we create a message with method not specified
message = Message('')
message.setMethod(Message.UNDEFINED)
(self._strings_received[string_key])[foundIdx : ]
return message
'''
This method implements the message status, such as start and end
period, disconnect, receive purchase and purchase feedback, and
activate the consumer.
'''
def do_processing(self, message):
logger.debug('Initiating do_processing %s', message.getStringMethod())
if (message.getMethod() == Message.END_PERIOD):
self.end_period_process(message)
elif (message.getMethod() == Message.START_PERIOD):
self.start_period_process(message)
elif (message.getMethod() == Message.DISCONNECT):
self.disconnect_process()
elif (message.getMethod() == Message.RECEIVE_PURCHASE):
self.receive_purchase(message)
elif (message.getMethod() == Message.ACTIVATE_CONSUMER):
self.activate(message)
elif (message.getMethod() == Message.RECEIVE_BID_INFORMATION):
self.receive_bid_information(message)
elif (message.getMethod() == Message.RECEIVE_PURCHASE_FEEDBACK):
self.receive_purchase_feedback(message)
elif (message.getMethod() == Message.GET_UNITARY_COST):
self.process_getUnitaryCost(message)
elif (message.getMethod() == Message.ACTIVATE_PRESENTER):
self.activate(message)
else:
logger.error('Message for parent %s with request method not handled: %s',
self._list_args['Id'], message.getStringMethod() )
'''
This method reads data from the socket until a complete
message is received
'''
def handle_read(self):
# Reads data from the socket until a complete message is received
try:
string_key = repr(self._addr_orig) + repr(self._sock_orig)
message = None
data = self.recv(1024)
self._strings_received[string_key] += data
message = self.getMessage(string_key)
logger.debug('Message for parent %s from:%s, character received:%s', self._list_args['Id'], string_key, str(len(self._strings_received[string_key])) )
# We need to do a while because more than one message could arrive almost at the same time for the agent.
while (message is not None):
logger.debug('Message for parent %s message: %d',self._list_args['Id'], len(message.__str__()) )
self.do_processing(message)
message = self.getMessage(string_key)
except Exception as e:
raise asyncore.ExitNow('Server is quitting!')
def handle_close(self):
#Flush the buffer
print self._sock_orig.getsockname()
logger.debug('closing connection host:%s port:%s',self._addr_orig, (self._sock_orig.getsockname(),))
self.close()
def handle_expt(self):
print self._sock_orig.getsockname()
logger.debug('Handle except host:%s port:%s',self._addr_orig, (self._sock_orig.getsockname(),))
self.close() # connection failed, shutdown
def writable(self):
return 0 # don't have anything to write
class AgentDispacher(asyncore.dispatcher):
def __init__(self, address, port, lock, testThread, thread_sockets, list_args):
asyncore.dispatcher.__init__(self, map=thread_sockets)
self._address = address
self._port = port
self._strings_received = {}
self._list_args = list_args
self._lock = lock
self._testThread = testThread
self._thread_sockets = thread_sockets
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((self._address, self._port))
self.listen(4)
logger.debug("Server Listening on {h}:{p}".format(h=self._address, p=self._port))
'''
This method handles the acceptance of incoming socket connection.
'''
def handle_accept(self):
logger.debug('handle Accept Id: %s', self._list_args['Id'])
pair = self.accept()
if pair is not None:
logger.debug('handle Accept Id: %s address:%s port:%s', self._list_args['Id'], self._address, self._port)
sock, addr = pair
logger.debug('Incoming connection from %s', repr(addr))
string_pair = repr(addr) + repr(sock)
self._strings_received[string_pair] = ''
try:
handler = AgentServerHandler( addr, sock, self._thread_sockets, self._lock, self._testThread, self._list_args, self._strings_received)
except asyncore.ExitNow, e:
raise FoundationException(str(e))
logger.debug('Ending handle Accept Id: %s address:%s port:%s', self._list_args['Id'], self._address, self._port)
def handle_close(self):
self.close()
'''
The class AgentListener defines the methods for listening the port.
'''
class AgentListener(threading.Thread):
def __init__(self, address, port, lock, testThread, list_args, group=None, target=None, name=None,
args=(), kwargs=None, verbose=None):
threading.Thread.__init__(self, group=group, target=target, name=name,
verbose=verbose)
self._stop = threading.Event()
self._thread_sockets = dict()
self._lock = lock
self._address = address
self._port = port
self._testThread = testThread
self._list_args = list_args
self._agentDispacher = AgentDispacher(self._address, self._port, self._lock, self._testThread, self._thread_sockets, self._list_args)
logger.info('initiating with address:%s port:%d arg:%s', address, port, list_args)
return
'''
This method starts listening the port.
'''
def run(self):
asyncore.loop(map=self._thread_sockets)
logger.info('asyncore ends Agent:%s address:%s port:%s', self._list_args['Id'], self._address, self._port)
return
def stop(self):
logger.debug('Start Stop thread address:%s port:%s', self._address, self._port)
self._agentDispacher.close()
logger.info('close the dispatcher Agent Id:%s - Address:%s port:%s', self._list_args['Id'], self._address, self._port)
'''
This method stops listening the port.
'''
def stopped(self):
return self._stop.isSet()
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/AgentServer.py",
"copies": "1",
"size": "24582",
"license": "mit",
"hash": 8908715504662643000,
"line_mean": 44.6914498141,
"line_max": 162,
"alpha_frac": 0.574526076,
"autogenerated": false,
"ratio": 4.151663570342848,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5226189646342848,
"avg_score": null,
"num_lines": null
} |
from foundation.Bid import Bid
from foundation.ChannelClockServer import Channel_ClockServer
from foundation.ChannelMarketplace import Channel_Marketplace
from foundation.FoundationException import FoundationException
from foundation.Message import Message
from foundation.Service import Service
from AgentType import AgentType
import random
import agent_properties
import logging
import re
import socket
import SocketServer
import threading
import time
import uuid
import xml.dom.minidom
logger = logging.getLogger('agent')
fh = logging.FileHandler('agent_logs.log')
fh.setLevel(logging.INFO)
formatter = logging.Formatter('format="%(threadName)s:-%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
class AgentClient:
def __init__(self, list_vars):
self._list_vars = list_vars
self._channelMarketPlace = None
self._channelMarketPlaceBuy =None
self._channelClockServer =None
def create_connect_message(self, strID):
connect = Message("")
connect.setMethod(Message.CONNECT)
connect.setParameter("Agent",strID)
return connect
'''
This method removes ilegal characters from the XML messages.
'''
def removeIlegalCharacters(self,xml):
RE_XML_ILLEGAL = u'([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])' + \
u'|' + \
u'([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])' % \
(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),
unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),
unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
xml = re.sub(RE_XML_ILLEGAL, " ", xml)
return xml
'''
This function connects the agent to servers ( clock server and markets places)
'''
def connect_servers(self, agent_type, strID, sellingAddress, buyingAddress, capacityControl):
logger.info('Starting connect servers agent %s selling Address:%s buyingAddress:%s', strID, sellingAddress, buyingAddress)
if (agent_type.getType() == AgentType.PROVIDER_ISP):
logger.debug('Agent Provider ISP %s', strID)
port = agent_properties.mkt_place_listening_port
address = sellingAddress
# This will be the channel to put bids.
self._channelMarketPlace = Channel_Marketplace(address, port)
address = buyingAddress
# This will be the channel to buy resources.
self._channelMarketPlaceBuy = Channel_Marketplace(address, port)
elif (agent_type.getType() == AgentType.PROVIDER_BACKHAUL):
logger.debug('Agent Provider Backhaul %s', strID)
port = agent_properties.mkt_place_listening_port
address = sellingAddress
# This will be the channel to put bids.
self._channelMarketPlace = Channel_Marketplace(address, port)
else:
logger.debug('Agent Other %s', strID)
port = agent_properties.mkt_place_listening_port
address = agent_properties.addr_mktplace_isp
self._channelMarketPlace = Channel_Marketplace(address, port)
self._channelClockServer = Channel_ClockServer()
# Send the Connect message to ClockServer
connect = self.create_connect_message(strID)
response1 = (self._channelClockServer).sendMessage(connect)
if (response1.isMessageStatusOk() == False):
raise FoundationException("Agent: It could not connect to clock server")
# Send the Connect message to MarketPlace
if (agent_type.getType() == AgentType.PROVIDER_ISP):
response2 = (self._channelMarketPlace).sendMessage(connect)
if (response2.isMessageStatusOk()):
response3 = (self._channelMarketPlaceBuy).sendMessage(connect)
if (response3.isMessageStatusOk() ):
logger.debug('We could connect to servers')
else:
logger.error('Provider ISP: It could not connect to the market place to Buy')
raise FoundationException("Provider ISP: It could not connect to the market place to Buy")
else:
logger.error('Provider ISP: It could not connect to market place to sell')
raise FoundationException("Provider ISP: It could not connect to market place to sell")
else:
response2 = (self._channelMarketPlace).sendMessage(connect)
if ( response2.isMessageStatusOk() ):
logger.info('We could connect servers')
else:
logger.error('The agent could not connect to market place')
raise FoundationException("Agent: It could not connect to market place")
logger.debug('Ending connect servers agent %s', strID)
def disconnect_servers(self, agent_type):
logger.debug('Disconnect Servers Id:%s', self._list_vars['Id'])
if (agent_type.getType() == AgentType.PROVIDER_ISP):
logger.debug('Disconnect provider isp')
self._channelMarketPlace.close()
self._channelMarketPlaceBuy.close()
elif (agent_type.getType() == AgentType.PROVIDER_BACKHAUL):
# This will be the channel to put bids.
logger.debug('Disconnect provider backhaul')
self._channelMarketPlace.close()
else:
logger.debug('Disconnect other different from provider')
self._channelMarketPlace.close()
self._channelClockServer.close()
logger.debug('Ending Diconnect servers agent %s', self._list_vars['Id'])
def sendMessageClock(self,message):
response = Message('')
if self._channelClockServer != None:
response = (self._channelClockServer).sendMessage(message)
return response
def sendMessageMarket(self , message):
response = Message('')
if self._channelMarketPlace != None:
response = (self._channelMarketPlace).sendMessage(message)
return response
def sendMessageMarketBuy(self , message):
response = Message('')
if self._channelMarketPlaceBuy != None:
response = (self._channelMarketPlaceBuy).sendMessage(message)
return response
'''
This method handles the GetService function. It checks if the
server has sent more than one message.
'''
def handleGetService(self, document):
logger.debug('Starting get service handler Id:%s', self._list_vars['Id'])
document = self.removeIlegalCharacters(document)
logger.debug('document:%s', document)
try:
dom = xml.dom.minidom.parseString(document)
servicesXml = dom.getElementsByTagName("Service")
if (len(servicesXml) > 1):
raise FoundationException("The server sent more than one service")
else:
service = Service()
for servicexml in servicesXml:
service.setFromXmlNode(servicexml)
logger.debug('Ending get service handler')
return service
except Exception as e:
raise FoundationException(str(e))
logger.debug('Ending get service handler Id:%s', self._list_vars['Id'])
'''
This method handles the GetServices function. It removes ilegal
characters and get the service statement.
'''
def handleGetServices(self, document):
logger.debug('Starting get service Id:%s', self._list_vars['Id'])
document = self.removeIlegalCharacters(document)
try:
dom = xml.dom.minidom.parseString(document)
servicesXml = dom.getElementsByTagName("Service")
services = {}
for servicexml in servicesXml:
service = Service()
service.setFromXmlNode(servicexml)
services[service.getId()] = service
return services
except Exception as e:
raise FoundationException(str(e))
logger.debug('Ending get service Id:%s', self._list_vars['Id'])
def getServiceFromServer(self, serviceId):
logger.debug('Starting getServiceFromServer Id:%s', self._list_vars['Id'])
try:
connect = Message("")
connect.setMethod(Message.GET_SERVICES)
connect.setParameter("Service",serviceId)
response = self.sendMessageClock(connect)
if (response.isMessageStatusOk() ):
logger.debug('ending getServiceFromServer')
return self.handleGetService(response.getBody())
except FoundationException as e:
raise FoundationException(e.__str__())
'''
This method returns the available services.
'''
def getServices(self):
logger.debug('Starting get services Id:%s', self._list_vars['Id'])
messageAsk = Message('')
messageAsk.setMethod(Message.GET_SERVICES)
messageResult = self.sendMessageClock(messageAsk)
if messageResult.isMessageStatusOk():
return self.handleGetServices(messageResult.getBody())
else:
raise FoundationException('Services not received! Communication failed')
logger.debug('Ending get services Id:%s', self._list_vars['Id'])
'''
This method handles the best offers on the Pareto Front.
'''
def handleBestBids(self, docum):
logger.debug('Starting handleBestBids')
fronts = docum.getElementsByTagName("Front")
val_return = self.handleFronts(fronts)
logger.debug('Ending handleBestBids')
return val_return
'''
This method handles the Pareto Fronts.
'''
def handleFronts(self, fronts):
logger.debug('Starting handleFronts')
dic_return = {}
for front in fronts:
parNbrElement = front.getElementsByTagName("Pareto_Number")[0]
parNbr = int((parNbrElement.childNodes[0]).data)
dic_return[parNbr] = self.handleFront(front)
logger.debug('Ending handleFronts')
return dic_return
'''
This method handles the Pareto Front of offerings.
'''
def handleFront(self, front):
logger.debug('Starting handleFront')
val_return = []
bidXmLNodes = front.getElementsByTagName("Bid")
for bidXmlNode in bidXmLNodes:
bid = Bid()
bid.setFromXmlNode(bidXmlNode)
val_return.append(bid)
logger.debug('Ending handleFront' + str(len(val_return)))
return val_return
'''
This method creates the query for the Marketplace asking
other providers' offers.
'''
def createAskBids(self, serviceId):
messageAsk = Message('')
messageAsk.setMethod(Message.GET_BEST_BIDS)
messageAsk.setParameter('Provider', self._list_vars['strId'])
messageAsk.setParameter('Service', serviceId)
messageResult = self.sendMessageMarket(messageAsk)
if messageResult.isMessageStatusOk():
document = self.removeIlegalCharacters(messageResult.getBody())
try:
dom = xml.dom.minidom.parseString(document)
return self.handleBestBids(dom)
except Exception as e:
raise FoundationException(str(e))
else:
raise FoundationException("Best bids not received")
'''
This method creates the query for the Marketplace asking
other providers' offers.
'''
def AskBackhaulBids(self, serviceId):
messageAsk = Message('')
messageAsk.setMethod(Message.GET_BEST_BIDS)
messageAsk.setParameter('Provider', self._list_vars['strId'])
messageAsk.setParameter('Service', serviceId)
messageResult = self.sendMessageMarketBuy(messageAsk)
if messageResult.isMessageStatusOk():
document = self.removeIlegalCharacters(messageResult.getBody())
try:
dom = xml.dom.minidom.parseString(document)
return self.handleBestBids(dom)
except Exception as e:
raise FoundationException(str(e))
else:
raise FoundationException("Best bids not received")
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/AgentClient.py",
"copies": "1",
"size": "12761",
"license": "mit",
"hash": -305268230403306400,
"line_mean": 41.852233677,
"line_max": 131,
"alpha_frac": 0.611864274,
"autogenerated": false,
"ratio": 4.382211538461538,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5494075812461539,
"avg_score": null,
"num_lines": null
} |
from FoundationException import FoundationException
from Message import Message
import agent_properties
import socket
class Channel_ClockServer(object):
'''
The Channel_ClockServer class defines the methods for creating
the socket communication between the clock server and the simulation
environment (demand server). It includes the methods get and
send message, as well as closing the socket.
'''
def __init__(self):
# Creates the socket for Clock Server
self._streamStaged = ''
#HOST = '192.168.1.129' # The remote host
HOST = agent_properties.addr_clock_server
#PORT = 3333 # The same port as used by the server
PORT = agent_properties.clock_listening_port
self._s_clock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
err = self._s_clock.connect_ex((HOST, PORT))
if (err > 0):
raise FoundationException("Error: the Clock Server is not running")
def getMessage(self):
'''
This method is responsible for getting messages from
the socket.
'''
foundIdx = self._streamStaged.find("Method")
if (foundIdx == 0):
foundIdx2 = self._streamStaged.find("Method", foundIdx + 1)
if (foundIdx2 != -1):
message = Message(self._streamStaged[foundIdx : foundIdx2 - 1])
# Even that the message could have errors is complete
self._streamStaged = self._streamStaged[foundIdx2 : ]
else:
message = Message(self._streamStaged)
if (message.isComplete( len(self._streamStaged) )):
self._streamStaged = ''
else:
message = None
else:
if (len(self._streamStaged) == 0):
message = None
else:
# The message is not well formed, so we create a message with method not specified
message = Message('')
message.setMethod(Message.UNDEFINED)
self._streamStaged = self._streamStaged[foundIdx :]
return message
def sendMessage(self, message):
'''
This method is responsible for sending messages through the
socket.
'''
msgstr = message.__str__()
self._s_clock.sendall(msgstr)
messageResults = None
while (messageResults == None):
self._streamStaged = self._streamStaged + self._s_clock.recv(1024)
messageResults = self.getMessage()
return messageResults
def close(self):
'''
This method closes the socket.
'''
self._s_clock.shutdown(socket.SHUT_RDWR)
self._s_clock.close()
# End of Channel Marketplace class
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/ChannelClockServer.py",
"copies": "1",
"size": "2470",
"license": "mit",
"hash": 7049174092160336000,
"line_mean": 32.8356164384,
"line_max": 84,
"alpha_frac": 0.6668016194,
"autogenerated": false,
"ratio": 3.805855161787365,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9532051375080434,
"avg_score": 0.08812108122138615,
"num_lines": 73
} |
from FoundationException import FoundationException
from Message import Message
import socket
class ChannelProvider(object):
'''
The Channel_Provider class defines the methods for creating
the socket communication between the presenter and providers.
It includes the methods get and send message, as well as closing the socket.
'''
def __init__(self, address, port):
# Creates the socket
self._streamStaged = ''
HOST = address
PORT = port
self._s_provider = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
err = self._s_provider.connect_ex((HOST, PORT))
if (err > 0):
raise FoundationException("Error: the provider is not running")
def getMessage(self):
'''
This method is responsible for getting messages from
the socket.
'''
foundIdx = self._streamStaged.find("Method")
if (foundIdx == 0):
foundIdx2 = self._streamStaged.find("Method", foundIdx + 1)
if (foundIdx2 != -1):
message = Message(self._streamStaged[foundIdx : foundIdx2 - 1])
# Even that the message could have errors is complete
self._streamStaged = self._streamStaged[foundIdx2 : ]
else:
message = Message(self._streamStaged)
if (message.isComplete( len(self._streamStaged) )):
self._streamStaged = ''
else:
message = None
else:
if (len(self._streamStaged) == 0):
message = None
else:
# The message is not well formed, so we create a message with method not specified
message = Message('')
message.setMethod(Message.UNDEFINED)
self._streamStaged = self._streamStaged[foundIdx :]
return message
def sendMessage(self, message):
'''
This method is responsible for sending messages through the
socket.
'''
msgstr = message.__str__()
self._s_provider.sendall(msgstr)
messageResults = None
while (messageResults == None):
self._streamStaged = self._streamStaged + self._s_provider.recv(1024)
messageResults = self.getMessage()
return messageResults
def close(self):
'''
This method closes the socket.
'''
self._s_provider.shutdown(socket.SHUT_RDWR)
self._s_provider.close()
# End of Channel Marketplace class
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/ChannelProvider.py",
"copies": "1",
"size": "2232",
"license": "mit",
"hash": -6878527274061964000,
"line_mean": 31.347826087,
"line_max": 84,
"alpha_frac": 0.6666666667,
"autogenerated": false,
"ratio": 3.828473413379074,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.49951400800790735,
"avg_score": null,
"num_lines": null
} |
from FoundationException import FoundationException
class Message(object):
'''
The Message class declares methods to handle the messaging part of
the system. These methods include set and get message parameters
and body, and check if the message was received by the marketplace.
'''
# Initialize constants
UNDEFINED = 1
CONNECT = 2
RECEIVE_BID = 3
SEND_PORT = 4
START_PERIOD = 5
END_PERIOD = 6
RECEIVE_PURCHASE = 7
GET_BEST_BIDS = 8
GET_CURRENT_PERIOD = 9
DISCONNECT = 10
GET_SERVICES = 11
ACTIVATE_CONSUMER = 12
RECEIVE_PURCHASE_FEEDBACK = 13
SEND_AVAILABILITY = 14
RECEIVE_BID_INFORMATION = 15
GET_BID = 16
GET_PROVIDER_CHANNEL = 17
GET_UNITARY_COST = 18
ACTIVATE_PRESENTER = 19
GET_AVAILABILITY = 30
# define the separator
LINE_SEPARATOR = '\r\n'
MESSAGE_SIZE = 10
def __init__(self, messageStr):
self._method = Message.UNDEFINED
self._body = ''
self._parameters = {}
# Split message string when encounter LINE_SEPARATOR
splitList = messageStr.split(Message.LINE_SEPARATOR)
count = len(splitList)
# Split message string when encounter ':'
# Assign methods
if (count > 0):
methodLine = splitList[0]
methodParam = methodLine.split(':')
if (len(methodParam) == 2):
if (methodParam[1] == 'receiveBid'):
self._method = Message.RECEIVE_BID
elif (methodParam[1] == 'connect'):
self._method = Message.CONNECT
elif (methodParam[1] == 'disconnect'):
self._method = Message.DISCONNECT
elif (methodParam[1] == 'send_port'):
self._method = Message.SEND_PORT
elif (methodParam[1] == 'start_period'):
self._method = Message.START_PERIOD
elif (methodParam[1] == 'end_period'):
self._method = Message.END_PERIOD
elif (methodParam[1] == 'receive_purchase'):
self._method = Message.RECEIVE_PURCHASE
elif (methodParam[1] == 'get_best_bids'):
self._method = Message.GET_BEST_BIDS
elif (methodParam[1] == 'get_services'):
self._method = Message.GET_SERVICES
elif (methodParam[1] == 'activate_consumer'):
self._method = Message.ACTIVATE_CONSUMER
elif (methodParam[1] == 'receive_purchase_feedback'):
self._method = Message.RECEIVE_PURCHASE_FEEDBACK
elif (methodParam[1] == 'send_availability'):
self._method = Message.SEND_AVAILABILITY
elif (methodParam[1] == 'receive_bid_information'):
self._method = Message.RECEIVE_BID_INFORMATION
elif (methodParam[1] == 'get_bid'):
self._method = Message.GET_BID
elif (methodParam[1] == 'get_provider_channel'):
self._method = Message.GET_PROVIDER_CHANNEL
elif (methodParam[1] == 'get_unitary_cost'):
self._method = Message.GET_UNITARY_COST
elif (methodParam[1] == 'activate_presenter'):
self._method = Message.ACTIVATE_PRESENTER
elif (methodParam[1] == 'get_availability'):
self._method = Message.GET_AVAILABILITY
else:
self._method = Message.UNDEFINED
else:
self._method = Message.UNDEFINED
# Repeat for each line to get the parameters
if (count > 1):
i = 1
# Extracts the message header
while (i < count):
paramLine = splitList[i]
if (len(paramLine) == 0):
# Corresponds to the empty line
break
else:
lineParam = paramLine.split(':')
if (len(lineParam) == 2):
self._parameters[lineParam[0]] = lineParam[1]
i += 1
# Extracts the body
while (i < count):
self._body = self._body + splitList[i]
i += 1
def setParameter(self, parameterKey, parameterValue):
'''
This method add the parameter to the list of parameters.
'''
# First we check if the parameter key is already on the list
if parameterKey in self._parameters:
# If it is already on the list, we create an exception
raise FoundationException('Parameter is already included on the list')
# If not, we add the parameter to the list
else:
self._parameters[parameterKey] = parameterValue
def getParameter(self, param):
'''
This method returns the message parameter.
'''
if param in self._parameters:
return self._parameters[param]
else:
raise FoundationException('Parameter not found')
def setBody(self,param):
'''
This method sets the message body.
'''
self._body = param
def getBody(self):
'''
This method returns the message body.
'''
return self._body
def setMethod(self, method):
'''
This method sets the methos according with the message status.
'''
# Check if the provided method is correct
# if it's not correct, we put undefined
if (method == Message.RECEIVE_BID):
self._method = Message.RECEIVE_BID
elif (method == Message.CONNECT):
self._method = Message.CONNECT
elif (method == Message.DISCONNECT):
self._method = Message.DISCONNECT
elif (method == Message.SEND_PORT):
self._method = Message.SEND_PORT
elif (method == Message.START_PERIOD):
self._method = Message.START_PERIOD
elif (method == Message.END_PERIOD):
self._method = Message.END_PERIOD
elif (method == Message.RECEIVE_PURCHASE):
self._method = Message.RECEIVE_PURCHASE
elif (method == Message.GET_BEST_BIDS):
self._method = Message.GET_BEST_BIDS
elif (method == Message.GET_SERVICES):
self._method = Message.GET_SERVICES
elif (method == Message.ACTIVATE_CONSUMER):
self._method = Message.ACTIVATE_CONSUMER
elif (method == Message.RECEIVE_PURCHASE_FEEDBACK):
self._method = Message.RECEIVE_PURCHASE_FEEDBACK
elif (method == Message.SEND_AVAILABILITY):
self._method = Message.SEND_AVAILABILITY
elif (method == Message.RECEIVE_BID_INFORMATION):
self._method = Message.RECEIVE_BID_INFORMATION
elif (method == Message.GET_BID):
self._method = Message.GET_BID
elif (method == Message.GET_PROVIDER_CHANNEL):
self._method = Message.GET_PROVIDER_CHANNEL
elif (method == Message.GET_UNITARY_COST):
self._method = Message.GET_UNITARY_COST
elif (method == Message.ACTIVATE_PRESENTER):
self._method = Message.ACTIVATE_PRESENTER
elif (method == Message.GET_AVAILABILITY):
self._method = Message.GET_AVAILABILITY
else:
self._method = Message.UNDEFINED
def getMethod(self):
'''
This method returns the current message status.
'''
return self._method
def getStringMethod(self):
'''
Similar to getMethod, this method returns the current message
status, but in a string format.
'''
if (self._method == Message.RECEIVE_BID):
return "receive_bid"
elif (self._method == Message.CONNECT):
return "connect"
elif (self._method == Message.DISCONNECT):
return "disconnect"
elif (self._method == Message.SEND_PORT):
return "send_port"
elif (self._method == Message.START_PERIOD):
return "start_period"
elif (self._method == Message.END_PERIOD):
return "end_period"
elif (self._method == Message.RECEIVE_PURCHASE):
return "receive_purchase"
elif (self._method == Message.GET_BEST_BIDS):
return "get_best_bids"
elif (self._method == Message.GET_SERVICES):
return "get_services"
elif (self._method == Message.ACTIVATE_CONSUMER):
return "activate_consumer"
elif (self._method == Message.RECEIVE_PURCHASE_FEEDBACK):
return "receive_purchase_feedback"
elif (self._method == Message.SEND_AVAILABILITY):
return "send_availability"
elif (self._method == Message.RECEIVE_BID_INFORMATION):
return "receive_bid_information"
elif (self._method == Message.GET_BID):
return "get_bid"
elif (self._method == Message.GET_PROVIDER_CHANNEL):
return "get_provider_channel"
elif (self._method == Message.GET_UNITARY_COST):
return "get_unitary_cost"
elif (self._method == Message.ACTIVATE_PRESENTER):
return "activate_presenter"
elif (self._method == Message.GET_AVAILABILITY):
return "get_availability"
else:
return "invalid_method"
def __str__(self):
'''
This method reconstructs the original message appending
its parameters.
'''
result = 'Method:'
if self.getStringMethod() is not None:
result = result + self.getStringMethod()
result = result + Message.LINE_SEPARATOR
result2 = ''
for item in self._parameters:
result2 = result2 + item
result2 = result2 + ':'
result2 = result2 + str(self._parameters[item])
result2 = result2 + Message.LINE_SEPARATOR
result2 = result2 + Message.LINE_SEPARATOR
if self._body is not None:
result2 = result2 + self._body
result = result + 'Message_Size:'
size = len(result) + len(result2) + 2 + Message.MESSAGE_SIZE
sizeStr = str(size).zfill(Message.MESSAGE_SIZE)
result = result + sizeStr
result = result + Message.LINE_SEPARATOR
result = result + result2
return result
def isMessageStatusOk(self):
'''
This method checks if the message was sucesfully received.
'''
if ('Status_Code' in self._parameters):
code = int(self.getParameter('Status_Code'))
if (code == 200):
return True
else:
return False
return False
def setMessageStatusOk(self):
'''
This method establishes the message as Ok
'''
self.setParameter("Status_Code", "200");
self.setParameter("Status_Description", "OK");
def isComplete(self, lenght):
try:
size = self.getParameter("Message_Size")
messageSize = int(size)
if (lenght == messageSize):
return True
else:
return False
except FoundationException as e:
print 'The message is' + '\n' + self.__str__()
raise FoundationException("Parameter not found")
except ValueError as e:
print 'The value in size is' + str(size)
raise FoundationException("Invalid value inside Message Size")
# End of Message class
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/Message.py",
"copies": "1",
"size": "11686",
"license": "mit",
"hash": -1877483152334655000,
"line_mean": 37.9533333333,
"line_max": 82,
"alpha_frac": 0.5563922642,
"autogenerated": false,
"ratio": 4.403165033911078,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5459557298111077,
"avg_score": null,
"num_lines": null
} |
from foundation.FoundationException import FoundationException
import uuid
import logging
from foundation.AgentServer import AgentServerHandler
from foundation.AgentType import AgentType
from foundation.Agent import Agent
from foundation.Message import Message
from foundation.DecisionVariable import DecisionVariable
from ProviderAgentException import ProviderException
from Provider import Provider
from foundation.Bid import Bid
import MySQLdb
import xml.dom.minidom
import foundation.agent_properties
import math
logger = logging.getLogger('provider_public')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('provider_public.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
class ProviderPublic(Provider):
def __init__(self, strID, Id, serviceId, accessProviderSeed, marketPosition,
adaptationFactor, monopolistPosition, debug, resources,
numberOffers, numAccumPeriods, numAncestors, startFromPeriod,
sellingAddress, buyingAddress, capacityControl, purchase_service):
try:
logger.debug('Starting Init Agent:%s - Public Provider', strID)
agent_type = AgentType(AgentType.PROVIDER_BACKHAUL)
super(ProviderPublic, self).__init__(strID, Id, serviceId, accessProviderSeed, marketPosition, adaptationFactor, monopolistPosition, debug, resources, numberOffers, numAccumPeriods, numAncestors, startFromPeriod, sellingAddress, buyingAddress, capacityControl, purchase_service, agent_type)
logger.debug('Ending Init Agent: %s - Type:%s Public Provider Created', self._list_vars['strId'], str((self._list_vars['Type']).getType()))
except FoundationException as e:
raise ProviderException(e.__str__())
def calculateUnitaryResourceRequirements(self, bidQuality, fileResult):
'''
Calculates the resource requirement in order to execute the
service provided by a bid. with quality attributes speified in bidQuality
The parameter bidQuality has the requirements in quality for a bid that will be created
'''
self.registerLog(fileResult, 'Starting calculateBidUnitaryResourceRequirements')
resourceConsumption = {}
resources = self._used_variables['resources']
for decisionVariable in (self._service)._decision_variables:
minValue = ((self._service)._decision_variables[decisionVariable]).getMinValue()
maxValue = ((self._service)._decision_variables[decisionVariable]).getMaxValue()
resourceId = ((self._service)._decision_variables[decisionVariable]).getResource()
if ((self._service)._decision_variables[decisionVariable].getModeling() == DecisionVariable.MODEL_QUALITY):
# Bring the cost function associated to the decision variable.
decisionVar = (self._service)._decision_variables[decisionVariable]
costFun = decisionVar.getCostFunction() # None if not defined.
value = float(bidQuality[decisionVariable])
if ((self._service)._decision_variables[decisionVariable].getOptimizationObjective() == DecisionVariable.OPT_MAXIMIZE):
if ((maxValue - minValue) != 0):
percentage = ((value - minValue) / ( maxValue - minValue ))
else:
percentage = ((value - minValue) / minValue)
else:
if ((maxValue - minValue) != 0):
percentage = ((maxValue - value) / ( maxValue - minValue ))
else:
percentage = ((maxValue - value) / maxValue)
self.registerLog(fileResult, 'value:' + str(value) + 'Percentage:'+ str(percentage))
if resourceId in resources:
costValue = 0
if (costFun != None):
costValue = costValue + costFun.getEvaluation(percentage)
else:
# linear relationship with 1 to 1 relationship.
costValue = 1 + percentage
resourceConsumption.setdefault(resourceId, 0)
resourceConsumption[resourceId] += costValue
self.registerLog(fileResult, 'Ending calculateUnitaryResourceRequirements'+ str(resourceConsumption))
return resourceConsumption
def calculateUnitaryCost(self, resourceConsumption, fileResult):
'''
Calculates the bid unitary cost as a function of their decision variables
'''
self.registerLog(fileResult, 'Starting calculateUnitaryCost')
totalUnitaryCost = 0
resources = self._used_variables['resources']
for resource in resourceConsumption:
if resource in resources:
unitaryCost = float((resources[resource])['Cost'])
totalUnitaryCost = totalUnitaryCost + (unitaryCost * resourceConsumption[resource] )
self.registerLog(fileResult, 'Ending calculateUnitaryCost' + str(totalUnitaryCost))
return totalUnitaryCost
def initializeBidParameters(self, radius, fileResult):
logger.debug('Starting - initializeBidParameters')
output = {}
#initialize the bids separeated every radious distance
for decisionVariable in (self._service)._decision_variables:
logger.debug('initializeBidParameters - decision Variable %s', str(decisionVariable))
if ((self._service)._decision_variables[decisionVariable].getModeling() == DecisionVariable.MODEL_QUALITY):
if ((self._service)._decision_variables[decisionVariable].getOptimizationObjective() == DecisionVariable.OPT_MAXIMIZE):
optimum = 1 # Maximize
else:
optimum = 2 # Minimize
min_val = (self._service)._decision_variables[decisionVariable].getMinValue()
max_val = (self._service)._decision_variables[decisionVariable].getMaxValue()
logger.debug('miValue %s - maxValue%s', str(min_val), str(max_val))
if (optimum == 1):
k = 0
val = min_val
output[k] = {}
while val < max_val:
(output[k])[decisionVariable] = val
k = k+1
val = min_val + (k*radius*(max_val-min_val))
if val < max_val:
output[k] = {}
logger.debug('Value %s ', str(val))
else:
k = 0
output[k] = {}
val = max_val
while val > min_val:
(output[k])[decisionVariable] = val
k = k + 1
val = max_val - (k*radius*(max_val-min_val))
if val > min_val:
output[k] = {}
logger.debug('Value %s ', str(val))
logger.debug('initializeBidParameters - Quality parameters have been specified')
# The following establishes the price for each bid.
for decisionVariable in (self._service)._decision_variables:
if ((self._service)._decision_variables[decisionVariable].getModeling() == DecisionVariable.MODEL_PRICE):
for k in output:
resourceConsumption = self.calculateUnitaryResourceRequirements(output[k], fileResult)
totalCost = self.calculateUnitaryCost(resourceConsumption, fileResult)
(output[k])[decisionVariable] = totalCost
logger.debug('Ending - initializeBidParameters NumOutput:' + str(len(output)) )
return output
def initializeBids(self, radius, fileResult):
'''
Method to initialize offers. It receives a signal from the
simulation environment (demand server) with its position
in the market. The argument position serves to understand
if the provider at the beginning is oriented towards low
price (0) or high quality (1). Providers innovators
can compite with offers with high quality and low price.
'''
self.registerLog(fileResult,'Starting - initializeBids')
output = self.initializeBidParameters(radius, fileResult)
k = len(output)
staged_bids = self.createInitialBids(k, output, fileResult)
self.registerLog(fileResult,'Ending initializeBids - NumStaged' + str(len(staged_bids)))
return staged_bids
def updateClosestBidForecast(self, currentPeriod, bid, staged_bids, forecast, fileResult):
'''
This method updates the forecast of the bid closest to the given bid.
'''
finalDistance = -1 # infinity
bidIdToIncrease = ''
for bidId in staged_bids:
if (staged_bids[bidId])['Action'] == Bid.ACTIVE:
bidToCompare = (staged_bids[bidId])['Object']
distance = self.distance(bid,bidToCompare, fileResult)
if finalDistance == -1:
finalDistance = distance
bidIdToIncrease = bidId
if (finalDistance >= 0) and (finalDistance > distance):
finalDistance = distance
bidIdToIncrease = bidId
if (finalDistance >= 0):
(staged_bids[bidIdToIncrease])['Forecast'] = (staged_bids[bidIdToIncrease])['Forecast'] + forecast
self.registerLog(fileResult, 'Ending updateClosestBidForecast - Period:' + str(currentPeriod) + ' The closest Bid is:' + bidIdToIncrease + 'Forecast:' + str(forecast) )
'''
Return True if the distance between both bids is less tha radius - tested:OK
'''
def areNeighborhoodBids(self, radius, bid1, bid2, fileResult):
val_return = False
distance = self.distance(bid1,bid2, fileResult)
if distance <= radius:
val_return = True
#self.registerLog(fileResult, 'Ending - areNeighborhoodBids - Radius' + str(radius) + ' distance:' + str(distance))
return val_return
def maintainBids(self, currentPeriod, radius, serviceOwn, staged_bids, fileResult):
self.registerLog(fileResult, 'Starting maintainBids:' + str(len(staged_bids)) )
sortedActiveBids = self.sortByLastMarketShare(currentPeriod, fileResult)
for bidId in sortedActiveBids:
if bidId not in staged_bids:
bid = (self._list_vars['Bids'])[bidId]
newBid = self.copyBid(bid)
bidPrice = self.getBidPrice(newBid)
unitaryBidCost = self.completeNewBidInformation(newBid, bidPrice, fileResult)
if bidPrice >= unitaryBidCost:
if (self.isANonValueAddedBid( radius, newBid, staged_bids, fileResult) == False):
newBid.insertParentBid(bid)
marketZoneDemand, forecast = self.calculateMovedBidForecast(currentPeriod, radius, bid, newBid, Provider.MARKET_SHARE_ORIENTED, fileResult)
staged_bids[newBid.getId()] = {'Object': newBid, 'Action': Bid.ACTIVE, 'MarketShare': marketZoneDemand, 'Forecast': forecast }
else:
# increase the forecast of the closest bid.
self.updateClosestBidForecast(currentPeriod, newBid, staged_bids, forecast, fileResult)
# inactive current bid.
staged_bids[bid.getId()] = {'Object': bid, 'Action': Bid.INACTIVE, 'MarketShare': {}, 'Forecast': 0 }
self.registerLog(fileResult, 'Ending maintainBids:' + str(len(staged_bids)) )
def exec_algorithm(self):
'''
This method checks if the service provider is able to place an
offer in the marketplace, i.e. if the offering period is open.
If this is the case, it will place the offer at the best position
possible.
'''
try:
logger.debug('The state for agent %s is %s',
self._list_vars['strId'], str(self._list_vars['State']))
fileResult = open(self._list_vars['strId'] + '.log',"a")
self.registerLog(fileResult, 'executing algorithm - Period: ' + str(self._list_vars['Current_Period']) )
if (self._list_vars['State'] == AgentServerHandler.BID_PERMITED):
logger.debug('Number of bids: %s for provider: %s', len(self._list_vars['Bids']), self._list_vars['strId'])
currentPeriod = self.getCurrentPeriod()
adaptationFactor = self.getAdaptationFactor()
marketPosition = self.getMarketPosition()
serviceOwn = self._service
radius = foundation.agent_properties.own_neighbor_radius
staged_bids = {}
if (len(self._list_vars['Bids']) == 0):
staged_bids = self.initializeBids(radius, fileResult)
else:
# By assumption providers at this point have the bid usage updated.
self.maintainBids(currentPeriod, radius, serviceOwn, staged_bids, fileResult)
self.eliminateNeighborhoodBid(staged_bids, fileResult)
self.registerLog(fileResult, 'The Final Number of Staged offers is:' + str(len(staged_bids)) )
self.sendBids(staged_bids, fileResult) #Pending the status of the bid.
self.purgeBids(staged_bids, fileResult)
except ProviderException as e:
self.registerLog(fileResult, e.message)
except Exception as e:
self.registerLog(fileResult, e.message)
fileResult.close()
self._list_vars['State'] = AgentServerHandler.IDLE
logger.info('Ending exec_algorithm %s - CurrentPeriod: %s', self._list_vars['strId'], str(self._list_vars['Current_Period']) ) | {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/ProviderPublic.py",
"copies": "1",
"size": "14188",
"license": "mit",
"hash": 1247966551614343400,
"line_mean": 54.6431372549,
"line_max": 302,
"alpha_frac": 0.6098815901,
"autogenerated": false,
"ratio": 4.391210151655834,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5501091741755834,
"avg_score": null,
"num_lines": null
} |
from foundation import forms, rest
from foundation.backend import register
from . import models
class FormViewMixin(object):
""" Add overrides to view code here, or replace the view classes in the
dictionary on the controller. """
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(FormViewMixin, self).formfield_for_dbfield(db_field,
**kwargs)
# if formfield: # concrete inheritance
widget = formfield.widget
# do not apply to templated widgets
# if not isinstance(widget, forms.widgets.WidgetTemplateMixin):
widget.attrs['class'] = ' '.join((
widget.attrs.get('class', ''), 'form-control'
))
return formfield
class APIFormController(forms.FormController):
viewsets = {
None: forms.PageViewSet,
'api': rest.APIViewSet,
'embed': forms.EmbedViewSet,
}
view_mixin_class = FormViewMixin
class PostController(APIFormController):
# view_class_mixin = ViewMixin
model = models.Post
public_modes = ('list', 'display')
fields = ('blog', 'title', 'body')
@register(models.Blog)
class BlogController(APIFormController):
# auth
fk_name = 'owner'
public_modes = ('list', 'display')
fieldsets = {
'public': (
('form', {
'name': None,
'fields': ('owner', 'title'),
'description': 'The purpose of this fieldset.',
# classes
# readonly_fields
# template_name?
}),
('tabs', {
'fields': ('description', 'blog_entries'),
'template_name': 'tabs.html'
}),
),
}
readonly_fields = ('description',)
children = [PostController]
url_model_prefix = ''
| {
"repo_name": "altio/foundation",
"path": "sample/blogs/controllers.py",
"copies": "2",
"size": "1899",
"license": "mit",
"hash": 3521469784592892000,
"line_mean": 25.0136986301,
"line_max": 78,
"alpha_frac": 0.5508162191,
"autogenerated": false,
"ratio": 4.426573426573427,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5977389645673427,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
import objc
import traceback
import urllib
import urllib2
def serviceSelector(fn):
# this is the signature of service selectors
return objc.selector(fn, signature="v@:@@o^@")
def ERROR(s):
#NSLog(u"ERROR: %s", s)
return s
NAME = 'TinyURLService-0.0'
TINYURL_API = 'http://tinyurl.com/api-create.php'
def getTinyURL(url):
data = urllib.urlencode(dict(url=url, source=NAME))
return urllib2.urlopen(TINYURL_API, data).read().decode('utf-8')
class TinyURLService(NSObject):
@serviceSelector
def doTinyURLService_userData_error_(self, pboard, data, error):
# Mail.app in 10.4.1 doesn't do NSURLPboardType correctly!
# Probably elsewhere too, so we just use strings.
try:
#NSLog(u'doTinyURLService: %s', pboard)
types = pboard.types()
url = None
if NSStringPboardType in types:
#NSLog(u'getting NSStringPboardType')
urlString = pboard.stringForType_(NSStringPboardType)
#NSLog(u'NSStringPboardType: %s', urlString)
url = NSURL.URLWithString_(urlString.strip())
if url is None:
#NSLog(u'urlString was %s', urlString)
return ERROR(NSLocalizedString(
"Error: Given URL was not well-formed.",
"Given URL not well-formed."
))
if url is None:
return ERROR(NSLocalizedString(
"Error: Pasteboard doesn't contain a valid URL.",
"Pasteboard doesn't contain a valid URL.",
))
urlString = url.absoluteString()
#NSLog(u'urlString = %s', urlString)
res = getTinyURL(urlString.UTF8String())
#NSLog(u'res = %r' % (res,))
resURL = NSURL.URLWithString_(res)
#NSLog(u'resURL = %s', resURL)
if resURL is None:
NSLog(u'res was %s', res)
return ERROR(NSLocalizedString(
"Error: Resultant URL was not well-formed.",
"Resultant URL not well-formed."
))
pboard.declareTypes_owner_([NSStringPboardType], None)
pboard.setString_forType_(resURL.absoluteString(), NSStringPboardType)
return ERROR(None)
except:
traceback.print_exc()
return ERROR(u'Exception, see traceback')
def main():
serviceProvider = TinyURLService.alloc().init()
NSRegisterServicesProvider(serviceProvider, u'TinyURLService')
AppHelper.runConsoleEventLoop()
if __name__ == '__main__':
main()
| {
"repo_name": "Khan/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/TinyURLService/TinyURLService.py",
"copies": "3",
"size": "2768",
"license": "mit",
"hash": -3679961507973837300,
"line_mean": 32.756097561,
"line_max": 82,
"alpha_frac": 0.5769508671,
"autogenerated": false,
"ratio": 3.8876404494382024,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5964591316538203,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
from PyObjCTools import NibClassBuilder
from FileSettings import *
class PreferencesWindowController(NSWindowController):
commandline = objc.IBOutlet()
debug = objc.IBOutlet()
filetype = objc.IBOutlet()
honourhashbang = objc.IBOutlet()
inspect = objc.IBOutlet()
interpreter = objc.IBOutlet()
nosite = objc.IBOutlet()
optimize = objc.IBOutlet()
others = objc.IBOutlet()
tabs = objc.IBOutlet()
verbose = objc.IBOutlet()
with_terminal = objc.IBOutlet()
_singleton = None
settings = None
def getPreferencesWindow(cls):
if not cls._singleton:
cls._singleton = PreferencesWindowController.alloc().init()
cls._singleton.showWindow_(cls._singleton)
return cls._singleton
getPreferencesWindow = classmethod(getPreferencesWindow)
def init(self):
return self.initWithWindowNibName_(u'PreferenceWindow')
def load_defaults(self):
title = self.filetype.titleOfSelectedItem()
self.settings = FileSettings.getDefaultsForFileType_(title)
def updateDisplay(self):
if self.settings is None:
return
dct = self.settings.fileSettingsAsDict()
self.interpreter.reloadData()
self.interpreter.setStringValue_(dct['interpreter'])
self.honourhashbang.setState_(dct['honourhashbang'])
self.debug.setState_(dct['debug'])
self.verbose.setState_(dct['verbose'])
self.inspect.setState_(dct['inspect'])
self.optimize.setState_(dct['optimize'])
self.nosite.setState_(dct['nosite'])
self.tabs.setState_(dct['tabs'])
self.others.setStringValue_(dct['others'])
self.with_terminal.setState_(dct['with_terminal'])
self.commandline.setStringValue_(self.settings.commandLineForScript_(u'<your script here>'))
def windowDidLoad(self):
super(PreferencesWindowController, self).windowDidLoad()
try:
self.load_defaults()
self.updateDisplay()
except:
import traceback
traceback.print_exc()
import pdb, sys
pdb.post_mortem(sys.exc_info()[2])
def updateSettings(self):
self.settings.updateFromSource_(self)
@objc.IBAction
def doFiletype_(self, sender):
self.load_defaults()
self.updateDisplay()
@objc.IBAction
def doReset_(self, sender):
self.settings.reset()
self.updateDisplay()
@objc.IBAction
def doApply_(self, sender):
self.updateSettings()
self.updateDisplay()
def fileSettingsAsDict(self):
return dict(
interpreter=self.interpreter.stringValue(),
honourhashbang=self.honourhashbang.state(),
debug=self.debug.state(),
verbose=self.verbose.state(),
inspect=self.inspect.state(),
optimize=self.optimize.state(),
nosite=self.nosite.state(),
tabs=self.tabs.state(),
others=self.others.stringValue(),
with_terminal=self.with_terminal.state(),
scriptargs=u'',
)
def controlTextDidChange_(self, aNotification):
self.updateSettings()
self.updateDisplay()
def comboBox_indexOfItemWithStringValue_(self, aComboBox, aString):
if self.settings is None:
return -1
dct = self.settings.fileSettingsAsDict()
return dct['interpreter_list'].indexOfObject_(aString)
def comboBox_objectValueForItemAtIndex_(self, aComboBox, index):
if self.settings is None:
return None
return self.settings.fileSettingsAsDict()['interpreter_list'][index]
def numberOfItemsInComboBox_(self, aComboBox):
if self.settings is None:
return 0
return len(self.settings.fileSettingsAsDict()['interpreter_list'])
| {
"repo_name": "ariabuckles/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/PyObjCLauncher/PreferencesWindowController.py",
"copies": "3",
"size": "3906",
"license": "mit",
"hash": 3888206629548278000,
"line_mean": 32.9652173913,
"line_max": 100,
"alpha_frac": 0.6426011265,
"autogenerated": false,
"ratio": 4.0602910602910605,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.620289218679106,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
from PyObjCTools import NibClassBuilder
import os
from FileSettings import *
from doscript import doscript
class MyDocument(NSDocument):
commandline = objc.IBOutlet()
debug = objc.IBOutlet()
honourhashbang = objc.IBOutlet()
inspect = objc.IBOutlet()
interpreter = objc.IBOutlet()
nosite = objc.IBOutlet()
optimize = objc.IBOutlet()
others = objc.IBOutlet()
scriptargs = objc.IBOutlet()
tabs = objc.IBOutlet()
verbose = objc.IBOutlet()
with_terminal = objc.IBOutlet()
def init(self):
self = super(MyDocument, self).init()
if self is not None:
self.script = u'<no script>.py'
self.filetype = u'Python Script'
self.settings = None
return self
def windowNibName(self):
return u'MyDocument'
def close(self):
super(MyDocument, self).close()
if NSApp().delegate().shouldTerminate():
NSApp().terminate_(self)
def load_defaults(self):
self.settings = FileSettings.newSettingsForFileType_(self.filetype)
def updateDisplay(self):
dct = self.settings.fileSettingsAsDict()
self.interpreter.setStringValue_(dct['interpreter'])
self.honourhashbang.setState_(dct['honourhashbang'])
self.debug.setState_(dct['verbose'])
self.inspect.setState_(dct['inspect'])
self.optimize.setState_(dct['optimize'])
self.nosite.setState_(dct['nosite'])
self.tabs.setState_(dct['tabs'])
self.others.setStringValue_(dct['others'])
self.scriptargs.setStringValue_(dct['scriptargs'])
self.with_terminal.setState_(dct['with_terminal'])
self.commandline.setStringValue_(self.settings.commandLineForScript_(self.script))
def update_settings(self):
self.settings.updateFromSource_(self)
def run(self):
cmdline = self.settings.commandLineForScript_(self.script)
dct = self.settings.fileSettingsAsDict()
if dct['with_terminal']:
res = doscript(cmdline)
else:
res = os.system(cmdline)
if res:
NSLog(u'Exit status: %d', res)
return False
return True
def windowControllerDidLoadNib_(self, aController):
super(MyDocument, self).windowControllerDidLoadNib_(aController)
self.load_defaults()
self.updateDisplay()
def dataRepresentationOfType_(self, aType):
return None
def readFromFile_ofType_(self, filename, typ):
show_ui = NSApp().delegate().shouldShowUI()
self.script = filename
self.filetype = typ
self.settings = FileSettings.newSettingsForFileType_(typ)
if show_ui:
self.updateDisplay()
return True
else:
self.run()
self.close()
return False
@objc.IBAction
def doRun_(self, sender):
self.update_settings()
self.updateDisplay()
if self.run():
self.close()
@objc.IBAction
def doCancel_(self, sender):
self.close()
@objc.IBAction
def doReset_(self, sender):
self.settings.reset()
self.updateDisplay()
@objc.IBAction
def doApply_(self, sender):
self.update_settings()
self.updateDisplay()
def controlTextDidChange_(self, aNotification):
self.update_settings()
self.updateDisplay()
def fileSettingsAsDict(self):
return dict(
interpreter=self.interpreter.stringValue(),
honourhashbang=self.honourhashbang.state(),
debug=self.debug.state(),
verbose=self.verbose.state(),
inspect=self.inspect.state(),
optimize=self.optimize.state(),
nosite=self.nosite.state(),
tabs=self.tabs.state(),
others=self.others.stringValue(),
with_terminal=self.with_terminal.state(),
scriptargs=self.scriptargs.stringValue(),
)
| {
"repo_name": "ariabuckles/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/PyObjCLauncher/MyDocument.py",
"copies": "3",
"size": "4031",
"license": "mit",
"hash": -8228932568028853000,
"line_mean": 30.2480620155,
"line_max": 90,
"alpha_frac": 0.6172165716,
"autogenerated": false,
"ratio": 3.9636184857423795,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.608083505734238,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
from robofab.pens.pointPen import AbstractPointPen
import vanilla
from defconAppKit.controls.placardScrollView import PlacardScrollView, PlacardPopUpButton
backgroundColor = NSColor.whiteColor()
metricsColor = NSColor.colorWithCalibratedWhite_alpha_(.4, .5)
metricsTitlesColor = NSColor.colorWithCalibratedWhite_alpha_(.1, .5)
marginColor = NSColor.colorWithCalibratedWhite_alpha_(.5, .11)
fillColor = NSColor.colorWithCalibratedWhite_alpha_(0, .4)
strokeColor = NSColor.colorWithCalibratedWhite_alpha_(0, 1)
fillAndStrokFillColor = NSColor.blackColor()
componentFillColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.2, .2, .3, .4)
componentStrokeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.2, .2, .3, .7)
pointColor = NSColor.colorWithCalibratedWhite_alpha_(.6, 1)
pointStrokeColor = NSColor.colorWithCalibratedWhite_alpha_(1, 1)
startPointColor = NSColor.colorWithCalibratedWhite_alpha_(0, .2)
bezierHandleColor = NSColor.colorWithCalibratedWhite_alpha_(0, .2)
pointCoordinateColor = NSColor.colorWithCalibratedWhite_alpha_(.5, .75)
anchorColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(1, .2, 0, 1)
bluesColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(.5, .7, 1, .3)
familyBluesColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(1, 1, .5, .3)
class DefconAppKitGlyphNSView(NSView):
def init(self):
self = super(DefconAppKitGlyphNSView, self).init()
self._glyph = None
self._unitsPerEm = 1000
self._descender = -250
self._xHeight = 500
self._capHeight = 750
self._ascender = 750
self._showFill = True
self._showStroke = True
self._showMetrics = True
self._showMetricsTitles = True
self._showOnCurvePoints = True
self._showOffCurvePoints = False
self._showPointCoordinates = False
self._showAnchors = True
self._showBlues = False
self._showFamilyBlues = False
self._pointSize = None
self._centerVertically = True
self._centerHorizontally = True
self._noPointSizePadding = 200
self._xCanvasAddition = 250
self._yCanvasAddition = 250
self._verticalCenterYBuffer = 0
self._scale = 1.0
self._inverseScale = 0.1
self._impliedPointSize = 1000
self._backgroundColor = backgroundColor
self._metricsColor = metricsColor
self._metricsTitlesColor = metricsTitlesColor
self._marginColor = marginColor
self._fillColor = fillColor
self._strokeColor = strokeColor
self._fillAndStrokFillColor = fillAndStrokFillColor
self._componentFillColor = componentFillColor
self._componentStrokeColor = componentStrokeColor
self._pointColor = pointColor
self._pointStrokeColor = pointStrokeColor
self._startPointColor = startPointColor
self._bezierHandleColor = bezierHandleColor
self._pointCoordinateColor = pointCoordinateColor
self._anchorColor = anchorColor
self._bluesColor = bluesColor
self._familyBluesColor = familyBluesColor
self._fitToFrame = None
return self
# --------------
# Custom Methods
# --------------
def recalculateFrame(self):
self._calcScale()
self._setFrame()
self.setNeedsDisplay_(True)
def _getGlyphWidthHeight(self):
if self._glyph.bounds:
left, bottom, right, top = self._glyph.bounds
else:
left = right = bottom = top = 0
left = min((0, left))
right = max((right, self._glyph.width))
bottom = self._descender
top = max((self._capHeight, self._ascender, self._unitsPerEm + self._descender))
width = abs(left) + right
height = -bottom + top
return width, height
def _calcScale(self):
if self.superview() is None:
return
if self._pointSize is None:
visibleHeight = self.superview().visibleRect().size[1]
fitHeight = visibleHeight
glyphWidth, glyphHeight = self._getGlyphWidthHeight()
glyphHeight += self._noPointSizePadding * 2
self._scale = fitHeight / glyphHeight
else:
self._scale = self._pointSize / float(self._unitsPerEm)
if self._scale <= 0:
self._scale = .01
self._inverseScale = 1.0 / self._scale
self._impliedPointSize = self._unitsPerEm * self._scale
def _setFrame(self):
if not self.superview():
return
scrollWidth, scrollHeight = self.superview().visibleRect().size
# pick the width and height
glyphWidth, glyphHeight = self._getGlyphWidthHeight()
if self._pointSize is not None:
glyphWidth += self._xCanvasAddition * 2
glyphHeight += self._yCanvasAddition * 2
glyphWidth = glyphWidth * self._scale
glyphHeight = glyphHeight * self._scale
width = glyphWidth
height = glyphHeight
if scrollWidth > width:
width = scrollWidth
if scrollHeight > height:
height = scrollHeight
# set the frame
self.setFrame_(((0, 0), (width, height)))
self._fitToFrame = self.superview().visibleRect().size
# calculate and store the vetical centering offset
self._verticalCenterYBuffer = (height - glyphHeight) / 2.0
def setGlyph_(self, glyph):
self._glyph = glyph
self._font = None
if glyph is not None:
font = self._font = glyph.getParent()
if font is not None:
self._unitsPerEm = font.info.unitsPerEm
self._descender = font.info.descender
self._xHeight = font.info.xHeight
self._ascender = font.info.ascender
self._capHeight = font.info.capHeight
self.recalculateFrame()
self.setNeedsDisplay_(True)
def getGlyph(self):
return self._glyph
# --------------------
# Notification Support
# --------------------
def glyphChanged(self):
self.setNeedsDisplay_(True)
def fontChanged(self):
self.setGlyph_(self._glyph)
# ---------------
# Display Control
# ---------------
# def setPointSize_(self, value):
# self._pointSize = value
# self.setNeedsDisplay_(True)
#
# def getPointSize(self):
# return self._pointSize
def setShowFill_(self, value):
self._showFill = value
self.setNeedsDisplay_(True)
def getShowFill(self):
return self._showFill
def setShowStroke_(self, value):
self._showStroke = value
self.setNeedsDisplay_(True)
def getShowStroke(self):
return self._showStroke
def setShowMetrics_(self, value):
self._showMetrics = value
self.setNeedsDisplay_(True)
def getShowMetrics(self):
return self._showMetrics
def setShowMetricsTitles_(self, value):
self._showMetricsTitles = value
self.setNeedsDisplay_(True)
def getShowMetricsTitles(self):
return self._showMetricsTitles
def setShowOnCurvePoints_(self, value):
self._showOnCurvePoints = value
self.setNeedsDisplay_(True)
def getShowOnCurvePoints(self):
return self._showOnCurvePoints
def setShowOffCurvePoints_(self, value):
self._showOffCurvePoints = value
self.setNeedsDisplay_(True)
def getShowOffCurvePoints(self):
return self._showOffCurvePoints
def setShowPointCoordinates_(self, value):
self._showPointCoordinates = value
self.setNeedsDisplay_(True)
def getShowPointCoordinates(self):
return self._showPointCoordinates
def setShowAnchors_(self, value):
self._showAnchors = value
self.setNeedsDisplay_(True)
def getShowAnchors(self):
return self._showAnchors
def setShowBlues_(self, value):
self._showBlues = value
self.setNeedsDisplay_(True)
def getShowBlues(self):
return self._showBlues
def setShowFamilyBlues_(self, value):
self._showFamilyBlues = value
self.setNeedsDisplay_(True)
def getShowFamilyBlues(self):
return self._showFamilyBlues
# --------------
# NSView Methods
# --------------
def isOpaque(self):
return True
def drawRect_(self, rect):
needCalc = False
if self.superview() and self._fitToFrame != self.superview().visibleRect().size:
needCalc = True
if self.inLiveResize() and self._pointSize is None:
needCalc = True
if needCalc:
self.recalculateFrame()
self.drawBackground()
if self._glyph is None:
return
# apply vertical offset
transform = NSAffineTransform.transform()
if self._centerVertically:
yOffset = self._verticalCenterYBuffer
else:
canvasHeight = self._getGlyphWidthHeight()[1] + (self._yCanvasAddition * 2)
canvasHeight = canvasHeight * self._scale
frameHeight = self.frame().size[1]
yOffset = frameHeight - canvasHeight + (self._yCanvasAddition * self._scale)
transform.translateXBy_yBy_(0, yOffset)
transform.concat()
# apply the overall scale
transform = NSAffineTransform.transform()
transform.scaleBy_(self._scale)
transform.concat()
yOffset = yOffset * self._inverseScale
# shift to baseline
transform = NSAffineTransform.transform()
transform.translateXBy_yBy_(0, -self._descender)
transform.concat()
yOffset = yOffset - self._descender
# draw the blues
if self._showBlues:
self.drawBlues()
if self._showFamilyBlues:
self.drawFamilyBlues()
# draw the margins
if self._centerHorizontally:
visibleWidth = self.bounds().size[0]
width = self._glyph.width * self._scale
diff = visibleWidth - width
xOffset = round((diff / 2) * self._inverseScale)
else:
xOffset = self._xCanvasAddition
if self._showMetrics:
self.drawMargins(xOffset, yOffset)
# draw the horizontal metrics
if self._showMetrics:
self.drawHorizontalMetrics()
# apply horizontal offset
transform = NSAffineTransform.transform()
transform.translateXBy_yBy_(xOffset, 0)
transform.concat()
# draw the glyph
if self._showFill:
self.drawFill()
if self._showStroke:
self.drawStroke()
self.drawPoints()
if self._showAnchors:
self.drawAnchors()
def roundPosition(self, value):
value = value * self._scale
value = round(value) - .5
value = value * self._inverseScale
return value
def drawBackground(self):
self._backgroundColor.set()
NSRectFill(self.bounds())
def drawBlues(self):
width = self.bounds().size[0] * self._inverseScale
self._bluesColor.set()
font = self._glyph.getParent()
if font is None:
return
attrs = ["postscriptBlueValues", "postscriptOtherBlues"]
for attr in attrs:
values = getattr(font.info, attr)
if not values:
continue
yMins = [i for index, i in enumerate(values) if not index % 2]
yMaxs = [i for index, i in enumerate(values) if index % 2]
for yMin, yMax in zip(yMins, yMaxs):
NSRectFillUsingOperation(((0, yMin), (width, yMax - yMin)), NSCompositeSourceOver)
def drawFamilyBlues(self):
width = self.bounds().size[0] * self._inverseScale
self._familyBluesColor.set()
font = self._glyph.getParent()
if font is None:
return
attrs = ["postscriptFamilyBlues", "postscriptFamilyOtherBlues"]
for attr in attrs:
values = getattr(font.info, attr)
if not values:
continue
yMins = [i for index, i in enumerate(values) if not index % 2]
yMaxs = [i for index, i in enumerate(values) if index % 2]
for yMin, yMax in zip(yMins, yMaxs):
NSRectFillUsingOperation(((0, yMin), (width, yMax - yMin)), NSCompositeSourceOver)
def drawHorizontalMetrics(self):
toDraw = [
("Descender", self._descender),
("Baseline", 0),
("X Height", self._xHeight),
("Cap Height", self._capHeight),
("Ascender", self._ascender)
]
positions = {}
for name, position in toDraw:
if position not in positions:
positions[position] = []
positions[position].append(name)
# lines
path = NSBezierPath.bezierPath()
x1 = 0
x2 = self.bounds().size[0] * self._inverseScale
for position, names in sorted(positions.items()):
y = self.roundPosition(position)
path.moveToPoint_((x1, y))
path.lineToPoint_((x2, y))
path.setLineWidth_(1.0 * self._inverseScale)
self._metricsColor.set()
path.stroke()
# text
if self._showMetricsTitles and self._impliedPointSize > 150:
fontSize = 9 * self._inverseScale
shadow = NSShadow.shadow()
shadow.setShadowColor_(self._backgroundColor)
shadow.setShadowBlurRadius_(5)
shadow.setShadowOffset_((0, 0))
attributes = {
NSFontAttributeName : NSFont.systemFontOfSize_(fontSize),
NSForegroundColorAttributeName : self._metricsTitlesColor
}
glowAttributes = {
NSFontAttributeName : NSFont.systemFontOfSize_(fontSize),
NSForegroundColorAttributeName : self._metricsColor,
NSStrokeColorAttributeName : self._backgroundColor,
NSStrokeWidthAttributeName : 25,
NSShadowAttributeName : shadow
}
for position, names in sorted(positions.items()):
y = position - (fontSize / 2)
text = ", ".join(names)
text = " %s " % text
t = NSAttributedString.alloc().initWithString_attributes_(text, glowAttributes)
t.drawAtPoint_((0, y))
t = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
t.drawAtPoint_((0, y))
def drawMargins(self, xOffset, yOffset):
x1 = 0
w1 = xOffset
x2 = self._glyph.width + xOffset
w2 = (self.bounds().size[0] * self._inverseScale) - x2
h = self.bounds().size[1] * self._inverseScale
rects = [
((x1, -yOffset), (w1, h)),
((x2, -yOffset), (w2, h))
]
self._marginColor.set()
for rect in rects:
NSRectFillUsingOperation(rect, NSCompositeSourceOver)
def drawFill(self):
# outlines
path = self._glyph.getRepresentation("defconAppKit.NoComponentsNSBezierPath")
if self._showStroke:
self._fillColor.set()
else:
self._fillAndStrokFillColor.set()
path.fill()
# components
path = self._glyph.getRepresentation("defconAppKit.OnlyComponentsNSBezierPath")
self._componentFillColor.set()
path.fill()
def drawStroke(self):
# outlines
path = self._glyph.getRepresentation("defconAppKit.NoComponentsNSBezierPath")
self._strokeColor.set()
path.setLineWidth_(1.0 * self._inverseScale)
path.stroke()
# components
path = self._glyph.getRepresentation("defconAppKit.OnlyComponentsNSBezierPath")
self._componentStrokeColor.set()
path.setLineWidth_(1.0 * self._inverseScale)
path.stroke()
def drawPoints(self):
# work out appropriate sizes and
# skip if the glyph is too small
pointSize = self._impliedPointSize
if pointSize > 550:
startPointSize = 21
offCurvePointSize = 5
onCurvePointSize = 6
onCurveSmoothPointSize = 7
elif pointSize > 250:
startPointSize = 15
offCurvePointSize = 3
onCurvePointSize = 4
onCurveSmoothPointSize = 5
elif pointSize > 175:
startPointSize = 9
offCurvePointSize = 1
onCurvePointSize = 2
onCurveSmoothPointSize = 3
else:
return
if pointSize > 250:
coordinateSize = 9
else:
coordinateSize = 0
# use the data from the outline representation
outlineData = self._glyph.getRepresentation("defconAppKit.OutlineInformation")
points = []
# start point
if self._showOnCurvePoints and outlineData["startPoints"]:
startWidth = startHeight = self.roundPosition(startPointSize * self._inverseScale)
startHalf = startWidth / 2.0
path = NSBezierPath.bezierPath()
for point, angle in outlineData["startPoints"]:
x, y = point
if angle is not None:
path.moveToPoint_((x, y))
path.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle_clockwise_(
(x, y), startHalf, angle-90, angle+90, True)
path.closePath()
else:
path.appendBezierPathWithOvalInRect_(((x-startHalf, y-startHalf), (startWidth, startHeight)))
self._startPointColor.set()
path.fill()
# off curve
if self._showOffCurvePoints and outlineData["offCurvePoints"]:
# lines
path = NSBezierPath.bezierPath()
for point1, point2 in outlineData["bezierHandles"]:
path.moveToPoint_(point1)
path.lineToPoint_(point2)
self._bezierHandleColor.set()
path.setLineWidth_(1.0 * self._inverseScale)
path.stroke()
# points
offWidth = offHeight = self.roundPosition(offCurvePointSize * self._inverseScale)
offHalf = offWidth / 2.0
path = NSBezierPath.bezierPath()
for point in outlineData["offCurvePoints"]:
x, y = point["point"]
points.append((x, y))
x = self.roundPosition(x - offHalf)
y = self.roundPosition(y - offHalf)
path.appendBezierPathWithOvalInRect_(((x, y), (offWidth, offHeight)))
path.setLineWidth_(3.0 * self._inverseScale)
self._pointStrokeColor.set()
path.stroke()
self._backgroundColor.set()
path.fill()
self._pointColor.set()
path.setLineWidth_(1.0 * self._inverseScale)
path.stroke()
# on curve
if self._showOnCurvePoints and outlineData["onCurvePoints"]:
width = height = self.roundPosition(onCurvePointSize * self._inverseScale)
half = width / 2.0
smoothWidth = smoothHeight = self.roundPosition(onCurveSmoothPointSize * self._inverseScale)
smoothHalf = smoothWidth / 2.0
path = NSBezierPath.bezierPath()
for point in outlineData["onCurvePoints"]:
x, y = point["point"]
points.append((x, y))
if point["smooth"]:
x = self.roundPosition(x - smoothHalf)
y = self.roundPosition(y - smoothHalf)
path.appendBezierPathWithOvalInRect_(((x, y), (smoothWidth, smoothHeight)))
else:
x = self.roundPosition(x - half)
y = self.roundPosition(y - half)
path.appendBezierPathWithRect_(((x, y), (width, height)))
self._pointStrokeColor.set()
path.setLineWidth_(3.0 * self._inverseScale)
path.stroke()
self._pointColor.set()
path.fill()
# text
if self._showPointCoordinates and coordinateSize:
fontSize = 9 * self._inverseScale
attributes = {
NSFontAttributeName : NSFont.systemFontOfSize_(fontSize),
NSForegroundColorAttributeName : self._pointCoordinateColor
}
for x, y in points:
posX = x
posY = y
x = round(x, 1)
if int(x) == x:
x = int(x)
y = round(y, 1)
if int(y) == y:
y = int(y)
text = "%d %d" % (x, y)
self._drawTextAtPoint(text, attributes, (posX, posY), 3)
def drawAnchors(self):
pointSize = self._impliedPointSize
anchorSize = 5
fontSize = 9
if pointSize > 500:
pass
elif pointSize > 250:
fontSize = 7
elif pointSize > 50:
anchorSize = 3
fontSize = 7
else:
return
anchorSize = self.roundPosition(anchorSize * self._inverseScale)
anchorHalf = anchorSize * .5
fontSize = fontSize * self._inverseScale
font = NSFont.boldSystemFontOfSize_(fontSize)
attributes = {
NSFontAttributeName : font,
NSForegroundColorAttributeName : self._anchorColor
}
path = NSBezierPath.bezierPath()
for anchor in self._glyph.anchors:
x, y = anchor.x, anchor.y
name = anchor.name
path.appendBezierPathWithOvalInRect_(((x - anchorHalf, y - anchorHalf), (anchorSize, anchorSize)))
if pointSize > 100 and name:
self._drawTextAtPoint(name, attributes, (x, y - 2), fontSize * self._scale * .85, drawBackground=True)
self._pointStrokeColor.set()
path.setLineWidth_(3.0 * self._inverseScale)
path.stroke()
self._anchorColor.set()
path.fill()
def _drawTextAtPoint(self, text, attributes, (posX, posY), yOffset, drawBackground=False):
text = NSAttributedString.alloc().initWithString_attributes_(text, attributes)
width, height = text.size()
fontSize = attributes[NSFontAttributeName].pointSize()
posX -= width / 2
posY -= fontSize + (yOffset * self._inverseScale)
posX = self.roundPosition(posX)
posY = self.roundPosition(posY)
if drawBackground:
shadow = NSShadow.alloc().init()
shadow.setShadowColor_(self._backgroundColor)
shadow.setShadowOffset_((0, 0))
shadow.setShadowBlurRadius_(3)
width += 4 * self._inverseScale
height += 2 * self._inverseScale
x = posX - (2 * self._inverseScale)
y = posY - (1 * self._inverseScale)
context = NSGraphicsContext.currentContext()
context.saveGraphicsState()
shadow.set()
self._backgroundColor.set()
NSRectFill(((x, y), (width, height)))
context.restoreGraphicsState()
text.drawAtPoint_((posX, posY))
class GlyphView(PlacardScrollView):
glyphViewClass = DefconAppKitGlyphNSView
def __init__(self, posSize):
self._glyphView = self.glyphViewClass.alloc().init()
super(GlyphView, self).__init__(posSize, self._glyphView, autohidesScrollers=False)
self.buildPlacard()
self.setPlacard(self.placard)
def buildPlacard(self):
placardW = 65
placardH = 16
self.placard = vanilla.Group((0, 0, placardW, placardH))
self.placard.optionsButton = PlacardPopUpButton((0, 0, placardW, placardH),
[], callback=self._placardDisplayOptionsCallback, sizeStyle="mini")
self._populatePlacard()
#button.menu().setAutoenablesItems_(False)
def _populatePlacard(self):
options = [
"Fill",
"Stroke",
"Metrics",
"On Curve Points",
"Off Curve Points",
"Point Coordinates",
"Anchors",
"Blues",
"Family Blues"
]
# make a default item
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Display...", None, "")
## 10.5+
try:
item.setHidden_(True)
## ugh. in <= 10.4, make the item disabled
except AttributeError:
item.setEnabled_(False)
item.setState_(False)
items = [item]
for attr in options:
method = "getShow" + attr.replace(" ", "")
state = getattr(self._glyphView, method)()
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(attr, None, "")
item.setState_(state)
items.append(item)
## set the items
self.placard.optionsButton.setItems(items)
button = self.placard.optionsButton.getNSPopUpButton()
button.setTitle_("Display...")
def _breakCycles(self):
self._unsubscribeFromGlyph()
self._glyphView = None
super(GlyphView, self)._breakCycles()
def _placardDisplayOptionsCallback(self, sender):
index = sender.get()
attr = sender.getItems()[index]
method = "getShow" + attr.replace(" ", "")
state = getattr(self._glyphView, method)()
method = "setShow" + attr.replace(" ", "") + "_"
getattr(self._glyphView, method)(not state)
self._populatePlacard()
# -------------
# Notifications
# -------------
def _subscribeToGlyph(self, glyph):
if glyph is not None:
glyph.addObserver(self, "_glyphChanged", "Glyph.Changed")
font = glyph.getParent()
if font is not None:
font.info.addObserver(self, "_fontChanged", "Info.Changed")
def _unsubscribeFromGlyph(self):
if self._glyphView is not None:
glyph = self._glyphView.getGlyph()
if glyph is not None:
glyph.removeObserver(self, "Glyph.Changed")
font = glyph.getParent()
if font is not None:
font.info.removeObserver(self, "Info.Changed")
def _glyphChanged(self, notification):
self._glyphView.glyphChanged()
def _fontChanged(self, notification):
self._glyphView.fontChanged()
# --------------
# Public Methods
# --------------
def set(self, glyph):
self._unsubscribeFromGlyph()
self._subscribeToGlyph(glyph)
self._glyphView.setGlyph_(glyph)
def setShowFill(self, value):
self._populatePlacard()
self._glyphView.setShowFill_(value)
def getShowFill(self):
return self._glyphView.getShowFill()
def setShowStroke(self, value):
self._populatePlacard()
self._glyphView.setShowStroke_(value)
def getShowStroke(self):
return self._glyphView.getShowStroke()
def setShowMetrics(self, value):
self._populatePlacard()
self._glyphView.setShowMetrics_(value)
def getShowMetrics(self):
return self._glyphView.getShowMetrics()
def setShowMetricsTitles(self, value):
self._populatePlacard()
self._glyphView.setShowMetricsTitles_(value)
def getShowMetricsTitles(self):
return self._glyphView.getShowMetricsTitles()
def setShowOnCurvePoints(self, value):
self._populatePlacard()
self._glyphView.setShowOnCurvePoints_(value)
def getShowOnCurvePoints(self):
return self._glyphView.getShowOnCurvePoints()
def setShowOffCurvePoints(self, value):
self._populatePlacard()
self._glyphView.setShowOffCurvePoints_(value)
def getShowOffCurvePoints(self):
return self._glyphView.getShowOffCurvePoints()
def setShowPointCoordinates(self, value):
self._populatePlacard()
self._glyphView.setShowPointCoordinates_(value)
def getShowPointCoordinates(self):
return self._glyphView.getShowPointCoordinates()
def setShowAnchors(self, value):
self._populatePlacard()
self._glyphView.setShowAnchors_(value)
def getShowAnchors(self):
return self._glyphView.getShowAnchors()
def setShowBlues(self, value):
self._populatePlacard()
self._glyphView.setShowBlues_(value)
def getShowBlues(self):
return self._glyphView.getShowBlues()
def setShowFamilyBlues(self, value):
self._populatePlacard()
self._glyphView.setShowFamilyBlues_(value)
def getShowFamilyBlues(self):
return self._glyphView.getShowFamilyBlues()
| {
"repo_name": "Ye-Yong-Chi/defconAppKit",
"path": "Lib/defconAppKit/controls/glyphView.py",
"copies": "1",
"size": "28882",
"license": "mit",
"hash": -2526875953974061000,
"line_mean": 35.1929824561,
"line_max": 118,
"alpha_frac": 0.5920296378,
"autogenerated": false,
"ratio": 4.0581705774905155,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0008609052395909687,
"num_lines": 798
} |
from Foundation import *
from AppKit import *
from session import Session
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, app):
self.session = None
self.init_status_bar()
self.init_menu()
def init_status_bar(self):
self.status_bar = NSStatusBar.systemStatusBar()
self.status_item = self.status_bar.statusItemWithLength_(NSVariableStatusItemLength)
self.status_item.setHighlightMode_(1)
icon = NSImage.alloc().initWithContentsOfFile_('icon.png')
self.status_item.setImage_(icon)
def init_menu(self):
self.menu = NSMenu.alloc().init()
self.menu_item_start = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Start', 'start:', '')
self.menu.addItem_(self.menu_item_start)
menu_item_quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
self.menu.addItem_(menu_item_quit)
self.status_item.setMenu_(self.menu)
def start_(self, notification):
if self.session != None:
self.session.stop()
self.session = Session()
self.session.start()
| {
"repo_name": "pilu/bloody-mary",
"path": "app_delegate.py",
"copies": "1",
"size": "1078",
"license": "mit",
"hash": 4475198752251831000,
"line_mean": 32.6875,
"line_max": 104,
"alpha_frac": 0.7077922078,
"autogenerated": false,
"ratio": 3.422222222222222,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9432237603567069,
"avg_score": 0.039555365291030556,
"num_lines": 32
} |
from Foundation import *
from AppKit import *
from vanillaBase import VanillaBaseControl
_modeMap = {
"graphical": NSClockAndCalendarDatePickerStyle,
"text": 2, #NSTextFieldDatePickerStyle raises an error
"textStepper": NSTextFieldAndStepperDatePickerStyle,
}
_timeDisplayFlagMap = {
None : 0,
"hourMinute" : NSHourMinuteDatePickerElementFlag,
"hourMinuteSecond" : NSHourMinuteSecondDatePickerElementFlag,
}
_dateDisplayFlagMap = {
None : 0,
"yearMonth" : NSYearMonthDatePickerElementFlag,
"yearMonthDay" : NSYearMonthDayDatePickerElementFlag,
}
class DatePicker(VanillaBaseControl):
"""
**posSize** Tuple of form *(left, top, width, height)* representing the position and size of the date picker control.
+-------------------------------------+
| **Standard Dimensions - Text Mode** |
+---------+---+-----------------------+
| Regular | H | 22 |
+---------+---+-----------------------+
| Small | H | 19 |
+---------+---+-----------------------+
| Mini | H | 16 |
+---------+---+-----------------------+
+------------------------------------------+
| **Standard Dimensions - Graphical Mode** |
+--------------------+---------------------+
| Calendar and Clock | 227w 148h |
+--------------------+---------------------+
| Calendar | 139w 148h |
+--------------------+---------------------+
| Clock | 122w 123h |
+--------------------+---------------------+
**date** A *NSDate* object representing the date and time that should be set in the control.
**minDate** A *NSDate* object representing the lowest date and time that can be set in the control.
**maxDate** A *NSDate* object representing the highest date and time that can be set in the control.
**showStepper** A boolean indicating if the thumb stepper should be shown in text mode.
**mode** A string representing the desired mode for the date picker control. The options are:
+-------------+
| "text" |
+-------------+
| "graphical" |
+-------------+
**timeDisplay** A string representing the desired time units that should be displayed in the
date picker control. The options are:
+--------------------+-------------------------------+
| None | Do not display time. |
+--------------------+-------------------------------+
| "hourMinute" | Display hour and minute. |
+--------------------+-------------------------------+
| "hourMinuteSecond" | Display hour, minute, second. |
+--------------------+-------------------------------+
**dateDisplay** A string representing the desired date units that should be displayed in the
date picker control. The options are:
+----------------+------------------------------+
| None | Do not display date. |
+----------------+------------------------------+
| "yearMonth" | Display year and month. |
+----------------+------------------------------+
| "yearMonthDay" | Display year, month and day. |
+----------------+------------------------------+
**sizeStyle** A string representing the desired size style of the date picker control. This only
applies in text mode. The options are:
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
| "mini" |
+-----------+
"""
nsDatePickerClass = NSDatePicker
def __init__(self, posSize, date=None, minDate=None, maxDate=None, showStepper=True, mode="text",
timeDisplay="hourMinuteSecond", dateDisplay="yearMonthDay", callback=None, sizeStyle="regular"):
self._setupView(self.nsDatePickerClass, posSize, callback=callback)
self._setSizeStyle(sizeStyle)
self._nsObject.setDrawsBackground_(True)
self._nsObject.setBezeled_(True)
if mode == "text" and showStepper:
mode += "Stepper"
style = _modeMap[mode]
self._nsObject.setDatePickerStyle_(style)
flag = _timeDisplayFlagMap[timeDisplay]
flag = flag | _dateDisplayFlagMap[dateDisplay]
self._nsObject.setDatePickerElements_(flag)
if date is None:
date = NSDate.date()
self._nsObject.setDateValue_(date)
if minDate is not None:
self._nsObject.setMinDate_(minDate)
if maxDate is not None:
self._nsObject.setMaxDate_(maxDate)
def getNSDatePicker(self):
"""
Return the *NSDatePicker* that this object wraps.
"""
return self._nsObject
def get(self):
"""
Get the contents of the date picker control.
"""
return self._nsObject.dateValue()
def set(self, value):
"""
Set the contents of the date picker control.
**value** A *NSDate* object.
"""
self._nsObject.setDateValue_(value)
| {
"repo_name": "bitforks/vanilla",
"path": "Lib/vanilla/vanillaDatePicker.py",
"copies": "3",
"size": "5039",
"license": "mit",
"hash": -8048295713131612000,
"line_mean": 34.9928571429,
"line_max": 121,
"alpha_frac": 0.4955348283,
"autogenerated": false,
"ratio": 4.467198581560283,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6462733409860284,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
import applesms
from third.vector import vector
class BouncingBrush(NSObject):
'''
A screensaver which demonstrates Apple's Sudden Motion Sensor (SMS), based on an Io demo program
'''
def initWithFrame_(self, frame):
self = super(BouncingBrush, self).init()
(x,y),(width,height) = frame
self.position = vector(25,0, 0)
self.velocity = vector(2, 2, 0)
self.acceleration = vector(0, 0, 0)
self.radius = 32
self.brush_size = [self.radius * 2] * 2
self.elasticity = .66
self.friction = .995
self.setBounds((width, height))
self.initBrush()
return self
def initBrush(self):
self.brush = NSImage.alloc().initWithSize_(self.brush_size)
self.brush.lockFocus()
circle = NSBezierPath.alloc().init()
circle.appendBezierPathWithOvalInRect_(((0,0), self.brush_size))
NSColor.whiteColor().set()
circle.fill()
self.brush.unlockFocus()
def setBounds(self, bounds):
self.bounds = bounds
self.minPosition = vector(0,0,0)
self.maxPosition = vector(bounds[0] - self.radius, bounds[1] - self.radius, 0)
def move(self):
self.acceleration = vector(applesms.coords())
self.acceleration *= -.002
self.velocity += self.acceleration
self.velocity *= self.friction
self.position += self.velocity
self.position[2] = 0
if self.position[0] < self.minPosition[0]:
self.position[0] = self.minPosition[0]
self.velocity[0] *= -self.elasticity
elif self.position[0] > self.maxPosition[0]:
self.position[0] = self.maxPosition[0]
self.velocity[0] *= -self.elasticity
if self.position[1] < self.minPosition[1]:
self.position[1] = self.minPosition[1]
self.velocity[1] *= -self.elasticity
elif self.position[1] > self.maxPosition[1]:
self.position[1] = self.maxPosition[1]
self.velocity[1] *= -self.elasticity
def draw(self):
self.brush.dissolveToPoint_fraction_(self.position[:2], 0.05);
def action(self):
self.move()
self.draw()
| {
"repo_name": "dethe/pastels",
"path": "brush3.py",
"copies": "1",
"size": "2301",
"license": "mit",
"hash": -8459068553997062000,
"line_mean": 33.3432835821,
"line_max": 100,
"alpha_frac": 0.5906127771,
"autogenerated": false,
"ratio": 3.6236220472440945,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.47142348243440946,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
import objc
class DashboardController (NSViewController):
def show(self):
self.window = NSWindow.alloc().init()
self.DashboardViewController = NSViewController.alloc().initWithNibName_bundle_("Dashboard", None)
self.dashboardView = self.DashboardViewController.view()
show = classmethod(show)
def resetSubviews(self):
for i in range(1, len(self.dashboardView.subviews())):
self.dashboardView.subviews().removeObjectAtIndex_(i)
@objc.IBAction
def audio_(self, sender):
self.resetSubviews()
self.AudioViewController = NSViewController.alloc().initWithNibName_bundle_("Audio", None)
self.audioView = self.AudioViewController.view()
self.dashboardView.addSubview_(self.audioView)
@objc.IBAction
def chat_(self, sender):
self.resetSubviews()
self.ChatViewController = NSViewController.alloc().initWithNibName_bundle_("Chat", None)
self.chatView = self.ChatViewController.view()
self.dashboardView.addSubview_(self.chatView)
@objc.IBAction
def link_(self, sender):
self.resetSubviews()
self.LinkViewController = NSViewController.alloc().initWithNibName_bundle_("Link", None)
self.linkView = self.LinkViewController.view()
self.dashboardView.addSubview_(self.linkView)
@objc.IBAction
def logout_(self, sender):
NSApp().terminate_(self)
@objc.IBAction
def photo_(self, sender):
self.resetSubviews()
self.PhotoViewController = NSViewController.alloc().initWithNibName_bundle_("Photo", None)
self.photoView = self.PhotoViewController.view()
self.dashboardView.addSubview_(self.photoView)
@objc.IBAction
def quote_(self, sender):
self.resetSubviews()
self.QuoteViewController = NSViewController.alloc().initWithNibName_bundle_("Quote", None)
self.quoteView = self.QuoteViewController.view()
self.dashboardView.addSubview_(self.quoteView)
@objc.IBAction
def text_(self, sender):
self.resetSubviews()
self.TextViewController = NSViewController.alloc().initWithNibName_bundle_("Text", None)
self.textView = self.TextViewController.view()
self.dashboardView.addSubview_(self.textView)
@objc.IBAction
def video_(self, sender):
self.resetSubviews()
self.VideoViewController = NSViewController.alloc().initWithNibName_bundle_("Video", None)
self.videoView = self.VideoViewController.view()
self.dashboardView.addSubview_(self.videoView) | {
"repo_name": "jyr/opentumblr-cocoa",
"path": "DashboardController.py",
"copies": "1",
"size": "2441",
"license": "mit",
"hash": -8315299575468666000,
"line_mean": 34.9117647059,
"line_max": 100,
"alpha_frac": 0.7439573945,
"autogenerated": false,
"ratio": 3.3855755894590844,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9071333888609925,
"avg_score": 0.11163981906983195,
"num_lines": 68
} |
from Foundation import *
from AppKit import *
import objc
import urllib2
import tumblr
from tumblr import Api
from DashboardController import *
class LoginController(NSWindowController):
blog = objc.IBOutlet()
password = objc.IBOutlet()
user = objc.IBOutlet()
def init(self):
self.errors = {'403':'Login o password incorrectos','404':'Tumblrlog incorrecto','urlopen':'no ingreso su tumblrlog'}
return self
@objc.IBAction
def authTumblr_(self, sender):
self.p = self.password.stringValue()
self.u = self.user.stringValue()
self.b = self.blog.stringValue()
self.api = Api(self.b, self.u, self.p)
NSLog("Blog %s, User %s , Password %s" % (self.b, self.u, self.p))
try:
self.auth = self.api.auth_check()
self.destroy()
DashboardController.show()
except tumblr.TumblrAuthError:
print self.errors['403']
except tumblr.TumblrError(self):
print self.errors['404']
#except urllib2.HTTPError():
# print self.errors['404']
#except urllib2.URLError:
# print self.errors['urlopen']
def destroy(self):
app = NSApplication.sharedApplication()
appdelegate = app.delegate()
appdelegate.w.close()
| {
"repo_name": "jyr/opentumblr-cocoa",
"path": "LoginController.py",
"copies": "1",
"size": "1166",
"license": "mit",
"hash": -4015286507459814000,
"line_mean": 26.7619047619,
"line_max": 119,
"alpha_frac": 0.6963979417,
"autogenerated": false,
"ratio": 2.9444444444444446,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.8726113828681719,
"avg_score": 0.08294571149254527,
"num_lines": 42
} |
from Foundation import *
from AppKit import *
import random
from twisted.internet import ssl
from friendly.model import Account
class CreateAccountModel(NSObject):
def init(self):
self = NSObject.init(self)
if self is None:
return None
self.onlyContacts = True
self.announceList = []
self.fullName = ""
self.email = ""
self.displayName = "New Account"
self.listenPort = 1232
self.usePortMapper = False
self.useExistingIdentity = False
return self
class CreateAccountController(NSWindowController):
model = objc.IBOutlet()
announceController = objc.IBOutlet()
announceTable = objc.IBOutlet()
def initWithApp_(self, app):
"""
Initialize a new create-account dialog window controller.
"""
self = NSWindowController.initWithWindowNibName_owner_(
self, "CreateAccount", self)
self.app = app
return self
def addAnnounceEntry_(self, sender):
"""
"""
insertedObject = self.announceController.newObject()
row = self.announceTable.numberOfRows()
self.announceController.insertObject_atArrangedObjectIndex_(
insertedObject, row
)
self.announceTable.editColumn_row_withEvent_select_(
0, row, None, True
)
def randomizeListenPort_(self, sender):
"""
Randomize listen port.
"""
self.model.listenPort = random.randint(1024, 65535)
def createAccount_(self, sender):
""".
"""
sslopt = dict()
if self.model.fullName or self.model.email:
if self.model.fullName and self.model.email:
emailAddress = "%s <%s>" % (
self.model.fullName,
self.model.email
)
elif self.model.fullName:
emailAddress = self.model.fullName
else:
emailAddress = self.model.email
sslopt['emailAddress'] = emailAddress
serialNumber = 1
cert = ssl.KeyPair.generate().selfSignedCert(serialNumber,
**sslopt)
print 'SSL certificate generated:'
print cert.inspect()
# create the new account
account = Account.alloc().initWithName_andCert_(
self.model.displayName, cert
)
self.app.addAccount_(account)
self.close()
def openIdentityFile_(self, sender):
pass
| {
"repo_name": "jrydberg/friendly",
"path": "friendly/account.py",
"copies": "1",
"size": "2598",
"license": "mit",
"hash": -2833732429787589600,
"line_mean": 29.2093023256,
"line_max": 68,
"alpha_frac": 0.5673595073,
"autogenerated": false,
"ratio": 4.565905096660808,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5633264603960809,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
import random
from zope.interface import Interface
from twisted.plugin import getPlugins
from friendly import plugins, ifriendly
from friendly.model import Contact
class ImportContactsController(NSWindowController):
"""
Coordinating controller for importing contacts.
The controller is responsible for a window where the user may add
display names and email addresses of contacts.
"""
accountBox = objc.ivar('accountBox')
contactTable = objc.ivar('contactTable')
disclosureTriangle = objc.ivar('disclosureTriangle')
passwordInput = objc.ivar('passwordInput')
usernameInput = objc.ivar('usernameInput')
serviceBox = objc.ivar('serviceBox')
spinner = objc.ivar('spinner')
statusLabel = objc.ivar('statusLabel')
arrayController = objc.ivar('arrayController')
accountController = objc.ivar('accountController')
def initWithApp_(self, app):
"""
Initialize new controller instance.
"""
self = NSWindowController.initWithWindowNibName_owner_(
self, "ImportContacts", self
)
if self is not None:
self.app = app
return self
def awakeFromNib(self):
self.disclosureTriangle.setState_(NSOffState)
self.disclosurePressed_(self.disclosureTriangle)
# get all contact importers.
self.importers = list(
getPlugins(ifriendly.IContactImporter, plugins)
)
self.serviceBox.removeAllItems()
for importer in self.importers:
self.serviceBox.addItemWithTitle_(importer.description)
@objc.IBAction
def addContacts_(self, sender):
"""
"""
account = self.accountController.selectedObjects()[0]
for description in self.arrayController.arrangedObjects():
if not description['import']:
continue
name = description['name']
email = description['email']
if account.hasContactWithEmail_(email) or not len(email):
continue
contact = Contact.alloc().initWithName_andEmail_(
name, email
)
account.addContact_(contact)
self.app.saveAccounts()
def _addContact(self, description):
"""
Add a single description to the contact list.
@param description: C{dict} describing the contact.
"""
insertedObject = self.arrayController.newObject()
insertedObject['import'] = True
insertedObject['name'] = description['name']
insertedObject['email'] = description['email']
row = self.contactTable.numberOfRows()
self.arrayController.insertObject_atArrangedObjectIndex_(
insertedObject, row
)
def cbImporter(self, contacts):
self.spinner.stopAnimation_(self)
for contact in contacts:
self._addContact(contact)
self.status("Imported %d contacts" % len(contacts))
def ebImporter(self, failure):
self.status("Failed to import")
print failure
self.spinner.stopAnimation_(self)
def status(self, message):
self.statusLabel.setHidden_(False)
self.statusLabel.setStringValue_(message)
@objc.IBAction
def addContactsFromService_(self, sender):
importerIndex = self.serviceBox.indexOfSelectedItem()
importer = self.importers[importerIndex]
username = self.usernameInput.stringValue()
password = self.passwordInput.stringValue()
self.spinner.startAnimation_(self)
d = importer.importContacts(username, password, self.status)
d.addCallback(self.cbImporter)
d.addErrback(self.ebImporter)
@objc.IBAction
def addNewContact_(self, sender):
"""
"""
insertedObject = self.arrayController.newObject()
insertedObject['import'] = True
row = self.contactTable.numberOfRows()
self.arrayController.insertObject_atArrangedObjectIndex_(
insertedObject, row
)
self.contactTable.editColumn_row_withEvent_select_(
1, row, None, True
)
@objc.IBAction
def disclosurePressed_(self, sender):
"""
Called when disclosure triangle has been pressed.
"""
LARGE = 481 + 20
SMALL = 285 + 20
frame = self.window().frame()
if sender.state() == NSOnState:
frame.size.height = LARGE
frame.origin.y -= (LARGE - SMALL)
else:
frame.size.height = SMALL
frame.origin.y += (LARGE - SMALL)
self.window().setFrame_display_animate_(frame, True, True)
class EndpointStringValueTransformer(NSValueTransformer):
def transformedValueClass(self):
return NSString
def transformedValue_(self, endpoint):
if endpoint is not None:
return "XXX"
return None
class CertificateFingerprintValueTransformer(NSValueTransformer):
def transformedValueClass(self):
return NSString
def transformedValue_(self, cert):
if cert is not None:
return cert.digest()
return None
class ContactStatusImageValueTransformer(NSValueTransformer):
def init(self):
self = NSValueTransformer.init(self)
self.connectedImage = None
return self
def transformedValueClass(self):
return NSImage
def transformedValue_(self, value):
if self.connectedImage is None:
self.connectedImage = NSImage.imageNamed_(
'status-connected'
)
return self.connectedImage
class ContactListController(NSWindowController):
app = objc.IBOutlet()
arrayController = objc.IBOutlet()
def initWithApp_(self, app):
self = NSWindowController.initWithWindowNibName_owner_(
self, "ContactList", self)
self.app = app
return self
@objc.IBAction
def export_(self, sender):
pass
@objc.IBAction
def connect_(self, sender):
pass
| {
"repo_name": "jrydberg/friendly",
"path": "friendly/contacts.py",
"copies": "1",
"size": "6184",
"license": "mit",
"hash": -1408420968544375800,
"line_mean": 30.2323232323,
"line_max": 69,
"alpha_frac": 0.6290426908,
"autogenerated": false,
"ratio": 4.477914554670528,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.005317610079514841,
"num_lines": 198
} |
from Foundation import *
from AppKit import *
import time
def application(appName):
appPath = NSWorkspace.sharedWorkspace().fullPathForApplication_(appName);
if (not appPath):
print("Could not find application '" + appName + "'")
return None
appBundle = NSBundle.bundleWithPath_(appPath)
bundleId = appBundle.bundleIdentifier()
runningApps = NSWorkspace.sharedWorkspace().launchedApplications().valueForKey_("NSApplicationBundleIdentifier")
if not bundleId in runningApps:
NSWorkspace.sharedWorkspace().launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_(bundleId, NSWorkspaceLaunchWithoutActivation | NSWorkspaceLaunchAsync, None, None)
port = bundleId + ".JSTalk"
conn = None
tries = 0
while ((conn is None) and (tries < 10)):
conn = NSConnection.connectionWithRegisteredName_host_(port, None)
tries = tries + 1;
if (not conn):
time.sleep(1)
if (not conn):
print("Could not find a JSTalk connection to " + appName)
return None
return conn.rootProxy()
def proxyForApp(appName):
return application(appName) | {
"repo_name": "ccgus/jstalk",
"path": "example_scripts/JSTalk.py",
"copies": "1",
"size": "1235",
"license": "mit",
"hash": -6454366959978930000,
"line_mean": 29.9,
"line_max": 207,
"alpha_frac": 0.6712550607,
"autogenerated": false,
"ratio": 4.379432624113475,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5550687684813475,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
class FileSettings(NSObject):
fsdefault_py = None
fsdefault_pyw = None
fsdefault_pyc = None
default_py = None
default_pyw = None
default_pyc = None
factorySettings = None
prefskey = None
settings = None
def getFactorySettingsForFileType_(cls, filetype):
if filetype == u'Python Script':
curdefault = cls.fsdefault_py
elif filetype == u'Python GUI Script':
curdefault = cls.fsdefault_pyw
elif filetype == u'Python Bytecode Document':
curdefault = cls.fsdefault_pyc
else:
NSLog(u'Funny File Type: %s\n', filetype)
curdefault = cls.fsdefault_py
filetype = u'Python Script'
if curdefault is None:
curdefault = FileSettings.alloc().initForFSDefaultFileType_(filetype)
return curdefault
getFactorySettingsForFileType_ = classmethod(getFactorySettingsForFileType_)
def getDefaultsForFileType_(cls, filetype):
if filetype == u'Python Script':
curdefault = cls.default_py
elif filetype == u'Python GUI Script':
curdefault = cls.default_pyw
elif filetype == u'Python Bytecode Document':
curdefault = cls.default_pyc
else:
NSLog(u'Funny File Type: %s', filetype)
curdefault = cls.default_py
filetype = u'Python Script'
if curdefault is None:
curdefault = FileSettings.alloc().initForDefaultFileType_(filetype)
return curdefault
getDefaultsForFileType_ = classmethod(getDefaultsForFileType_)
def newSettingsForFileType_(cls, filetype):
return FileSettings.alloc().initForFileType_(filetype)
newSettingsForFileType_ = classmethod(newSettingsForFileType_)
def initWithFileSettings_(self, source):
self = super(FileSettings, self).init()
self.settings = source.fileSettingsAsDict().copy()
self.origsource = None
return self
def initForFileType_(self, filetype):
defaults = FileSettings.getDefaultsForFileType_(filetype)
self = self.initWithFileSettings_(defaults)
self.origsource = defaults
return self
def initForFSDefaultFileType_(self, filetype):
self = super(FileSettings, self).init()
if type(self).factorySettings is None:
bndl = NSBundle.mainBundle()
path = bndl.pathForResource_ofType_(u'factorySettings', u'plist')
type(self).factorySettings = NSDictionary.dictionaryWithContentsOfFile_(path)
if type(self).factorySettings is None:
NSLog(u'Missing %s', path)
return None
dct = type(self).factorySettings.get(filetype)
if dct is None:
NSLog(u'factorySettings.plist misses file type "%s"', filetype)
return None
self.applyValuesFromDict_(dct)
interpreters = dct[u'interpreter_list']
mgr = NSFileManager.defaultManager()
self.settings['interpreter'] = u'no default found'
for filename in interpreters:
filename = filename.nsstring().stringByExpandingTildeInPath()
if mgr.fileExistsAtPath_(filename):
self.settings['interpreter'] = filename
break
self.origsource = None
return self
def applyUserDefaults_(self, filetype):
dct = NSUserDefaults.standardUserDefaults().dictionaryForKey_(filetype)
if dct:
self.applyValuesFromDict_(dct)
def initForDefaultFileType_(self, filetype):
fsdefaults = FileSettings.getFactorySettingsForFileType_(filetype)
self = self.initWithFileSettings_(fsdefaults)
if self is None:
return self
self.settings['interpreter_list'] = fsdefaults.settings['interpreter_list']
self.settings['scriptargs'] = u''
self.applyUserDefaults_(filetype)
self.prefskey = filetype
return self
def reset(self):
if self.origsource:
self.updateFromSource_(self.origsource)
else:
fsdefaults = FileSettings.getFactorySettingsForFileType_(self.prefskey)
self.updateFromSource_(fsdefaults)
def updateFromSource_(self, source):
self.settings.update(source.fileSettingsAsDict())
if self.origsource is None:
NSUserDefaults.standardUserDefaults().setObject_forKey_(self.fileSettingsAsDict(), self.prefskey)
def applyValuesFromDict_(self, dct):
if self.settings is None:
self.settings = {}
self.settings.update(dct)
def commandLineForScript_(self, script):
cur_interp = None
if self.settings['honourhashbang']:
try:
line = file(script, 'rU').next().rstrip()
except:
pass
else:
if line.startswith('#!'):
cur_interp = line[2:]
if cur_interp is None:
cur_interp = self.settings['interpreter']
cmd = []
cmd.append('"'+cur_interp.replace('"', '\\"')+'"')
if self.settings['debug']:
cmd.append('-d')
if self.settings['verbose']:
cmd.append('-v')
if self.settings['inspect']:
cmd.append('-i')
if self.settings['optimize']:
cmd.append('-O')
if self.settings['nosite']:
cmd.append('-S')
if self.settings['tabs']:
cmd.append('-t')
others = self.settings['others']
if others:
cmd.append(others)
cmd.append('"'+script.replace('"', '\\"')+'"')
cmd.append(self.settings['scriptargs'])
if self.settings['with_terminal']:
cmd.append("""&& echo "Exit status: $?" && python -c 'import sys;sys.stdin.readline()' && exit 1""")
else:
cmd.append('&')
return ' '.join(cmd)
def fileSettingsAsDict(self):
return self.settings
| {
"repo_name": "albertz/music-player",
"path": "mac/pyobjc-framework-Cocoa/Examples/AppKit/PyObjCLauncher/FileSettings.py",
"copies": "3",
"size": "6020",
"license": "bsd-2-clause",
"hash": 2661072002642458600,
"line_mean": 36.625,
"line_max": 112,
"alpha_frac": 0.6079734219,
"autogenerated": false,
"ratio": 4.352856109906002,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6460829531806002,
"avg_score": null,
"num_lines": null
} |
#from Foundation import *
#from AppKit import *
import compiler
parse = compiler.parse
import compiler.ast
Sub = compiler.ast.Sub
UnarySub = compiler.ast.UnarySub
Add = compiler.ast.Add
import Foundation
import AppKit
NSObject = AppKit.NSObject
NSColor = AppKit.NSColor
NSMutableParagraphStyle = AppKit.NSMutableParagraphStyle
NSCenterTextAlignment = AppKit.NSCenterTextAlignment
NSFont = AppKit.NSFont
NSForegroundColorAttributeName = AppKit.NSForegroundColorAttributeName
NSCursor = AppKit.NSCursor
NSGraphicsContext = AppKit.NSGraphicsContext
NSBezierPath = AppKit.NSBezierPath
NSString = AppKit.NSString
NSEvent = AppKit.NSEvent
NSAlternateKeyMask = AppKit.NSAlternateKeyMask
NSShiftKeyMask = AppKit.NSShiftKeyMask
NSParagraphStyleAttributeName = AppKit.NSParagraphStyleAttributeName
NSFontAttributeName = AppKit.NSFontAttributeName
MAGICVAR = "__magic_var__"
class ValueLadder:
view = None
visible = False
value = None
origValue = None
dirty = False
type = None
negative = False
unary = False
add = False
def __init__(self, textView, value, clickPos, screenPoint, viewPoint):
self.textView = textView
self.value = value
self.origValue = value
self.type = type(value)
self.clickPos = clickPos
self.origX, self.origY = screenPoint
self.x, self.y = screenPoint
self.viewPoint = viewPoint
(x,y),(self.width,self.height) = self.textView.bounds()
self.originalString = self.textView.string()
self.backgroundColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
0.4,0.4,0.4, 1.0)
self.strokeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
0.1,0.1,0.1, 1.0)
self.textColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(
1.0,1.0,1.0, 1.0)
paraStyle = NSMutableParagraphStyle.alloc().init()
paraStyle.setAlignment_(NSCenterTextAlignment)
font = NSFont.fontWithName_size_("Monaco", 10)
self.textAttributes = {
NSForegroundColorAttributeName: self.textColor,
NSParagraphStyleAttributeName: paraStyle,NSFontAttributeName:font}
# To speed things up, the code is compiled only once.
# The number is replaced with a magic variable, that is set in the
# namespace when executing the code.
begin,end = self.clickPos
self.patchedSource = (self.originalString[:begin]
+ MAGICVAR
+ self.originalString[end:])
#ast = parse(self.patchedSource + "\n\n")
#self._checkSigns(ast)
success, output = self.textView.document.boxedRun_args_(self._parseAndCompile, [])
if success:
self.show()
else:
self.textView.document._flushOutput(output)
def _parseAndCompile(self):
ast = parse(self.patchedSource.encode('ascii', 'replace') + "\n\n")
self._checkSigns(ast)
self.textView.document._compileScript(self.patchedSource)
def _checkSigns(self, node):
"""Recursively check for special sign cases.
The following cases are special:
- Substraction. When you select the last part of a substraction
(e.g. the 5 of "10-5"), it might happen that you drag the number to
a positive value. In that case, the result should be "10+5".
- Unary substraction. Values like "-5" should have their sign removed
when you drag them to a positive value.
- Addition. When you select the last part of an addition
(e.g. the 5 of "10+5"), and drag the number to a negative value,
the result should be "10-5".
This algorithm checks for these cases. It tries to find the magic var,
and then checks the parent node to see if it is one of these cases,
then sets the appropriate state variables in the object.
This algorithm is recursive. Because we have to differ between a
"direct hit" (meaning the current child was the right one) and a
"problem resolved" (meaning the algorithm found the node, did its
work and now needs to bail out), we have three return codes:
- -1: nothing was found in this node and its child nodes.
- 1: direct hit. The child you just searched contains the magicvar.
check the current node to see if it is one of the special cases.
- 0: bail out. Somewhere, a child contained the magicvar, and we
acted upon it. Now leave this algorithm as soon as possible.
"""
# Check whether I am the correct node
try:
if node.name == MAGICVAR:
return 1 # If i am, return the "direct hit" code.
except AttributeError:
pass
# We keep an index to see what child we are checking. This
# is important for binary operations, were we are only interested
# in the second part. ("a-10" has to change to "a+10",
# but "10-a" shouldn't change to "+10-a")
index = 0
# Recursively check my children
for child in node.getChildNodes():
retVal = self._checkSigns(child)
# Direct hit. The child I just searched contains the magicvar.
# Check whether this node is one of the special cases.
if retVal == 1:
# Unary substitution.
if isinstance(node, UnarySub):
self.negative = True
self.unary = True
# Binary substitution. Only the second child is of importance.
elif isinstance(node, Sub) and index == 1:
self.negative = True
# Binary addition. Only the second child is of importance.
elif isinstance(node, Add) and index == 1:
self.add = True
# Return the "bail out" code, whether we found some
# special case or not. There can only be one magicvar in the
# code, so once that is found we can stop looking.
return 0
# If the child returns a bail out code, we leave this routine
# without checking the other children, passing along the
# bail out code.
elif retVal == 0:
return 0 # Nothing more needs to be done.
# Next child.
index += 1
# We searched all children, but couldn't find any magicvars.
return -1
def show(self):
self.visible = True
self.textView.setNeedsDisplay_(True)
NSCursor.hide()
def hide(self):
"""Hide the ValueLadder and update the code.
Updating the code means we have to replace the current value with
the new value, and account for any special cases."""
self.visible = False
begin,end = self.clickPos
# Potentionally change the sign on the number.
# The following cases are valid:
# - A subtraction where the value turned positive "random(5-8)" --> "random(5+8)"
# - A unary subtraction where the value turned positive "random(-5)" --> "random(5)"
# Note that the sign dissapears here.
# - An addition where the second part turns negative "random(5+8)" --> "random(5-8)"
# Note that the code replaces the sign on the place where it was, leaving the code intact.
# Case 1: Negative numbers where the new value is negative as well.
# This means the numbers turn positive.
if self.negative and self.value < 0:
# Find the minus sign.
i = begin - 1
notFound = True
while True:
if self.originalString[i] == '-':
if self.unary: # Unary subtractions will have the sign removed.
# Re-create the string: the spaces between the value and the '-' + the value
value = self.originalString[i+1:begin] + str(abs(self.value))
else: # Binary subtractions get a '+'
value = '+' + self.originalString[i+1:begin] + str(abs(self.value))
range = (i,end-i)
break
i -= 1
# Case 2: Additions (only additions where we are the second part
# interests us, this is checked already on startup)
elif self.add and self.value < 0:
# Find the plus sign.
i = begin - 1
notFound = True
while True:
if self.originalString[i] == '+':
# Re-create the string:
# - a '+' (instead of the minus)
# - the spaces between the '-' and the constant
# - the constant itself
value = '-' + self.originalString[i+1:begin] + str(abs(self.value))
range = (i,end-i)
break
i -= 1
# Otherwise, it's a normal case. Note that here also, positive numbers
# can turn negative, but no existing signs have to be changed.
else:
value = str(self.value)
range = (begin, end-begin)
# The following textView methods make sure that an undo operation
# is registered, so users can undo their drag.
self.textView.shouldChangeTextInRange_replacementString_(range, value)
self.textView.textStorage().replaceCharactersInRange_withString_(range, value)
self.textView.didChangeText()
self.textView.setNeedsDisplay_(True)
self.textView.document.currentView.direct = False
NSCursor.unhide()
def draw(self):
mx,my=self.viewPoint
x = mx-20
w = 80
h = 20
h2 = h*2
context = NSGraphicsContext.currentContext()
aa = context.shouldAntialias()
context.setShouldAntialias_(False)
r = ((mx-w/2,my+12),(w,h))
NSBezierPath.setDefaultLineWidth_(0)
self.backgroundColor.set()
NSBezierPath.fillRect_(r)
self.strokeColor.set()
NSBezierPath.strokeRect_(r)
# A standard value just displays the value that you have been dragging.
if not self.negative:
v = str(self.value)
# When the value is negative, we don't display a double negative,
# but a positive.
elif self.value < 0:
v = str(abs(self.value))
# When the value is positive, we have to add a minus sign.
else:
v = "-" + str(self.value)
NSString.drawInRect_withAttributes_(v, ((mx-w/2,my+14),(w,h2)), self.textAttributes)
context.setShouldAntialias_(aa)
def mouseDragged_(self, event):
mod = event.modifierFlags()
newX, newY = NSEvent.mouseLocation()
deltaX = newX-self.x
delta = deltaX
if self.negative:
delta = -delta
if mod & NSAlternateKeyMask:
delta /= 100.0
elif mod & NSShiftKeyMask:
delta *= 10.0
self.value = self.type(self.value + delta)
self.x, self.y = newX, newY
self.dirty = True
self.textView.setNeedsDisplay_(True)
self.textView.document.magicvar = self.value
self.textView.document.currentView.direct = True
self.textView.document.runScriptFast()
| {
"repo_name": "karstenw/nodebox-pyobjc",
"path": "nodebox/gui/mac/ValueLadder.py",
"copies": "1",
"size": "11679",
"license": "mit",
"hash": -5965952268167383000,
"line_mean": 39.8356643357,
"line_max": 100,
"alpha_frac": 0.5902046408,
"autogenerated": false,
"ratio": 4.236126224156692,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5326330864956692,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from AppKit import *
MAGICVAR = "__magic_var__"
class ValueLadder:
view = None
visible = False
value = None
origValue = None
dirty = False
type = None
negative = False
unary = False
add = False
def __init__(self, textView, value, clickPos, screenPoint, viewPoint):
self.textView = textView
self.value = value
self.origValue = value
self.type = type(value)
self.clickPos = clickPos
self.origX, self.origY = screenPoint
self.x, self.y = screenPoint
self.viewPoint = viewPoint
(x,y),(self.width,self.height) = self.textView.bounds()
self.originalString = self.textView.string()
self.backgroundColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.4,0.4,0.4,1.0)
self.strokeColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(0.1,0.1,0.1, 1.0)
self.textColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(1.,1.,1.,1.)
paraStyle = NSMutableParagraphStyle.alloc().init()
paraStyle.setAlignment_(NSCenterTextAlignment)
font = NSFont.fontWithName_size_("Monaco", 10)
self.textAttributes = {NSForegroundColorAttributeName:self.textColor,NSParagraphStyleAttributeName:paraStyle,NSFontAttributeName:font}
# To speed things up, the code is compiled only once.
# The number is replaced with a magic variable, that is set in the
# namespace when executing the code.
begin,end = self.clickPos
self.patchedSource = self.originalString[:begin] + MAGICVAR + self.originalString[end:]
#ast = parse(self.patchedSource + "\n\n")
#self._checkSigns(ast)
success, output = self.textView.document._boxedRun(self._parseAndCompile)
if success:
self.show()
else:
self.textView.document._flushOutput(output)
def _parseAndCompile(self):
from compiler import parse
ast = parse(self.patchedSource.encode('ascii', 'replace') + "\n\n")
self._checkSigns(ast)
self.textView.document._compileScript(self.patchedSource)
def _checkSigns(self, node):
"""Recursively check for special sign cases.
The following cases are special:
- Substraction. When you select the last part of a substraction
(e.g. the 5 of "10-5"), it might happen that you drag the number to
a positive value. In that case, the result should be "10+5".
- Unary substraction. Values like "-5" should have their sign removed
when you drag them to a positive value.
- Addition. When you select the last part of an addition
(e.g. the 5 of "10+5"), and drag the number to a negative value,
the result should be "10-5".
This algorithm checks for these cases. It tries to find the magic var,
and then checks the parent node to see if it is one of these cases,
then sets the appropriate state variables in the object.
This algorithm is recursive. Because we have to differ between a
"direct hit" (meaning the current child was the right one) and a
"problem resolved" (meaning the algorithm found the node, did its
work and now needs to bail out), we have three return codes:
- -1: nothing was found in this node and its child nodes.
- 1: direct hit. The child you just searched contains the magicvar.
check the current node to see if it is one of the special cases.
- 0: bail out. Somewhere, a child contained the magicvar, and we
acted upon it. Now leave this algorithm as soon as possible.
"""
from compiler.ast import Sub, UnarySub, Add
# Check whether I am the correct node
try:
if node.name == MAGICVAR:
return 1 # If i am, return the "direct hit" code.
except AttributeError:
pass
# We keep an index to see what child we are checking. This
# is important for binary operations, were we are only interested
# in the second part. ("a-10" has to change to "a+10",
# but "10-a" shouldn't change to "+10-a")
index = 0
# Recursively check my children
for child in node.getChildNodes():
retVal = self._checkSigns(child)
# Direct hit. The child I just searched contains the magicvar.
# Check whether this node is one of the special cases.
if retVal == 1:
# Unary substitution.
if isinstance(node, UnarySub):
self.negative = True
self.unary = True
# Binary substitution. Only the second child is of importance.
elif isinstance(node, Sub) and index == 1:
self.negative = True
# Binary addition. Only the second child is of importance.
elif isinstance(node, Add) and index == 1:
self.add = True
# Return the "bail out" code, whether we found some
# special case or not. There can only be one magicvar in the
# code, so once that is found we can stop looking.
return 0
# If the child returns a bail out code, we leave this routine
# without checking the other children, passing along the
# bail out code.
elif retVal == 0:
return 0 # Nothing more needs to be done.
# Next child.
index += 1
# We searched all children, but couldn't find any magicvars.
return -1
def show(self):
self.visible = True
self.textView.setNeedsDisplay_(True)
NSCursor.hide()
def hide(self):
"""Hide the ValueLadder and update the code.
Updating the code means we have to replace the current value with
the new value, and account for any special cases."""
self.visible = False
begin,end = self.clickPos
# Potentionally change the sign on the number.
# The following cases are valid:
# - A subtraction where the value turned positive "random(5-8)" --> "random(5+8)"
# - A unary subtraction where the value turned positive "random(-5)" --> "random(5)"
# Note that the sign dissapears here.
# - An addition where the second part turns negative "random(5+8)" --> "random(5-8)"
# Note that the code replaces the sign on the place where it was, leaving the code intact.
# Case 1: Negative numbers where the new value is negative as well.
# This means the numbers turn positive.
if self.negative and self.value < 0:
# Find the minus sign.
i = begin - 1
notFound = True
while True:
if self.originalString[i] == '-':
if self.unary: # Unary subtractions will have the sign removed.
# Re-create the string: the spaces between the value and the '-' + the value
value = self.originalString[i+1:begin] + str(abs(self.value))
else: # Binary subtractions get a '+'
value = '+' + self.originalString[i+1:begin] + str(abs(self.value))
range = (i,end-i)
break
i -= 1
# Case 2: Additions (only additions where we are the second part
# interests us, this is checked already on startup)
elif self.add and self.value < 0:
# Find the plus sign.
i = begin - 1
notFound = True
while True:
if self.originalString[i] == '+':
# Re-create the string:
# - a '+' (instead of the minus)
# - the spaces between the '-' and the constant
# - the constant itself
value = '-' + self.originalString[i+1:begin] + str(abs(self.value))
range = (i,end-i)
break
i -= 1
# Otherwise, it's a normal case. Note that here also, positive numbers
# can turn negative, but no existing signs have to be changed.
else:
value = str(self.value)
range = (begin, end-begin)
# The following textView methods make sure that an undo operation
# is registered, so users can undo their drag.
self.textView.shouldChangeTextInRange_replacementString_(range, value)
self.textView.textStorage().replaceCharactersInRange_withString_(range, value)
self.textView.didChangeText()
self.textView.setNeedsDisplay_(True)
self.textView.document.currentView.direct = False
NSCursor.unhide()
def draw(self):
mx,my=self.viewPoint
x = mx-20
w = 80
h = 20
h2 = h*2
context = NSGraphicsContext.currentContext()
aa = context.shouldAntialias()
context.setShouldAntialias_(False)
r = ((mx-w/2,my+12),(w,h))
NSBezierPath.setDefaultLineWidth_(0)
self.backgroundColor.set()
NSBezierPath.fillRect_(r)
self.strokeColor.set()
NSBezierPath.strokeRect_(r)
# A standard value just displays the value that you have been dragging.
if not self.negative:
v = str(self.value)
# When the value is negative, we don't display a double negative,
# but a positive.
elif self.value < 0:
v = str(abs(self.value))
# When the value is positive, we have to add a minus sign.
else:
v = "-" + str(self.value)
NSString.drawInRect_withAttributes_(v, ((mx-w/2,my+14),(w,h2)), self.textAttributes)
context.setShouldAntialias_(aa)
def mouseDragged_(self, event):
mod = event.modifierFlags()
newX, newY = NSEvent.mouseLocation()
deltaX = newX-self.x
delta = deltaX
if self.negative:
delta = -delta
if mod & NSAlternateKeyMask:
delta /= 100.0
elif mod & NSShiftKeyMask:
delta *= 10.0
self.value = self.type(self.value + delta)
self.x, self.y = newX, newY
self.dirty = True
self.textView.setNeedsDisplay_(True)
self.textView.document.magicvar = self.value
self.textView.document.currentView.direct = True
self.textView.document.runScriptFast_()
| {
"repo_name": "gt-ros-pkg/rcommander-core",
"path": "nodebox_qt/src/nodebox/gui/mac/ValueLadder.py",
"copies": "1",
"size": "10651",
"license": "bsd-3-clause",
"hash": -135349581263037250,
"line_mean": 41.604,
"line_max": 142,
"alpha_frac": 0.5878321284,
"autogenerated": false,
"ratio": 4.2282651845970625,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5316097312997062,
"avg_score": null,
"num_lines": null
} |
# from Foundation import *
from AppKit import NSDate, NSDatePicker, NSClockAndCalendarDatePickerStyle, NSTextFieldAndStepperDatePickerStyle, NSHourMinuteDatePickerElementFlag, NSHourMinuteSecondDatePickerElementFlag, NSYearMonthDatePickerElementFlag, NSYearMonthDayDatePickerElementFlag
from vanilla.vanillaBase import VanillaBaseControl
_modeMap = {
"graphical": NSClockAndCalendarDatePickerStyle,
"text": 2, #NSTextFieldDatePickerStyle raises an error
"textStepper": NSTextFieldAndStepperDatePickerStyle,
}
_timeDisplayFlagMap = {
None : 0,
"hourMinute" : NSHourMinuteDatePickerElementFlag,
"hourMinuteSecond" : NSHourMinuteSecondDatePickerElementFlag,
}
_dateDisplayFlagMap = {
None : 0,
"yearMonth" : NSYearMonthDatePickerElementFlag,
"yearMonthDay" : NSYearMonthDayDatePickerElementFlag,
}
class DatePicker(VanillaBaseControl):
"""
**posSize** Tuple of form *(left, top, width, height)* or *"auto"*
representing the position and size of the date picker control.
+-------------------------------------+
| **Standard Dimensions - Text Mode** |
+---------+---+-----------------------+
| Regular | H | 22 |
+---------+---+-----------------------+
| Small | H | 19 |
+---------+---+-----------------------+
| Mini | H | 16 |
+---------+---+-----------------------+
+------------------------------------------+
| **Standard Dimensions - Graphical Mode** |
+--------------------+---------------------+
| Calendar and Clock | 227w 148h |
+--------------------+---------------------+
| Calendar | 139w 148h |
+--------------------+---------------------+
| Clock | 122w 123h |
+--------------------+---------------------+
**date** A `NSDate`_ object representing the date and time that should be
set in the control.
**minDate** A `NSDate`_ object representing the lowest date and time that
can be set in the control.
**maxDate** A `NSDate`_ object representing the highest date and time that
can be set in the control.
**showStepper** A boolean indicating if the thumb stepper should be shown
in text mode.
**mode** A string representing the desired mode for the date picker control.
The options are:
+-------------+
| "text" |
+-------------+
| "graphical" |
+-------------+
**timeDisplay** A string representing the desired time units that should be
displayed in the date picker control. The options are:
+--------------------+-------------------------------+
| None | Do not display time. |
+--------------------+-------------------------------+
| "hourMinute" | Display hour and minute. |
+--------------------+-------------------------------+
| "hourMinuteSecond" | Display hour, minute, second. |
+--------------------+-------------------------------+
**dateDisplay** A string representing the desired date units that should be
displayed in the date picker control. The options are:
+----------------+------------------------------+
| None | Do not display date. |
+----------------+------------------------------+
| "yearMonth" | Display year and month. |
+----------------+------------------------------+
| "yearMonthDay" | Display year, month and day. |
+----------------+------------------------------+
**sizeStyle** A string representing the desired size style of the
date picker control. This only applies in text mode. The options are:
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
| "mini" |
+-----------+
.. _NSDate: https://developer.apple.com/documentation/foundation/nsdate?language=objc
"""
nsDatePickerClass = NSDatePicker
def __init__(self, posSize, date=None, minDate=None, maxDate=None, showStepper=True, mode="text",
timeDisplay="hourMinuteSecond", dateDisplay="yearMonthDay", callback=None, sizeStyle="regular"):
self._setupView(self.nsDatePickerClass, posSize, callback=callback)
self._setSizeStyle(sizeStyle)
self._nsObject.setDrawsBackground_(True)
self._nsObject.setBezeled_(True)
if mode == "text" and showStepper:
mode += "Stepper"
style = _modeMap[mode]
self._nsObject.setDatePickerStyle_(style)
flag = _timeDisplayFlagMap[timeDisplay]
flag = flag | _dateDisplayFlagMap[dateDisplay]
self._nsObject.setDatePickerElements_(flag)
if date is None:
date = NSDate.date()
self._nsObject.setDateValue_(date)
if minDate is not None:
self._nsObject.setMinDate_(minDate)
if maxDate is not None:
self._nsObject.setMaxDate_(maxDate)
def getNSDatePicker(self):
"""
Return the `NSDatePicker`_ that this object wraps.
.. _NSDatePicker: https://developer.apple.com/documentation/appkit/nsdatepicker?language=objc
"""
return self._nsObject
def get(self):
"""
Get the contents of the date picker control.
"""
return self._nsObject.dateValue()
def set(self, value):
"""
Set the contents of the date picker control.
**value** A `NSDate`_ object.
"""
self._nsObject.setDateValue_(value)
| {
"repo_name": "typesupply/vanilla",
"path": "Lib/vanilla/vanillaDatePicker.py",
"copies": "1",
"size": "5524",
"license": "mit",
"hash": -3920034251838323000,
"line_mean": 35.582781457,
"line_max": 259,
"alpha_frac": 0.5217233888,
"autogenerated": false,
"ratio": 4.387609213661636,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.002134965866432652,
"num_lines": 151
} |
# from Foundation import *
from AppKit import NSDatePicker, NSClockAndCalendarDatePickerStyle, NSTextFieldAndStepperDatePickerStyle, NSHourMinuteDatePickerElementFlag, NSHourMinuteSecondDatePickerElementFlag, NSYearMonthDatePickerElementFlag, NSYearMonthDayDatePickerElementFlag
from vanilla.vanillaBase import VanillaBaseControl
_modeMap = {
"graphical": NSClockAndCalendarDatePickerStyle,
"text": 2, #NSTextFieldDatePickerStyle raises an error
"textStepper": NSTextFieldAndStepperDatePickerStyle,
}
_timeDisplayFlagMap = {
None : 0,
"hourMinute" : NSHourMinuteDatePickerElementFlag,
"hourMinuteSecond" : NSHourMinuteSecondDatePickerElementFlag,
}
_dateDisplayFlagMap = {
None : 0,
"yearMonth" : NSYearMonthDatePickerElementFlag,
"yearMonthDay" : NSYearMonthDayDatePickerElementFlag,
}
class DatePicker(VanillaBaseControl):
"""
**posSize** Tuple of form *(left, top, width, height)* representing the position and size of the date picker control.
+-------------------------------------+
| **Standard Dimensions - Text Mode** |
+---------+---+-----------------------+
| Regular | H | 22 |
+---------+---+-----------------------+
| Small | H | 19 |
+---------+---+-----------------------+
| Mini | H | 16 |
+---------+---+-----------------------+
+------------------------------------------+
| **Standard Dimensions - Graphical Mode** |
+--------------------+---------------------+
| Calendar and Clock | 227w 148h |
+--------------------+---------------------+
| Calendar | 139w 148h |
+--------------------+---------------------+
| Clock | 122w 123h |
+--------------------+---------------------+
**date** A *NSDate* object representing the date and time that should be set in the control.
**minDate** A *NSDate* object representing the lowest date and time that can be set in the control.
**maxDate** A *NSDate* object representing the highest date and time that can be set in the control.
**showStepper** A boolean indicating if the thumb stepper should be shown in text mode.
**mode** A string representing the desired mode for the date picker control. The options are:
+-------------+
| "text" |
+-------------+
| "graphical" |
+-------------+
**timeDisplay** A string representing the desired time units that should be displayed in the
date picker control. The options are:
+--------------------+-------------------------------+
| None | Do not display time. |
+--------------------+-------------------------------+
| "hourMinute" | Display hour and minute. |
+--------------------+-------------------------------+
| "hourMinuteSecond" | Display hour, minute, second. |
+--------------------+-------------------------------+
**dateDisplay** A string representing the desired date units that should be displayed in the
date picker control. The options are:
+----------------+------------------------------+
| None | Do not display date. |
+----------------+------------------------------+
| "yearMonth" | Display year and month. |
+----------------+------------------------------+
| "yearMonthDay" | Display year, month and day. |
+----------------+------------------------------+
**sizeStyle** A string representing the desired size style of the date picker control. This only
applies in text mode. The options are:
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
| "mini" |
+-----------+
"""
nsDatePickerClass = NSDatePicker
def __init__(self, posSize, date=None, minDate=None, maxDate=None, showStepper=True, mode="text",
timeDisplay="hourMinuteSecond", dateDisplay="yearMonthDay", callback=None, sizeStyle="regular"):
self._setupView(self.nsDatePickerClass, posSize, callback=callback)
self._setSizeStyle(sizeStyle)
self._nsObject.setDrawsBackground_(True)
self._nsObject.setBezeled_(True)
if mode == "text" and showStepper:
mode += "Stepper"
style = _modeMap[mode]
self._nsObject.setDatePickerStyle_(style)
flag = _timeDisplayFlagMap[timeDisplay]
flag = flag | _dateDisplayFlagMap[dateDisplay]
self._nsObject.setDatePickerElements_(flag)
if date is None:
date = NSDate.date()
self._nsObject.setDateValue_(date)
if minDate is not None:
self._nsObject.setMinDate_(minDate)
if maxDate is not None:
self._nsObject.setMaxDate_(maxDate)
def getNSDatePicker(self):
"""
Return the *NSDatePicker* that this object wraps.
"""
return self._nsObject
def get(self):
"""
Get the contents of the date picker control.
"""
return self._nsObject.dateValue()
def set(self, value):
"""
Set the contents of the date picker control.
**value** A *NSDate* object.
"""
self._nsObject.setDateValue_(value)
| {
"repo_name": "moyogo/vanilla",
"path": "Lib/vanilla/vanillaDatePicker.py",
"copies": "1",
"size": "5280",
"license": "mit",
"hash": 6990085280853478000,
"line_mean": 36.7142857143,
"line_max": 251,
"alpha_frac": 0.5159090909,
"autogenerated": false,
"ratio": 4.425817267393127,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5441726358293126,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from IOBluetooth import *
from objc import *
from pyble._roles import Peripheral
from gatt import OSXBLEService, OSXBLECharacteristic, OSXBLEDescriptor
from util import CBUUID2String
import uuid
import logging
import struct
from pprint import pformat
import time
from threading import Condition
from functools import wraps
from pyble.patterns import Trace
logger = logging.getLogger(__name__)
@Trace
class OSXPeripheral(NSObject, Peripheral):
"""
Connected Peripheral
CBPeripheral calss Reference:
https://developer.apple.com/librarY/mac/documentation/CoreBluetooth/Reference/CBPeripheral_Class/translated_content/CBPeripheral.html
CBPeripheralDelegate Protocol Reference:
https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBPeripheralDelegate_Protocol/translated_content/CBPeripheralDelegate.html
"""
def init(self):
Peripheral.__init__(self)
self.trace.traceInstance(self)
self.instance = None
self.cv = Condition()
self.ready = False
self.state = Peripheral.DISCONNECTED
# advertisement data
self.advLocalName = None
self.advManufacturerData = None
self.advServiceUUIDs = []
self.advServiceData = None
self.advOverflowServiceUUIDs = []
self.advIsConnectable = False
self.advTxPowerLevel = 0
self.advSolicitedServiceUUIDs = []
return self
@property
def isConnected(self):
return self.state == Peripheral.CONNECTED
@property
def services(self):
if len(self._services) == 0 and self.instance:
self.discoverServices()
return self._services
@services.setter
def services(self, value):
self._services = value
@property
def rssi(self):
# retrive RSSI if peripheral is connected
if self.state == Peripheral.CONNECTED:
self.readRSSI()
return self._rssi
@rssi.setter
def rssi(self, value):
if self._rssi != value:
self._rssi = value
self.updateRSSI(self._rssi)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
if value == Peripheral.DISCONNECTED:
self.logger.debug("%s is disconnected" % self)
self._state = value
elif value == Peripheral.CONNECTING:
self.logger.debug("Connecting to %s" % self)
self._state = value
elif value == Peripheral.CONNECTED:
self.logger.debug("peripheral is connected")
self._state = value
# peripheral is connected, init. delegate to self
# collecting gatt information
if self.instance:
self.instance.setDelegate_(self)
else:
self._state = Peripheral.DISCONNECTED
self.logger.error("UNKOWN Peripheral State: " + value)
self.updateState()
# decorators for condition variables
def _waitResp(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
with self.cv:
self.ready = False
func(self, *args, **kwargs)
while True:
self.cv.wait(0)
NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantPast())
if self.ready:
break
return wrapper
def _notifyResp(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
self.ready = True
with self.cv:
try:
self.cv.notifyAll()
except Exception as e:
print e
return wrapper
@_waitResp
def readRSSI(self):
self.instance.readRSSI()
@_waitResp
def discoverServices(self):
self.instance.discoverServices_(None)
@_waitResp
def discoverCharacteristicsForService(self, service):
self.instance.discoverCharacteristics_forService_(nil, service)
@_waitResp
def discoverDescriptorsForCharacteristic(self, characteristic):
self.instance.discoverDescriptorsForCharacteristic_(characteristic)
@_waitResp
def readValueForCharacteristic(self, characteristic):
self.instance.readValueForCharacteristic_(characteristic)
@_waitResp
def readValueForDescriptor(self, descriptor):
self.instance.readValueForDescriptor_(descriptor)
@_waitResp
def writeValueForCharacteristic(self, value, characteristic, withResponse=True):
writeType = CBCharacteristicWriteWithResponse if withResponse else CBCharacteristicWriteWithoutResponse
self.instance.writeValue_forCharacteristic_type_(value, characteristic, writeType)
@_waitResp
def setNotifyForCharacteristic(self, flag, characteristic):
self.instance.setNotifyValue_forCharacteristic_(flag, characteristic)
@python_method
def findServiceByServiceInstance(self, instance):
uuidBytes = instance._.UUID._.data
for s in self.services:
if str(s.UUID) == CBUUID2String(uuidBytes):
return s
return None
@python_method
def findServiceByCharacteristicInstance(self, instance):
uuidBytes = instance._.service._.UUID._.data
for s in self.services:
if str(s.UUID) == CBUUID2String(uuidBytes):
return s
return None
@python_method
def findServiceByDescriptorInstance(self, instance):
uuidBytes = instance._.characteristic._.service._.UUID._.data
for s in self.services:
if str(s.UUID) == CBUUID2String(uuidBytes):
return s
return None
@python_method
def findCharacteristicByDescriptorInstance(self, instance):
service = self.findServiceByDescriptorInstance(instance)
uuidBytes = instance._.characteristic._.UUID._.data
for c in service.characteristics:
if str(c.UUID) == CBUUID2String(uuidBytes):
return c
return None
# CBPeripheral Delegate functions
# objc delegate functions cannot be applied with decorators
# make addtional functions to enable decorators
# Discovering Services
def peripheral_didDiscoverServices_(self, peripheral, error):
self.didDiscoverServices(peripheral, error)
@_notifyResp
def didDiscoverServices(self, peripheral, error):
if error != nil:
if error._.code == CBErrorNotConnected:
self.state = Peripheral.DISCONNECTED
return
if peripheral._.services:
self.logger.debug("%s discovered services" % self)
for service in peripheral._.services:
s = OSXBLEService(peripheral=self, instance=service)
self._services.append(s)
def peripheral_didDiscoverIncludeServicesForService_error_(self, peripheral, service, error):
self.logger.debug("%s discovered Include Services" % self)
# Discovering Characteristics and Characteristic Descriptors
def peripheral_didDiscoverCharacteristicsForService_error_(self, peripheral, service, error):
self.didDiscoverCharacteristicsForService(peripheral, service, error)
@_notifyResp
def didDiscoverCharacteristicsForService(self, peripheral, service, error):
if error != nil:
print error
return
s = self.findServiceByServiceInstance(service)
p = s.peripheral
self.logger.debug("%s:%s discovered characteristics" % (p, s))
for c in service._.characteristics:
characteristic = OSXBLECharacteristic(service=s, profile=s, instance=c)
s.addCharacteristic(characteristic)
def peripheral_didDiscoverDescriptorsForCharacteristic_error_(self, peripheral, characteristic, error):
self.didDiscoverDescriptorsForCharacteristic(peripheral, characteristic, error)
@_notifyResp
def didDiscoverDescriptorsForCharacteristic(self, peripheral, characteristic, error):
s = self.findServiceByCharacteristicInstance(characteristic)
p = s.peripheral
c = s.findCharacteristicByInstance(characteristic)
self.logger.debug("%s:%s:%s discovered descriptors" % (p, s, c))
for d in characteristic._.descriptors:
descriptor = OSXBLEDescriptor(characteristic=c, instance=d)
c.addDescriptor(descriptor)
# Retrieving Characteristic and characteristic Descriptor Values
def peripheral_didUpdateValueForCharacteristic_error_(self, peripheral, characteristic, error):
self.didUpdateValueForCharacteristic(peripheral, characteristic, error)
@_notifyResp
def didUpdateValueForCharacteristic(self, peripheral, characteristic, error):
s = self.findServiceByCharacteristicInstance(characteristic)
p = s.peripheral
c = s.findCharacteristicByInstance(characteristic)
value = None
if error == nil:
# converting NSData to bytestring
value = bytes(characteristic._.value)
c._value = value
if c.notify:
c.handler.on_notify(c, value)
self.logger.debug("%s:%s:%s updated value: %s" % (p, s, c, pformat(value)))
else:
self.logger.debug("%s:%s:%s %s" % (p, s, c, str(error)))
def peripheral_didUpdateValueForDescriptor_error_(self, peripheral, descriptor, error):
self.didUpdateValueForDescriptor(peripheral, descriptor, error)
@_notifyResp
def didUpdateValueForDescriptor(self, peripheral, descriptor, error):
s = self.findServiceByDescriptorInstance(descriptor)
p = s.peripheral
c = self.findCharacteristicByDescriptorInstance(descriptor)
d = c.findDescriptorByInstance(descriptor)
value = None
if error == nil:
# converting NSData to bytes
value = bytes(descriptor._.value)
d.value = value
self.logger.info("%s:%s:%s:%s updated value: %s" % (p, s, c, d, pformat(value)))
else:
self.logger.error("%s:%s:%s:%s %s" % (p, s, c, d, str(error)))
# Writing Characteristic and Characteristic Descriptor Values
def peripheral_didWriteValueForCharacteristic_error_(self, peripheral, characteristic, error):
self.didWriteValueForCharacteristic(peripheral, characteristic, error)
@_notifyResp
def didWriteValueForCharacteristic(self, peripheral, characteristic, error):
s = self.findServiceByCharacteristicInstance(characteristic)
p = s.peripheral
c = s.findCharacteristicByInstance(characteristic)
if error == nil:
self.logger.debug("Characteristic Value Write Done")
else:
self.logger.error("Characteristic Value Write Fail")
def peripheral_didWriteValueForDescriptor_error_(self, peripheral, descriptor, error):
if error == nil:
self.logger.debug("Descriptor Value write Done")
else:
self.logger.debug("Descriptor Value write Fail")
# Managing Notifications for a Characteristic's Value
def peripheral_didUpdateNotificationStateForCharacteristic_error_(self, peripheral, characteristic, error):
self.didUpdateNotificationStateForCharacteristic(peripheral, characteristic, error)
@_notifyResp
def didUpdateNotificationStateForCharacteristic(self, peripheral, characteristic, error):
s = self.findServiceByCharacteristicInstance(characteristic)
p = s.peripheral
c = s.findCharacteristicByInstance(characteristic)
result = "Success"
if error != nil:
result = "Fail"
self.logger.info(error)
c._notify = False
else:
c._notify = True
self.logger.debug("%s:%s:%s set Notification %s" % (p, s, c, result))
# Retrieving a Peripheral's Received Signal Strength Indicator(RSSI) Data
def peripheralDidUpdateRSSI_error_(self, peripheral, error):
self.didUpdateRSSI(peripheral, error)
@_notifyResp
def didUpdateRSSI(self, peripheral, error):
if error == nil:
rssi = int(peripheral.RSSI())
if rssi == 127:
# RSSI value cannot be read
return
self.logger.debug("%s updated RSSI value: %d -> %d" % (self, self._rssi, rssi))
self.rssi = rssi
else:
print error
# Monitoring Changes to a Peripheral's Name or Services
def peripheralDidUpdateName_(self, peripheral):
self.logger.info("%s updated name " % self)
self.name = peripheral._.name
def peripheral_didModifyServices_(self, peripheral, invalidatedServices):
self.logger.debug("%s updated services" % self)
def __repr__(self):
if self.name:
return "Peripheral{%s (%s)}" % (self.name, str(self.UUID).upper())
else:
return "Peripheral{UNKNOWN (%s)}" % (str(self.UUID).upper())
def __str__(self):
return self.__repr__()
def __eq__(self, other):
return isinstance(other, self.__class__) and (other.UUID == self.UUID)
def __ne__(self, other):
return not self.__eq__(other)
| {
"repo_name": "brettchien/PyBLEWrapper",
"path": "pyble/osx/peripheral.py",
"copies": "1",
"size": "13349",
"license": "mit",
"hash": -2037063080758622000,
"line_mean": 35.5726027397,
"line_max": 156,
"alpha_frac": 0.6501610608,
"autogenerated": false,
"ratio": 4.018362432269717,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5168523493069717,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from PyObjCTools import AppHelper
class FileObserver(NSObject):
def initWithFileDescriptor_readCallback_errorCallback_(self,
fileDescriptor, readCallback, errorCallback):
self = self.init()
self.readCallback = readCallback
self.errorCallback = errorCallback
self.fileHandle = NSFileHandle.alloc().initWithFileDescriptor_(
fileDescriptor)
self.nc = NSNotificationCenter.defaultCenter()
self.nc.addObserver_selector_name_object_(
self,
'fileHandleReadCompleted:',
NSFileHandleReadCompletionNotification,
self.fileHandle)
self.fileHandle.readInBackgroundAndNotify()
return self
def fileHandleReadCompleted_(self, aNotification):
ui = aNotification.userInfo()
newData = ui.objectForKey_(NSFileHandleNotificationDataItem)
if newData is None:
if self.errorCallback is not None:
self.errorCallback(self, ui.objectForKey_(NSFileHandleError))
self.close()
else:
self.fileHandle.readInBackgroundAndNotify()
if self.readCallback is not None:
self.readCallback(self, str(newData))
def close(self):
self.nc.removeObserver_(self)
if self.fileHandle is not None:
self.fileHandle.closeFile()
self.fileHandle = None
# break cycles in case these functions are closed over
# an instance of us
self.readCallback = None
self.errorCallback = None
def __del__(self):
# Without this, if a notification fires after we are GC'ed
# then the app will crash because NSNotificationCenter
# doesn't retain observers. In this example, it doesn't
# matter, but it's worth pointing out.
self.close()
def prompt():
sys.stdout.write("write something: ")
sys.stdout.flush()
def gotLine(observer, aLine):
if aLine:
print "you wrote:", aLine.rstrip()
prompt()
else:
print ""
AppHelper.stopEventLoop()
def gotError(observer, err):
print "error:", err
AppHelper.stopEventLoop()
if __name__ == '__main__':
import sys
observer = FileObserver.alloc().initWithFileDescriptor_readCallback_errorCallback_(
sys.stdin.fileno(), gotLine, gotError)
prompt()
AppHelper.runConsoleEventLoop(installInterrupt=True)
| {
"repo_name": "ariabuckles/pyobjc-core",
"path": "Examples/Scripts/stdinreader.py",
"copies": "2",
"size": "2450",
"license": "mit",
"hash": 4929040414520839000,
"line_mean": 33.5070422535,
"line_max": 87,
"alpha_frac": 0.6465306122,
"autogenerated": false,
"ratio": 4.351687388987567,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5998218001187567,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from PyObjCTools import AppHelper
from CGraphModel import *
from CGraphView import *
from fieldMath import *
#____________________________________________________________
class CGraphController(NSObject):
graphModel = objc.IBOutlet()
graphView = objc.IBOutlet()
fieldNormalizeCheck = objc.IBOutlet()
settingDrawer = objc.IBOutlet()
fieldSlider0 = objc.IBOutlet()
fieldSlider1 = objc.IBOutlet()
fieldSlider2 = objc.IBOutlet()
phaseSlider0 = objc.IBOutlet()
phaseSlider1 = objc.IBOutlet()
phaseSlider2 = objc.IBOutlet()
spacingSlider = objc.IBOutlet()
fieldDisplay0 = objc.IBOutlet()
fieldDisplay1 = objc.IBOutlet()
fieldDisplay2 = objc.IBOutlet()
phaseDisplay0 = objc.IBOutlet()
phaseDisplay1 = objc.IBOutlet()
phaseDisplay2 = objc.IBOutlet()
RMSGainDisplay = objc.IBOutlet()
spacingDisplay = objc.IBOutlet()
#____________________________________________________________
# Update GUI display and control values
def awakeFromNib(self):
self.mapImage = NSImage.imageNamed_("Map")
self.graphView.setMapImage(self.mapImage)
self.drawGraph()
def drawGraph(self):
self.spacingDisplay.setFloatValue_(radToDeg(self.graphModel.getSpacing()))
self.spacingSlider.setFloatValue_(radToDeg(self.graphModel.getSpacing()))
self.fieldDisplay0.setFloatValue_(self.graphModel.getField(0))
self.fieldDisplay1.setFloatValue_(self.graphModel.getField(1))
self.fieldDisplay2.setFloatValue_(self.graphModel.getField(2))
self.fieldSlider0.setFloatValue_(self.graphModel.getField(0))
self.fieldSlider1.setFloatValue_(self.graphModel.getField(1))
self.fieldSlider2.setFloatValue_(self.graphModel.getField(2))
self.phaseDisplay0.setFloatValue_(radToDeg(self.graphModel.getPhase(0)))
self.phaseDisplay1.setFloatValue_(radToDeg(self.graphModel.getPhase(1)))
self.phaseDisplay2.setFloatValue_(radToDeg(self.graphModel.getPhase(2)))
self.phaseSlider0.setFloatValue_(radToDeg(self.graphModel.getPhase(0)))
self.phaseSlider1.setFloatValue_(radToDeg(self.graphModel.getPhase(1)))
self.phaseSlider2.setFloatValue_(radToDeg(self.graphModel.getPhase(2)))
totalField = self.graphModel.getField(0) + self.graphModel.getField(1) + self.graphModel.getField(2)
RMSGain = self.graphModel.fieldGain()
self.graphView.setGain(RMSGain, totalField)
self.RMSGainDisplay.setFloatValue_(RMSGain*100.0)
path, maxMag = self.graphModel.getGraph()
self.graphView.setPath(path, maxMag)
#____________________________________________________________
# Handle GUI values
@objc.IBAction
def fieldDisplay0_(self, sender):
self.setNormalizedField(0, sender.floatValue())
self.drawGraph()
@objc.IBAction
def fieldDisplay1_(self, sender):
self.setNormalizedField(1, sender.floatValue())
self.drawGraph()
@objc.IBAction
def fieldDisplay2_(self, sender):
self.setNormalizedField(2, sender.floatValue())
self.drawGraph()
@objc.IBAction
def fieldSlider0_(self, sender):
self.setNormalizedField(0, sender.floatValue())
self.drawGraph()
@objc.IBAction
def fieldSlider1_(self, sender):
self.setNormalizedField(1, sender.floatValue())
self.drawGraph()
@objc.IBAction
def fieldSlider2_(self, sender):
self.setNormalizedField(2, sender.floatValue())
self.drawGraph()
def setNormalizedField(self, t, v):
if self.fieldNormalizeCheck.intValue():
f = [0, 0, 0]
cft = 0
for i in range(3):
f[i] = self.graphModel.getField(i)
cft += f[i]
aft = cft - v
if aft < 0.001:
v = cft - 0.001
aft = 0.001
f[t] = v
nft = 0
for i in range(3):
nft += f[i]
r = aft / (nft - f[t])
for i in range(3):
self.graphModel.setField(i, f[i] * r)
self.graphModel.setField(t, v)
else:
self.graphModel.setField(t, v)
@objc.IBAction
def phaseDisplay0_(self, sender):
self.graphModel.setPhase(0, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def phaseDisplay1_(self, sender):
self.graphModel.setPhase(1, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def phaseDisplay2_(self, sender):
self.graphModel.setPhase(2, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def phaseSlider0_(self, sender):
self.graphModel.setPhase(0, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def phaseSlider1_(self, sender):
self.graphModel.setPhase(1, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def phaseSlider2_(self, sender):
self.graphModel.setPhase(2, degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def spacingDisplay_(self, sender):
self.graphModel.setSpacing(degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def spacingSlider_(self, sender):
self.graphModel.setSpacing(degToRad(sender.floatValue()))
self.drawGraph()
@objc.IBAction
def settingDrawerButton_(self, sender):
self.settingDrawer.toggle_(self)
| {
"repo_name": "Khan/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/FieldGraph/CGraphController.py",
"copies": "3",
"size": "5532",
"license": "mit",
"hash": 4565490706155292700,
"line_mean": 32.125748503,
"line_max": 108,
"alpha_frac": 0.6292480116,
"autogenerated": false,
"ratio": 3.5348242811501596,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.566407229275016,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from PyObjCTools.TestSupport import *
import Foundation
try:
unicode
except NameError:
unicode = str
class TestHelper (NSObject):
def incFoo_(self, foo):
foo[0] += 1
class TestNSUndoManager(TestCase):
def testUndoManager(self):
x = TestHelper.new()
m = NSUndoManager.new()
l = [ 0 ]
m.prepareWithInvocationTarget_(x).incFoo_(l)
m.undo()
self.assertEqual(l[0], 1)
def __del__(self, objc=objc):
objc.recycleAutoreleasePool()
## Undo Integer test
## From David Eppstein
# test ability of int argument to pass through undo and then
# be used as parameter to another routine expecting an int
#
# the actual routine I want to use is
# NSTableView.editColumn_row_withEvent_select_
# but that involves setting up a UI; instead use NSIndexSpecifier
if hasattr(Foundation, 'NSIndexSpecifier'):
class TestUndoInt(TestCase):
class UndoInt(NSObject):
undo = NSUndoManager.alloc().init()
idx = NSIndexSpecifier.alloc().init()
idx.setIndex_(0)
def test_(self,i):
self.undo.prepareWithInvocationTarget_(self).test_(self.idx.index())
self.idx.setIndex_(i)
def testUndoInt(self):
# test that undo works
x = TestUndoInt.UndoInt.alloc().init()
x.test_(3)
assert(x.idx.index() == 3)
x.undo.undo()
assert(x.idx.index() == 0)
## end Undo Integer test
class TestSubclassingUndo(TestCase):
# Bugreport: 678759 Subclassing NSUndoManager fails
def testSubclass(self):
class UndoSubclass (NSUndoManager):
pass
x = TestHelper.new()
m = UndoSubclass.new()
l = [ 0 ]
m.prepareWithInvocationTarget_(x).incFoo_(l)
m.undo()
self.assertEqual(l[0], 1)
def testConstants(self):
self.assertIsInstance(NSUndoManagerCheckpointNotification, unicode)
self.assertIsInstance(NSUndoManagerWillUndoChangeNotification, unicode)
self.assertIsInstance(NSUndoManagerWillRedoChangeNotification, unicode)
self.assertIsInstance(NSUndoManagerDidUndoChangeNotification, unicode)
self.assertIsInstance(NSUndoManagerDidRedoChangeNotification, unicode)
self.assertIsInstance(NSUndoManagerDidOpenUndoGroupNotification, unicode)
self.assertIsInstance(NSUndoManagerWillCloseUndoGroupNotification, unicode)
self.assertEqual(NSUndoCloseGroupingRunLoopOrdering, 350000)
@min_os_level('10.7')
def testConstants10_7(self):
self.assertIsInstance(NSUndoManagerGroupIsDiscardableKey, unicode)
self.assertIsInstance(NSUndoManagerDidCloseUndoGroupNotification, unicode)
def testMethods(self):
self.assertResultIsBOOL(NSUndoManager.isUndoRegistrationEnabled)
self.assertResultIsBOOL(NSUndoManager.groupsByEvent)
self.assertArgIsBOOL(NSUndoManager.setGroupsByEvent_, 0)
self.assertResultIsBOOL(NSUndoManager.canUndo)
self.assertResultIsBOOL(NSUndoManager.canRedo)
self.assertResultIsBOOL(NSUndoManager.isUndoing)
self.assertResultIsBOOL(NSUndoManager.isRedoing)
self.assertArgIsSEL(NSUndoManager.registerUndoWithTarget_selector_object_, 1, b'v@:@')
@min_os_level('10.7')
def testMethods10_7(self):
self.assertArgIsBOOL(NSUndoManager.setActionIsDiscardable_, 0)
self.assertResultIsBOOL(NSUndoManager.undoActionIsDiscardable)
self.assertResultIsBOOL(NSUndoManager.redoActionIsDiscardable)
if __name__ == '__main__':
main( )
| {
"repo_name": "Khan/pyobjc-framework-Cocoa",
"path": "PyObjCTest/test_nsundomanager.py",
"copies": "3",
"size": "3623",
"license": "mit",
"hash": 5187678662994484000,
"line_mean": 33.179245283,
"line_max": 94,
"alpha_frac": 0.6892078388,
"autogenerated": false,
"ratio": 3.813684210526316,
"config_test": true,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6002892049326316,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
from PyObjCTools.TestSupport import *
try:
unicode
except NameError:
unicode = str
try:
long
except NameError:
long = int
class TestNSRange (TestCase):
def testStructs(self):
v = NSRange()
self.assertHasAttr(v, 'location')
self.assertHasAttr(v, 'length')
def testFunctions(self):
v = NSMakeRange(1, 4)
self.assertIsInstance(v, NSRange)
self.assertIsInstance(v.location, (int, long))
self.assertIsInstance(v.length, (int, long))
self.assertEqual(v.location, 1)
self.assertEqual(v.length, 4)
self.assertEqual(NSMaxRange(v), 5)
self.assertResultIsBOOL(NSLocationInRange)
self.assertIs(NSLocationInRange(3, v), True)
self.assertIs(NSLocationInRange(15, v), False)
self.assertResultIsBOOL(NSEqualRanges)
self.assertIs(NSEqualRanges(v, v), True)
v = NSUnionRange((1, 3), (5, 10))
self.assertIsInstance(v, NSRange)
v = NSIntersectionRange((1, 4), (3, 5))
self.assertIsInstance(v, NSRange)
v = NSStringFromRange((9, 10))
self.assertIsInstance(v, unicode)
w = NSRangeFromString(v)
self.assertIsInstance(w, NSRange)
self.assertEqual(w, (9, 10))
self.assertResultHasType(NSValue.rangeValue, NSRange.__typestr__)
if __name__ == "__main__":
main()
| {
"repo_name": "albertz/music-player",
"path": "mac/pyobjc-framework-Cocoa/PyObjCTest/test_nsrange.py",
"copies": "3",
"size": "1400",
"license": "bsd-2-clause",
"hash": -7704221615900855000,
"line_mean": 25.9230769231,
"line_max": 73,
"alpha_frac": 0.6292857143,
"autogenerated": false,
"ratio": 3.5714285714285716,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0007122507122507122,
"num_lines": 52
} |
from Foundation import *
from ToDoCell import *
from ToDoItem import *
from SelectionNotifyMatrix import *
ToDoItemChangedNotification = "ToDoItemChangedNotification"
class ToDoDocument (NSDocument):
calendar = objc.IBOutlet()
dayLabel = objc.IBOutlet()
itemList = objc.IBOutlet()
statusList = objc.IBOutlet()
__slots__ = ('_dataFromFile', '_activeDays', '_currentItems', '_selectedItem', '_selectedItemEdited')
def rowSelected_(self, notification):
row = notification.object().selectedRow()
if row == -1:
#print 'No rowSelected?'
return
self._selectedItem = self._currentItems.objectAtIndex_(row)
if not isinstance(self._selectedItem, ToDoItem):
self._selectedItem = None
NSNotificationCenter.defaultCenter().postNotificationName_object_userInfo_(ToDoItemChangedNotification, self._selectedItem, None)
def init(self):
NSDocument.init(self)
self._activeDays = None
self._currentItems = None
self._selectedItem = None
self._selectedItemEdited = 0
self._dataFromFile = None
return self
def __del__(self): # dealloc in Objective-C code
NSNotificationCenter.defaultCenter().removeObserver_(self)
def selectedItem(self):
return self._selectedItem
def windowNibName(self):
return "ToDoDocument"
def windowControllerDidLoadNib_(self, aController):
# NSDocument.windowControllerDidLoadNib_(self, aController)
self.setHasUndoManager_(0)
self.itemList.setDelegate_(self)
index = self.statusList.cells().count()
while index:
index -= 1
aCell = ToDoCell.alloc().init()
aCell.setTarget_(self)
aCell.setAction_('itemStatusClicked:')
self.statusList.putCell_atRow_column_(aCell, index, 0)
if self._dataFromFile:
self.loadDocWithData_(self._dataFromFile)
self._dataFromFile = None
else:
self.loadDocWithData_(None)
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, 'rowSelected:', RowSelectedNotification, self.itemList)
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, 'rowSelected:', RowSelectedNotification, self.statusList)
def loadDocWithData_(self, data):
if data:
dct = NSUnarchiver.unarchiveObjectWithData_(data)
self.initDataModelWithDictinary_(dct)
dayEnum = self._activeDays.keyEnumerator()
now = NSDate.date()
itemDate = dayEnum.nextObject()
while itemDate:
itemArray = self._activeDays.objectForKey_(itemDate)
itemEnum = itemArray.objectEnumerator()
anItem = itemEnum.nextObject()
while anItem:
if (isinstance(anItem, ToDoItem)
and anItem.secsUntilNotify()
and anItem.status() == INCOMPLETE):
due = anItem.day().addTimeInterfval_(anItem.secondsUntilDue())
elapsed = due.timeIntervalSinceDate_(now)
if elapsed > 0:
self.setTimerForItem_(anItem)
else:
#print "Past due"
NSBeep()
NSRunAlertPanel("To Do", "%s on %s is past due!"%(
anItem.itemName(),
due.descriptionWithCalendarFormat_timeZone_locale_(
"%b %d, %Y at %I:%M %p",
NSTimeZone.localTimeZone(),
None
)
), None, None, None)
anItem.setSecsUntilNotify_(0)
anItem = itemEnum.nextObject()
itemDate = dayEnum.nextObject()
else:
self.initDataModelWithDictionary_(None)
self.selectItemAtRow_(0)
self.updateLists()
self.dayLabel.setStringValue_(
self.calendar.selectedDay().descriptionWithCalendarFormat_timeZone_locale_(
"To Do on %a %B %d %Y",
NSTimeZone.defaultTimeZone(),
None))
def initDataModelWithDictionary_(self, aDict):
if aDict:
self._activeDays = aDict
else:
self._activeDays = NSMutableDictionary.alloc().init()
date = self.calendar.selectedDay()
self.setCurrentItems_(self._activeDays.objectForKey_(date))
def setCurrentItems_(self, newItems):
if newItems:
self._currentItems = newItems.mutableCopy()
else:
numRows, numCols = self.itemList.getNumberOfRows_columns_(None, None)
self._currentItems = NSMutableArray.alloc().initWithCapacity_(numRows)
for d in range(numRows):
self._currentItems.addObject_("")
def updateLists(self):
numRows = self.itemList.cells().count()
for i in range(numRows):
if self._currentItems:
thisItem = self._currentItems.objectAtIndex_(i)
else:
thisItem = None
#print ">>> object %d is %s %s"%(i, thisItem, isinstance(thisItem, ToDoItem))
if isinstance(thisItem, ToDoItem):
if thisItem.secsUntilDue():
due = thisItem.day().addTimeInterval_(thisItem.secsUntilDue())
else:
due = None
self.itemList.cellAtRow_column_(i, 0).setStringValue_(thisItem.itemName())
self.statusList.cellAtRow_column_(i, 0).setTimeDue_(due)
self.statusList.cellAtRow_column_(i, 0).setTriState_(thisItem.status())
else:
self.itemList.cellAtRow_column_(i, 0).setStringValue_("")
self.statusList.cellAtRow_column_(i, 0).setTitle_("")
self.statusList.cellAtRow_column_(i, 0).setImage_(None)
def saveDocItems(self):
if self._currentItems:
cnt = self._currentItems.count()
for i in range(cnt):
anItem = self._currentItems.objectAtIndex_(i)
if isinstance(anItem, ToDoItem):
self._activeDays.setObject_forKey_(self._currentItems, anItem.day())
break
def controlTextDidEndEditing_(self, notif):
if not self._selectedItemEdited:
return
row = self.itemList.selectedRow()
newName = self.itemList.selectedCell().stringValue()
if isinstance(self._currentItems.objectAtIndex_(row), ToDoItem):
prevNameAtIndex = self._currentItems.objectAtIndex_(row).itemName()
if newName == "":
self._currentItems.replaceObjectAtRow_withObject_(row, "")
elif prevNameAtIndex != newName:
self._currentItems.objectAtRow_(row).setItemName_(newName)
elif newName != "":
newItem = ToDoItem.alloc().initWithName_andDate_(newName, self.calendar.selectedDay())
self._currentItems.replaceObjectAtIndex_withObject_(row, newItem)
self._selectedItem = self._currentItems.objectAtIndex_(row)
if not isinstance(self._selectedItem, ToDoItem):
self._selectedItem = None
self.updateLists()
self._selectedItemEdited = 0
self.updateChangeCount_(NSChangeDone)
NSNotificationCenter.defaultCenter(
).postNotificationName_object_userInfo_(
ToDoItemChangedNotification, self._selectedItem, None)
def selectedItemModified(self):
if self._selectedItem:
self.setTimerForItem_(self._selectedItem)
self.updateLists()
self.updateChangeCount_(NSChangeDone)
def calendarMatrix_didChangeToDate_(self, matrix, date):
self.saveDocItems()
if self._activeDays:
self.setCurrentItems_(self._activeDays.objectForKey_(date))
else:
#print "calenderMatrix:didChangeToDate: -> no _activeDays"
pass
self.dayLabel.setStringValue_(
date.descriptionWithCalendarFormat_timeZone_locale_(
"To Do on %a %B %d %Y", NSTimeZone.defaultTimeZone(),
None))
self.updateLists()
self.selectedItemAtRow_(0)
def selectedItemAtRow_(self, row):
self.itemList.selectCellAtRow_column_(row, 0)
def controlTextDidBeginEditing_(self, notif):
self._selectedItemEdited = 1
def dataRepresentationOfType_(self, aType):
self.saveDocItems()
return NSArchiver.archivedDataWithRootObject_(self._activeDays)
def loadRepresentation_ofType_(self, data, aType):
if selfcalendar:
self.loadDocWithData_(data)
else:
self._dataFromFile = data
return 1
@objc.IBAction
def itemStatusClicked_(self, sender):
row = sender.selectedRow()
cell = sender.cellAtRow_column_(row, 0)
item = self._currentItems.objectAtIndex_(row)
if isinstance(item, ToDoItem):
# print "changing status to", cell.triState()
item.setStatus_(cell.triState())
self.setTimerForItem_(item)
self.updateLists()
self.updateChangeCount_(NSChangeDone)
NSNotificationCenter.defaultCenter().postNotificationName_object_userInfo_(
ToDoItemChangedNotification, item, None)
def setTimerForItem_(self, anItem):
if anItem.secsUntilNotify() and anItem.status() == INCOMPLETE:
notifyDate = anItem.day().addTimeInterval_(anItem.secsUntilDue() - anItem.secsUntilNotify())
aTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
notifyDate.timeIntervalSinceNow(),
self,
'itemTimerFired:',
anItem,
False)
anItem.setTimer_(aTimer)
else:
anItem.setTimer_(None)
def itemTimerFired_(self, timer):
#print "Timer fired for ", timer
anItem = timer.userInfo()
dueDate = anItem.day().addTimeInterval_(anItem.secsUntilDue())
NSBeep()
NSRunAlertPanel("To Do", "%s on %s"%(
anItem.itemName(), dueDate.descriptionWithCalendarFormat_timeZone_locale_(
"%b %d, %Y at %I:%M: %p", NSTimeZone.defaultTimeZone(), None),
), None, None, None)
anItem.setSecsUntilNotify_(0)
self.setTimerForItem_(anItem)
self.updateLists()
NSNotificationCenter.defaultCenter().postNotificationName_object_userInfo_(
ToDoItemChangedNotification,
anItem,
None)
def selectItemAtRow_(self, row):
self.itemList.selectCellAtRow_column_(row, 0)
if __name__ == "__main__":
x = ToDoDocument.alloc()
print x
print x.init()
| {
"repo_name": "Khan/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/Todo/ToDoDocument.py",
"copies": "3",
"size": "11139",
"license": "mit",
"hash": 5916706144950790000,
"line_mean": 35.5213114754,
"line_max": 142,
"alpha_frac": 0.5874854116,
"autogenerated": false,
"ratio": 4.25802752293578,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0018908134887622163,
"num_lines": 305
} |
from Foundation import *
import objc
class RPCMethod(NSObject):
def initWithDocument_name_(self, aDocument, aName):
self = super(RPCMethod, self).init()
self.document = aDocument
self.k_methodName = aName
self.k_methodSignature = None
self.k_methodDescription = None
return self
def methodName(self):
return self.k_methodName
def displayName(self):
if self.k_methodSignature is None:
return self.k_methodName
else:
return self.k_methodSignature
def setMethodSignature_(self, aSignature):
self.k_methodSignature = aSignature
setMethodSignature_ = objc.accessor(setMethodSignature_)
def methodDescription(self):
if self.k_methodDescription is None:
self.setMethodDescription_(u"<description not yet received>")
self.document.fetchMethodDescription_(self)
return self.k_methodDescription
def setMethodDescription_(self, aDescription):
self.k_methodDescription = aDescription
setMethodDescription_ = objc.accessor(setMethodDescription_)
| {
"repo_name": "albertz/music-player",
"path": "mac/pyobjc-framework-Cocoa/Examples/Twisted/WebServicesTool-CocoaBindings/RPCMethod.py",
"copies": "3",
"size": "1123",
"license": "bsd-2-clause",
"hash": -769448619926685700,
"line_mean": 32.0294117647,
"line_max": 73,
"alpha_frac": 0.679430098,
"autogenerated": false,
"ratio": 4.352713178294573,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6532143276294573,
"avg_score": null,
"num_lines": null
} |
from Foundation import *
# enum ToDoItemStatus
INCOMPLETE=0
COMPLETE=1
DEFER_TO_NEXT_DAY=2
SECS_IN_MINUTE=60
SECS_IN_HOUR=SECS_IN_MINUTE*60
SECS_IN_DAY=SECS_IN_HOUR*24
SECS_IN_WEEK=SECS_IN_DAY*7
class ToDoItem (NSObject):
__slots__ = (
'_day',
'_itemName',
'_notes',
'_timer',
'_secsUntilDue',
'_secsUntilNotify',
'_status',
)
def init(self):
self = NSObject.init(self)
if not self:
return None
self._day = None
self._itemName = None
self._notes = None
self._secsUntilDue = 0
self._secsUntilNotify = 0
self._status = None
self._timer = None
def description(self):
descr = """%s
\tName: %s
\tNotes: %s
\tCompleted: %s
\tSecs Until Due: %d
\tSecs Until Notify: %d
"""%(
super.description(),
self.itemName(),
self._day,
self._notes,
['No', 'YES'][self.status() == COMPLETE],
self._secsUntilDue,
self._secsUntilNotify)
return descr
def initWithName_andDate_(self, aName, aDate):
self = NSObject.init(self)
if not self:
return None
self._day = None
self._itemName = None
self._notes = None
self._secsUntilDue = 0
self._secsUntilNotify = 0
self._status = None
self._timer = None
if not aName:
return None
self.setItemName_(aName)
if aDate:
self.setDay_(aDate)
else:
now = NSCalendarDate.date()
self.setDay_(
NSCalendarDate.dateWithYear_month_day_hour_minute_second_timeZone_(
now.yearOfCommonEra(), now.monthOfYear(), now.dayOfMonth(), 0, 0, 0,
NSTimeZone.localTimeZone()))
self.setStatus_(INCOMPLETE)
self.setNotes_("")
return self
def encodeWithCoder_(self, coder):
coder.encodeObject_(self._day)
coder.encodeObject_(self._itemName)
coder.encodeObject_(self._notes)
tempTime = self._secsUntilDue
coder.encodeValueOfObjCType_at_(objc._C_LNG, tempTime)
tempTime = self._secsUntilNotify
coder.encodeValueOfObjCType_at_(objc._C_LNG, tempTime)
tempStatus = self._status
coder.encodeValueOfObjCType_at_(objc._C_INT, tempStatus)
def initWithCoder_(self, coder):
self.setDay_(coder.decodeObject())
self.setItemName_(coder.decodeObject())
self.setNotes_(coder.decodeObject())
tempTime = coder.decodeObjectOfObjCType_at_(objc._C_LNG)
self.setSecsUntilDue_(tempTime)
tempTime = coder.decodeObjectOfObjCType_at_(objc._C_LNG)
self.setSecsUntilNotify_(tempTime)
tempStatus = coder.decodeObjectOfObjCType_at_(objc._C_INT)
self.setSecsUntilNotify_(tempStatus)
return self
def __del__(self): # dealloc
if self._notes:
self._timer.invalidate()
def setDay_(self, newDay):
self._day = newDay
def day(self):
return self._day
def setItemName_(self, newName):
self._itemName = newName
def itemName(self):
return self._itemName
def setNotes_(self, newNotes):
self._notes = newNotes
def notes(self):
return self._notes
def setTimer_(self, newTimer):
if self._timer:
self._timer.invalidate()
if newTimer:
self._timer = newTimer
else:
self._timer = None
def timer(self):
return self._timer
def setStatus_(self, newStatus):
self._status = newStatus
def status(self):
return self._status
def setSecsUntilDue_(self, secs):
self._secsUntilDue = secs
def secsUntilDue(self):
return self._secsUntilDue
def setSecsUntilNotify_(self, secs):
self._secsUntilNotify = secs
def secsUntilNotify(self):
return self._secsUntilNotify
def ConvertTimeToSeconds(hour, minute, pm):
if hour == 12:
hour = 0
if pm:
hour += 12
return (hour * SECS_IN_HOUR) + (minute * SECS_IN_MINUTE)
def ConvertSecondsToTime(secs):
pm = 0
hour = secs / SECS_IN_HOUR
if hour > 11:
hour -= 12
pm = 1
if hour == 0:
hour = 12
minute = (secs % SECS_IN_HOUR) / SECS_IN_MINUTE
return (hour, minute, pm)
| {
"repo_name": "albertz/music-player",
"path": "mac/pyobjc-framework-Cocoa/Examples/AppKit/Todo/ToDoItem.py",
"copies": "3",
"size": "4451",
"license": "bsd-2-clause",
"hash": 2305598237088146200,
"line_mean": 22.0621761658,
"line_max": 84,
"alpha_frac": 0.5708829477,
"autogenerated": false,
"ratio": 3.627546862265689,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5698429809965688,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSBundle
import halfcaff.util
APPDIR = None
if not halfcaff.util.is_dev_mode():
APPDIR = NSBundle.mainBundle().bundlePath()
def is_login_enabled():
if not APPDIR:
return False
return APPDIR in list_login_items()
def enable_startup_at_login():
add_login_item(APPDIR)
def disable_startup_at_login():
remove_login_item(APPDIR)
#### From https://github.com/pudquick/pyLoginItems/
# /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Headers/LSSharedFileList.h
# Fun things:
# kLSSharedFileListFavoriteItems
# kLSSharedFileListFavoriteVolumes
# kLSSharedFileListRecentApplicationItems
# kLSSharedFileListRecentDocumentItems
# kLSSharedFileListRecentServerItems
# kLSSharedFileListSessionLoginItems
# kLSSharedFileListGlobalLoginItems - deprecated in 10.9
# Runs in user space, use this with a login script / launchd item / something running as the user
# Example usage:
#
# import pyLoginItems
# >>> pyLoginItems.list_login_items()
# [u'/Applications/Dropbox.app', u'/Applications/iTunes.app/Contents/MacOS/iTunesHelper.app']
#
# pyLoginItems.add_login_item('/Applications/Safari.app', 0)
# pyLoginItems.remove_login_item('/Applications/TextEdit.app')
from platform import mac_ver
from Foundation import NSURL
from LaunchServices import kLSSharedFileListSessionLoginItems, kLSSharedFileListNoUserInteraction
# Need to manually load in 10.11.x+
os_vers = int(mac_ver()[0].split('.')[1])
if os_vers > 10:
from Foundation import NSBundle
import objc
SFL_bundle = NSBundle.bundleWithIdentifier_('com.apple.coreservices.SharedFileList')
functions = [('LSSharedFileListCreate', '^{OpaqueLSSharedFileListRef=}^{__CFAllocator=}^{__CFString=}@'),
('LSSharedFileListCopySnapshot', '^{__CFArray=}^{OpaqueLSSharedFileListRef=}o^I'),
('LSSharedFileListItemCopyDisplayName', '^{__CFString=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListItemResolve', 'i^{OpaqueLSSharedFileListItemRef=}Io^^{__CFURL=}o^{FSRef=[80C]}'),
('LSSharedFileListItemMove', 'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListItemRemove', 'i^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}'),
('LSSharedFileListInsertItemURL', '^{OpaqueLSSharedFileListItemRef=}^{OpaqueLSSharedFileListRef=}^{OpaqueLSSharedFileListItemRef=}^{__CFString=}^{OpaqueIconRef=}^{__CFURL=}^{__CFDictionary=}^{__CFArray=}'),
('kLSSharedFileListItemBeforeFirst', '^{OpaqueLSSharedFileListItemRef=}'),
('kLSSharedFileListItemLast', '^{OpaqueLSSharedFileListItemRef=}'),]
objc.loadBundleFunctions(SFL_bundle, globals(), functions)
else:
from LaunchServices import kLSSharedFileListItemBeforeFirst, kLSSharedFileListItemLast, \
LSSharedFileListCreate, LSSharedFileListCopySnapshot, \
LSSharedFileListItemCopyDisplayName, LSSharedFileListItemResolve, \
LSSharedFileListItemMove, LSSharedFileListItemRemove, \
LSSharedFileListInsertItemURL
def _get_login_items():
# Setup the type of shared list reference we want
list_ref = LSSharedFileListCreate(None, kLSSharedFileListSessionLoginItems, None)
# Get the user's login items - actually returns two values, with the second being a seed value
# indicating when the snapshot was taken (which is safe to ignore here)
login_items,_ = LSSharedFileListCopySnapshot(list_ref, None)
return [list_ref, login_items]
def _get_item_cfurl(an_item, flags=None):
if flags is None:
# Attempt to resolve the items without interacting or mounting
flags = kLSSharedFileListNoUserInteraction + kLSSharedFileListNoUserInteraction
err, a_CFURL, a_FSRef = LSSharedFileListItemResolve(an_item, flags, None, None)
return a_CFURL
def list_login_items():
# Attempt to find the URLs for the items without mounting drives
URLs = []
for an_item in _get_login_items()[1]:
URLs.append(_get_item_cfurl(an_item).path())
return URLs
def remove_login_item(path_to_item):
current_paths = list_login_items()
if path_to_item in current_paths:
list_ref, current_items = _get_login_items()
i = current_paths.index(path_to_item)
target_item = current_items[i]
result = LSSharedFileListItemRemove(list_ref, target_item)
def add_login_item(path_to_item, position=-1):
# position:
# 0..N: Attempt to insert at that index position, with 0 being first
# -1: Insert as last item
# Note:
# If the item is already present in the list, it will get moved to the new location automatically.
list_ref, current_items = _get_login_items()
added_item = NSURL.fileURLWithPath_(path_to_item)
if position == 0:
# Seems to be buggy, will force it below
destination_point = kLSSharedFileListItemBeforeFirst
elif position == -1:
destination_point = kLSSharedFileListItemLast
elif position >= len(current_items):
# At or beyond to the end of the current list
position = -1
destination_point = kLSSharedFileListItemLast
else:
# 1 = after item 0, 2 = after item 1, etc.
destination_point = current_items[position - 1]
# The logic for LSSharedFileListInsertItemURL is generally fine when the item is not in the list
# already (with the exception of kLSSharedFileListItemBeforeFirst which appears to be broken, period)
# However, if the item is already in the list, the logic gets really really screwy.
# Your index calculations are invalidated by OS X because you shift an item, possibly shifting the
# indexes of other items in the list.
# It's easier to just remove it first, then re-add it.
current_paths = list_login_items()
if (len(current_items) == 0) or (position == -1):
# Either there's nothing there or it wants to be last
# Just add the item, it'll be fine
result = LSSharedFileListInsertItemURL(list_ref, destination_point, None, None, added_item, {}, [])
elif (position == 0):
# Special case - kLSSharedFileListItemBeforeFirst appears broken on (at least) 10.9
# Remove if already in the list
if path_to_item in current_paths:
i = current_paths.index(path_to_item)
old_item = current_items[i]
result = LSSharedFileListItemRemove(list_ref, old_item)
# Regenerate list_ref and items
list_ref, current_items = _get_login_items()
if (len(current_items) == 0):
# Simple case if nothing remains in the list
result = LSSharedFileListInsertItemURL(list_ref, destination_point, None, None, added_item, {}, [])
else:
# At least one item remains.
# The fix for the bug is:
# - Add our item after the first ('needs_fixing') item
# - Move the 'needs_fixing' item to the end
# - Move the 'needs_fixing' item after our added item (which is now first)
needs_fixing = _get_item_cfurl(current_items[0])
# Move our item
result = LSSharedFileListInsertItemURL(list_ref, current_items[0], None, None, added_item, {}, [])
if not (result is None):
# Only shift if the first insert worked
# Regenerate list_ref and items
list_ref, current_items = _get_login_items()
# Now move the old item last
result = LSSharedFileListInsertItemURL(list_ref, kLSSharedFileListItemLast, None, None, needs_fixing, {}, [])
# Regenerate list_ref and items
list_ref, current_items = _get_login_items()
# Now move the old item back under the new one
result = LSSharedFileListInsertItemURL(list_ref, current_items[0], None, None, needs_fixing, {}, [])
else:
# We're aiming for an index based on something else in the list.
# Only do something if we're not aiming at ourselves.
insert_after_path = _get_item_cfurl(destination_point).path()
if (insert_after_path != path_to_item):
# Seems to be a different file
if path_to_item in current_paths:
# Remove our object if it's already present
i = current_paths.index(path_to_item)
self_item = current_items[i]
result = LSSharedFileListItemRemove(list_ref, self_item)
# Regenerate list_ref and items
list_ref, current_items = _get_login_items()
# Re-find our original target
current_paths = list_login_items()
i = current_paths.index(insert_after_path)
destination_point = current_items[i]
# Add ourselves after the file
result = LSSharedFileListInsertItemURL(list_ref, destination_point, None, None, added_item, {}, [])
| {
"repo_name": "dougn/HalfCaff",
"path": "halfcaff/login.py",
"copies": "1",
"size": "9234",
"license": "mit",
"hash": -6490095444801592000,
"line_mean": 49.7417582418,
"line_max": 230,
"alpha_frac": 0.6626597358,
"autogenerated": false,
"ratio": 3.7248890681726503,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.48875488039726506,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSBundle, NSLog
import urllib, urllib2
import sys
import os
import json
import base64
import glob
#sensorpath = os.path.join("~", "Documents", "VMware", "WorkspaceONESensorMigration") #"~/Documents/VMware/WorkspaceOneSensorMigration/"
sensorpath = "SensorData/"
def oslog(text):
try:
NSLog('[SensorMigrator] ' + str(text))
except Exception as e: #noqa
print(e)
#print('[SensorMigrator] ' + str(text))
def getCAProfiles(auth, settings):
#Get Profile List
responselist = getProfileList(auth, settings)
profilelist = responselist['ProfileList']
for profile in profilelist:
# print(profile)
profileData = getProfileById(auth, settings, profile)
assignments = profile["AssignmentSmartGroups"]
converted = convertToSensor(profileData, profile["OrganizationGroupUuid"], assignments)
converted["query_type"] = determineLanguage(converted)
converted["script_data"] = base64.b64decode(converted["script_data"]).decode('utf-8')
saveToFile(converted)
def determineLanguage(data):
script = base64.b64decode(data["script_data"]).decode('utf-8')
first = script.partition('\n')[0]
if ("#!/" in first):
if ("zsh" in first):
return "ZSH"
elif ("python" in first):
return "PYTHON"
else:
return "BASH"
else:
return "BASH"
def saveToFile(data):
filename = data["name"] + ".json"
filepath = os.path.join(sensorpath, filename)
with open(filepath, 'w+') as outfile:
json.dump(data, outfile)
def convertName(name):
if name[0].isdigit():
name += name[0]
name = name[1:]
name = name.strip()
name = name.lower()
name = name.replace('-', '')
name = " ".join(name.split())
name = name.replace(' ', '_')
return name
def getProfileList(auth, settings):
apiendpoint = '/api/mdm/profiles/search?platform=AppleOsX&status=Active&payloadName=CustomAttribute&pagesize=500'
url = 'https://' + settings['APIServer'] + apiendpoint
headers = {'Authorization':auth,
'AW-Tenant-Code':settings["APIKey"],
'Accept':'application/json;version=2',
'Content-Type': 'application/json;version=2'}
try:
oslog("Getting Profile List...")
req = urllib2.Request(url=url, headers=headers)
resp = urllib2.urlopen(req).read()
ProfileData = json.loads(resp)
oslog("Proile List successfully retrieved.")
return ProfileData
except Exception as err:
oslog(err)
def getProfileById(auth, settings, profile):
apiendpoint = '/api/mdm/profiles/'
url = 'https://' + settings['APIServer'] + apiendpoint + str(profile['ProfileId'])
headers = {'Authorization':auth,
'AW-Tenant-Code':settings["APIKey"],
'Accept':'application/json;version=2',
'Content-Type': 'application/json;version=2'}
try:
oslog("Getting info for Profile: " + profile["ProfileName"])
req = urllib2.Request(url=url, headers=headers)
resp = urllib2.urlopen(req).read()
ProfileData = json.loads(resp)
oslog("Info retrieved successfully.")
return ProfileData
except Exception as err:
oslog(err)
def getSmartGroupUUID(auth, settings, SmartGroup):
apiendpoint = '/api/mdm/smartgroups/' + str(SmartGroup["Id"])
url = 'https://' + settings['APIServer'] + apiendpoint
headers = {'Authorization':auth,
'AW-Tenant-Code':settings["APIKey"],
'Accept':'application/json;version=2',
'Content-Type': 'application/json;version=2'}
try:
oslog("Getting Smart Group UUID for: " + SmartGroup["Name"])
req = urllib2.Request(url=url, headers=headers)
resp = urllib2.urlopen(req).read()
SGData = json.loads(resp)
oslog("Smart Group UUID: " + SGData["SmartGroupUuid"])
return SGData["SmartGroupUuid"]
except Exception as err:
oslog(err)
def convertToSensor(profile, ogUUID, assignments):
name = convertName(profile["CustomAttributes"][0]["AttributeName"])
description = profile["General"]["Description"]
data = profile["CustomAttributes"][0]["AttributeScript"]
if "Events" in profile["CustomAttributes"][0]:
triggerType = "EVENT"
triggers = profile["CustomAttributes"][0]["Events"]
else:
triggerType = "SCHEDULE"
triggers = []
newTriggers = []
for t in triggers:
newTriggers.append(convertName(t))
triggers = newTriggers
d = {"name": name,
"description": description,
"platform": "APPLE_OSX",
"query_type": "BASH",
"query_response_type": "STRING",
"organization_group_uuid": ogUUID,
"execution_context": "SYSTEM",
"execution_architecture": "EITHER64OR32BIT",
"script_data": data,
"trigger_type": triggerType,
"event_triggers": triggers,
"smart_groups": assignments
}
return d
def uploadSensors(auth, settings):
for filename in glob.glob(os.path.join(sensorpath, '*.json')):
oslog("Found Sensor Data: " + filename)
with open(filename) as sensorData_file:
sensorData = json.load(sensorData_file)
SensorInfo = createSensor(auth, settings, sensorData)
if SensorInfo is not None and settings["KeepSensorAssignment"] == 1:
AssignmentInfo = assignSensor(auth, settings, SensorInfo["uuid"], sensorData)
def getAuth(username, password):
auth_s = username + ":" + password
auth = bytes(auth_s)
return 'Basic ' + base64.b64encode(auth).decode('utf-8')
def createSensor(auth, settings, sensorData):
url = 'https://' + settings["APIServer"] + '/api/mdm/devicesensors/'
d = {"name": sensorData["name"],
"description": sensorData["description"],
"platform": "APPLE_OSX",
"query_type": sensorData["query_type"],
"query_response_type": sensorData["query_response_type"],
"trigger_type": "UNKNOWN",
"organization_group_uuid": sensorData["organization_group_uuid"],
"execution_context": sensorData["execution_context"],
"execution_architecture": "EITHER64OR32BIT",
"script_data": base64.b64encode(sensorData["script_data"]).decode('utf-8'),
"timeout": 0,
"event_trigger": [
0
],
"schedule_trigger": "UNKNOWN"
}
data = json.dumps(d).encode("utf-8")
headers = {'Authorization':auth,
'AW-Tenant-Code':settings["APIKey"],
'Accept':'application/json;version=2',
'Content-Type': 'application/json'}
try:
oslog("Creating Sensor...")
req = urllib2.Request(url=url, data=data, headers=headers)
resp = urllib2.urlopen(req).read()
SensorJSON = json.loads(resp)
oslog("Sensor successfully created: " + SensorJSON["uuid"])
return SensorJSON
except Exception as err:
oslog(err)
def assignSensor(auth, settings, sensorUUID, SensorData):
url = 'https://' + settings["APIServer"] + '/api/mdm/devicesensors/' + sensorUUID + '/assignment'
sgUUIDs = []
for sg in SensorData["smart_groups"]:
sgUUID = getSmartGroupUUID(auth, settings, sg)
sgUUIDs.append(sgUUID)
d = {"name": "Assignment Group 1",
"smart_group_uuids": sgUUIDs,
"trigger_type": SensorData["trigger_type"],
"event_triggers": SensorData["event_triggers"]
}
data = json.dumps(d).encode("utf-8")
headers = {'Authorization':auth,
'AW-Tenant-Code':settings["APIKey"],
'Accept':'application/json;version=2',
'Content-Type': 'application/json'}
try:
oslog("Assigning Sensor...")
req = urllib2.Request(url=url, data=data, headers=headers)
resp = urllib2.urlopen(req).read()
AssignmentJSON = json.loads(resp)
oslog("Sensor successfully assigned: " + AssignmentJSON["uuid"])
return AssignmentJSON
except Exception as err:
oslog(err)
def createFolder(path):
if not os.path.exists(path):
os.makedirs(path)
def main():
#setup
with open('settings.conf') as data_file:
settings = json.load(data_file)
auth = getAuth(settings["Username"], settings["Password"])
createFolder(sensorpath)
option = -1
while option != 0:
print("")
print("Select operation")
print("1: Get Custom Attribute Profiles from Source Tenant")
print("2: Upload Sensors to Destination Tenant")
print("0: Exit")
print("")
option = input()
option = int(option)
if option == 1:
oslog("Fetching Custom Attribute profiles...")
getCAProfiles(auth, settings)
elif option == 2:
oslog("Uploading Sensors...")
uploadSensors(auth, settings)
elif option == 0:
oslog("exiting.....")
os._exit(os.EX_OK)
if __name__ == '__main__':
main() | {
"repo_name": "vmwaresamples/AirWatch-samples",
"path": "macOS-Samples/Tools/CustomAttributesToSensorsMigration/migrator.py",
"copies": "1",
"size": "8991",
"license": "bsd-3-clause",
"hash": 4124600617743453000,
"line_mean": 31.4620938628,
"line_max": 136,
"alpha_frac": 0.619730842,
"autogenerated": false,
"ratio": 3.782498948254102,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9805803476063211,
"avg_score": 0.019285262838178236,
"num_lines": 277
} |
from Foundation import NSData
from objc import *
from pyble._gatt import Service, Characteristic, Descriptor
from util import CBUUID2String
import uuid
import logging
from pprint import pprint, pformat
import struct
logger = logging.getLogger(__name__)
from pyble.patterns import Trace
from pyble.handlers import ProfileHandler
@Trace
class OSXBLEService(Service):
def __init__(self, peripheral=None, instance=None):
try:
super().__init__()
except:
super(OSXBLEService, self).__init__()
# which peripheral own this service
self.instance = instance
self.peripheral = peripheral
self.UUID = ""
self.isPrimary = False
if not instance:
return
uuidBytes = instance._.UUID._.data
if len(uuidBytes) == 2:
self.name = str(instance._.UUID)
if self.name.startswith("Unknown"):
self.name = "UNKNOWN"
self.UUID = CBUUID2String(uuidBytes)
elif len(uuidBytes) == 16:
self.UUID = str(uuid.UUID(bytes=uuidBytes)).upper()
else:
# invalid UUID size
pass
self.isPrimary = (instance._.isPrimary == YES)
@property
def characteristicUUIDs(self):
if len(self._characteristicUUIDs) == 0:
self.peripheral.discoverCharacteristicsForService(self.instance)
for characteristic in self.characteristics:
self._characteristicUUIDs.append(characteristic.UUID)
return self._characteristicUUIDs
@characteristicUUIDs.setter
def characteristicUUIDs(self, value):
try:
self._characteristicUUIDs = value[:]
except:
pass
def __iter__(self):
if len(self.characteristics) == 0:
self.peripheral.discoverCharacteristicsForService(self.instance)
return iter(self.characteristics)
def findCharacteristicByInstance(self, instance):
for c in self.characteristics:
if str(c.UUID) == CBUUID2String(instance._.UUID._.data):
return c
return None
def getCharacteristicByInstance(self, instance):
for c in self.characteristics:
if str(c.UUID) == CBUUID2String(instance._.UUID._.data):
return c
return None
class OSXBLECharacteristic(Characteristic):
def __init__(self, service=None, profile=None, instance=None):
try:
super().__init__(service=service, profile=profile)
except:
super(OSXBLECharacteristic, self).__init__(service=service, profile=profile)
self._description = ""
self.properties = {
"broadcast": False, # 0x0001
"read": False, # 0x0002
"writeWithoutResponse": False, # 0x0004
"write": False, # 0x0008
"notify": False, # 0x0010
"indicate": False, # 0x0020
"authenticatedSignedWrites": False, # 0x0040
"extendedProperties": False, # 0x0080
"notifyEncryptionRequired": False, # 0x0100
"indicateEncryptionRequired": False # 0x0200
}
self._instance = None
self.service = service
self.profile = profile
self.UUID = ""
self._notify = False
if not instance:
return
# update basic info
self.instance = instance
uuidBytes = instance._.UUID._.data
if len(uuidBytes) == 2:
self.name = str(instance._.UUID)
if self.name.startswith("Unknown"):
self.name = "UNKNOWN"
self.UUID = CBUUID2String(uuidBytes)
elif len(uuidBytes) == 16:
self.UUID = str(uuid.UUID(bytes=uuidBytes)).upper()
else:
# invalid UUID size
pass
# callbacks
def _update_userdescription(self, description):
self._description = description
def _update_value(self, value):
self.value = value
def addDescriptor(self, descriptor):
if descriptor not in self.descriptors:
self.descriptors.append(descriptor)
if descriptor.UUID == "2901": # user description descriptor
descriptor.setDescriptorUserDescriptionCallback(self._update_userdescription)
def findDescriptorByInstance(self, instance):
for d in self.descriptors:
if str(d.UUID) == CBUUID2String(instance._.UUID._.data):
return d
return None
def showProperties(self):
print "%s:%s:%s properties" % (self.service.peripheral, self.service, self)
pprint(self.properties)
def showDescriptors(self):
print "%s:%s:%s descriptors" % (self.service.peripheral, self.service, self)
for d in self.descriptors:
print "\t%s: " % d, d.value
@property
def notify(self):
return self._notify
@notify.setter
def notify(self, value):
if not self.properties["notify"]:
self._notify = False
else:
self.service.peripheral.setNotifyForCharacteristic(value, self.instance)
return self._notify
@property
def instance(self):
return self._instance
@instance.setter
def instance(self, value):
self._instance = value
# update properties
if value._.properties:
self.updateProperties(int(value._.properties))
@property
def value(self):
if self.properties["read"]:
self.service.peripheral.readValueForCharacteristic(self.instance)
ret = self.handler.on_read(self, self._value)
if ret:
self._value = ret
return ret
return self._value
else:
return None
@value.setter
def value(self, data):
if not self.properties["write"]:
return
# data needs to be byte array
if not isinstance(data, bytearray):
raise TypeError("data needs to be a bytearray")
rawdata = NSData.dataWithBytes_length_(data, len(data))
self.service.peripheral.writeValueForCharacteristic(rawdata, self.instance)
@property
def description(self):
if len(self._description) == 0:
if len(self.descriptors) == 0:
self.service.peripheral.discoverDescriptorsForCharacteristic(self.instance)
d = None
for descriptor in self.descriptors:
if descriptor.UUID == "2901":
d = descriptor
break
if d:
self._description = d.value
return self._description
@description.setter
def description(self, value):
self._description = value
def updateProperties(self, properties):
for key in self.properties:
self.properties[key] = False
if properties & 0x0001:
self.properties["broadcast"] = True
if properties & 0x0002:
self.properties["read"] = True
if properties & 0x0004:
self.properties["writeWithoutResponse"] = True
if properties & 0x0008:
self.properties["write"] = True
if properties & 0x0010:
self.properties["notify"] = True
if properties & 0x0020:
self.properties["indicate"] = True
if properties & 0x0040:
self.properties["authenticatedSignedWrites"] = True
if properties & 0x0080:
self.properties["extendedProperties"] = True
if properties & 0x0100:
self.properties["notifyEncryptionRequired"] = True
if properties & 0x0200:
self.properties["indicateEncryptionRequired"] = True
class OSXBLEDescriptor(Descriptor):
def __init__(self, characteristic=None, instance=None):
try:
super().__init__()
except:
super(OSXBLEDescriptor, self).__init__()
self.characteristic = characteristic
self.instance = instance
self.UUID = ""
self._value = None
# callback
self.update_userdescription = None
if not instance:
return
uuidBytes = instance._.UUID._.data
if len(uuidBytes) == 2:
self.name = str(instance._.UUID)
if self.name.startswith("Unknown"):
self.name = "UNKNOWN"
self.UUID = CBUUID2String(uuidBytes)
elif len(uuidBytes) == 16:
self.UUID = str(uuid.UUID(bytes=uuidBytes)).upper()
else:
# invalid UUID size
pass
# register callbacks
def setDescriptorUserDescriptionCallback(self, func):
self.update_userdescription = func
@property
def value(self):
if self._value == None:
self.characteristic.service.peripheral.readValueForDescriptor(self.instance)
return self._value
@value.setter
def value(self, data):
# base on UUID to convert data
if self.UUID == "2900": # Characteristic Extended Properties
self._value = struct.unpack(">h", data)[0]
elif self.UUID == "2901": # Characteristic User Description
self._value = str(data)
if self.update_userdescription:
self.update_userdescription(self._value)
elif self.UUID == "2902": # Client Characteristic Configuration
self._value = struct.unpack(">H", data)[0]
elif self.UUID == "2903": # Client Characteristic Configuration
self._value = data
elif self.UUID == "2904": # Characteristic Presentation Format
self._value = data
elif self.UUID == "2905": # Characteristic Aggregate Format
self._value = data
elif self.UUID == "2906": # Valid Range
self._value = data
elif self.UUID == "2907": # External Report Reference
self._value = data
elif self.UUID == "2908": # Report Regerence
self._value = data
else:
# invalid descriptor
pass
def __repr__(self):
identifier = ""
if isinstance(self.UUID, type("")):
identifier = self.UUID
else:
identifier = str(self.UUID).upper()
return "Descriptor{%s <%s>}" % (self.name, identifier)
def __str__(self):
return self.__repr__()
| {
"repo_name": "brettchien/PyBLEWrapper",
"path": "pyble/osx/gatt.py",
"copies": "1",
"size": "10489",
"license": "mit",
"hash": 3378833135565165000,
"line_mean": 32.9449838188,
"line_max": 93,
"alpha_frac": 0.5807989322,
"autogenerated": false,
"ratio": 4.361330561330561,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5442129493530561,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSDate
from AppKit import NSRunLoop, NSProgressIndicator, NSProgressIndicatorBarStyle, NSProgressIndicatorSpinningStyle
from vanilla.vanillaBase import VanillaBaseObject, _sizeStyleMap, osVersion10_11, osVersionCurrent
class ProgressBar(VanillaBaseObject):
"""
A standard progress bar.::
from vanilla import *
class ProgressBarDemo(object):
def __init__(self):
self.w = Window((200, 65))
self.w.bar = ProgressBar((10, 10, -10, 16))
self.w.button = Button((10, 35, -10, 20), "Go!",
callback=self.showProgress)
self.w.open()
def showProgress(self, sender):
import time
self.w.bar.set(0)
for i in range(10):
self.w.bar.increment(10)
time.sleep(.2)
ProgressBarDemo()
**posSize** Tuple of form *(left, top, width, height)* representing
the position and size of the progress bar. The height of the progress
bar sould match the appropriate value for the given *sizeStyle*.
+-------------------------+
| **Standard Dimensions** |
+---------+---+-----------+
| Regular | H | 16 |
+---------+---+-----------+
| Small | H | 10 |
+---------+---+-----------+
**minValue** The minimum value of the progress bar.
**maxValue** The maximum value of the progress bar.
**isIndeterminate** Boolean representing if the progress bar is indeterminate.
Determinate progress bars show how much of the task has been completed.
Indeterminate progress bars simply show that the application is busy.
**sizeStyle** A string representing the desired size style of the pregress bar.
The options are:
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
"""
nsProgressIndicatorClass = NSProgressIndicator
allFrameAdjustments = {
"small": (-1, -0, 2, 0),
"regular": (-2, -0, 4, 0),
}
progressStyleMap = {
"bar" : NSProgressIndicatorBarStyle,
"spinning" : NSProgressIndicatorSpinningStyle
}
def __init__(self, posSize, minValue=0, maxValue=100, isIndeterminate=False, sizeStyle="regular", progressStyle="bar"):
self._setupView(self.nsProgressIndicatorClass, posSize)
self.frameAdjustments = self.allFrameAdjustments[sizeStyle]
self._nsObject.setControlSize_(_sizeStyleMap[sizeStyle])
self._nsObject.setStyle_(self.progressStyleMap[progressStyle])
self._nsObject.setMinValue_(minValue)
self._nsObject.setMaxValue_(maxValue)
self._nsObject.setIndeterminate_(isIndeterminate)
if isIndeterminate:
self._nsObject.setUsesThreadedAnimation_(True)
def getNSProgressIndicator(self):
"""
Return the *NSProgressIndicator* that this object wraps.
"""
return self._nsObject
# implementation note:
# display is called manually to ensure that the animation happens.
# otherwise if it is called during an expensive python function,
# it will not animate until the function is complete.
def set(self, value):
"""
Set the value of the progress bar to **value**.
*Only available in determinate progress bars.*
"""
self._nsObject.setDoubleValue_(value)
self._nsObject.display()
if osVersionCurrent >= osVersion10_11:
NSRunLoop.mainRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.0001))
def get(self):
"""
Get the current value of the progress bar.
*Only available in determinate progress bars.*
"""
return self._nsObject.doubleValue()
def increment(self, value=1):
"""
Increment the progress bar by **value**.
*Only available in determinate progress bars.*
"""
self._nsObject.incrementBy_(value)
self._nsObject.display()
if osVersionCurrent >= osVersion10_11:
NSRunLoop.mainRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.0001))
def start(self):
"""
Start the animation.
*Only available in indeterminate progress bars.*
"""
self._nsObject.startAnimation_(None)
def stop(self):
"""
Stop the animation.
*Only available in indeterminate progress bars.*
"""
self._nsObject.stopAnimation_(None)
| {
"repo_name": "moyogo/vanilla",
"path": "Lib/vanilla/vanillaProgressBar.py",
"copies": "1",
"size": "4547",
"license": "mit",
"hash": 568544268864587300,
"line_mean": 31.9492753623,
"line_max": 123,
"alpha_frac": 0.6012755663,
"autogenerated": false,
"ratio": 4.322243346007604,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0010062166809838462,
"num_lines": 138
} |
from Foundation import NSInvocation, NSString, NSMakeRange, NSMaxRange, NSLocationInRange, NSNotFound, NSMakeRect, NSMinY, NSWidth, NSHeight
from AppKit import NSRulerView, NSMiniControlSize, NSTextView, NSNotificationCenter, \
NSFontAttributeName, NSForegroundColorAttributeName, NSTextStorageDidProcessEditingNotification, \
NSFont, NSColor, NSBezierPath, NSRectFill
import math
from objc import super
"""
Based/translated from NoodleLineNumberView
http://www.noodlesoft.com/blog/2008/10/05/displaying-line-numbers-with-nstextview/
"""
class LineNumberNSRulerView(NSRulerView):
DEFAULT_THICKNESS = 22.
RULER_MARGIN = 5.
def init(self):
self = super(LineNumberNSRulerView, self).init()
self._font = NSFont.labelFontOfSize_(NSFont.systemFontSizeForControlSize_(NSMiniControlSize))
self._textColor = NSColor.colorWithCalibratedWhite_alpha_(.42, 1)
self._rulerBackgroundColor = None
self._lineIndices = None
return self
def setFont_(self, font):
self._font = font
def font(self):
return self._font
def setTextColor_(self, color):
self._textColor = color
self.setNeedsDisplay_(True)
def textColor(self):
return self._textColor
def textAttributes(self):
return {
NSFontAttributeName: self.font(),
NSForegroundColorAttributeName: self.textColor()
}
def setRulerBackgroundColor_(self, color):
self._rulerBackgroundColor = color
self.setNeedsDisplay_(True)
def rulerBackgroundColor(self):
return self._rulerBackgroundColor
def setClientView_(self, view):
oldClientView = self.clientView()
if oldClientView != view and isinstance(oldClientView, NSTextView):
NSNotificationCenter.defaultCenter().removeObserver_name_object_(self, NSTextStorageDidProcessEditingNotification, oldClientView.textStorage())
super(LineNumberNSRulerView, self).setClientView_(view)
if view is not None and isinstance(view, NSTextView):
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "textDidChange:",
NSTextStorageDidProcessEditingNotification,
view.textStorage())
def lineIndices(self):
if self._lineIndices is None:
self.calculateLines()
return self._lineIndices
def invalidateLineIndices(self):
self._lineIndices = None
def textDidChange_(self, sender):
self.calculateLines()
self.invalidateLineIndices()
self.setNeedsDisplay_(True)
def dealloc(self):
# make sure we remove ourselves as an observer of the text storage
view = self.clientView()
if view is not None:
NSNotificationCenter.defaultCenter().removeObserver_name_object_(self, NSTextStorageDidProcessEditingNotification, view.textStorage())
super(LineNumberNSRulerView, self).dealloc()
def calculateLines(self):
view = self.clientView()
if not isinstance(view, NSTextView):
return
text = view.string()
textLength = text.length()
if not textLength:
self._lineIndices = [1]
return
lineIndices = []
index = 0
numberOfLines = 0
while index < textLength:
lineIndices.append(index)
index = NSMaxRange(text.lineRangeForRange_(NSMakeRange(index, 0)))
numberOfLines += 1
lineStart, lineEnd, contentEnd = text.getLineStart_end_contentsEnd_forRange_(None, None, None, NSMakeRange(lineIndices[-1], 0))
if contentEnd < lineEnd:
lineIndices.append(index)
self._lineIndices = lineIndices
oldThickness = self.ruleThickness()
newThickness = self.requiredThickness()
if abs(oldThickness - newThickness) > 0:
invocation = NSInvocation.invocationWithMethodSignature_(self.methodSignatureForSelector_("setRuleThickness:"))
invocation.setSelector_("setRuleThickness:")
invocation.setTarget_(self)
invocation.setArgument_atIndex_(newThickness, 2)
invocation.performSelector_withObject_afterDelay_("invoke", None, 0)
def requiredThickness(self):
lineCount = len(self.lineIndices())
digits = int(math.log10(lineCount) + 1)
sampleString = NSString.stringWithString_("8" * digits)
stringSize = sampleString.sizeWithAttributes_(self.textAttributes())
return math.ceil(max([self.DEFAULT_THICKNESS, stringSize.width + self.RULER_MARGIN * 2]))
def lineNumberForCharacterIndex_inText_(self, index, text):
lines = self.lineIndices()
left = 0
right = len(lines)
while (right - left) > 1:
mid = (right + left) // 2
lineStart = lines[mid]
if index < lineStart:
right = mid
elif index > lineStart:
left = mid
else:
return mid
return left
def drawHashMarksAndLabelsInRect_(self, rect):
bounds = self.bounds()
view = self.clientView()
rulerBackgroundColor = self.rulerBackgroundColor()
if rulerBackgroundColor is not None:
rulerBackgroundColor.set()
NSRectFill(bounds)
if not isinstance(view, NSTextView):
return
layoutManager = view.layoutManager()
container = view.textContainer()
text = view.string()
nullRange = NSMakeRange(NSNotFound, 0)
yinset = view.textContainerInset().height
visibleRect = self.scrollView().contentView().bounds()
textAttributes = self.textAttributes()
lines = self.lineIndices()
glyphRange = layoutManager.glyphRangeForBoundingRect_inTextContainer_(visibleRect, container)
_range = layoutManager.characterRangeForGlyphRange_actualGlyphRange_(glyphRange, None)[0]
_range.length += 1
count = len(lines)
index = 0
lineNumber = self.lineNumberForCharacterIndex_inText_(_range.location, text)
for line in range(lineNumber, count):
index = lines[line]
if NSLocationInRange(index, _range):
rects, rectCount = layoutManager.rectArrayForCharacterRange_withinSelectedCharacterRange_inTextContainer_rectCount_(
NSMakeRange(index, 0),
nullRange,
container,
None
)
if rectCount > 0:
ypos = yinset + NSMinY(rects[0]) - NSMinY(visibleRect)
labelText = NSString.stringWithString_("%s" % (line + 1))
stringSize = labelText.sizeWithAttributes_(textAttributes)
x = NSWidth(bounds) - stringSize.width - self.RULER_MARGIN
y = ypos + (NSHeight(rects[0]) - stringSize.height) / 2.0
w = NSWidth(bounds) - self.RULER_MARGIN * 2.0
h = NSHeight(rects[0])
labelText.drawInRect_withAttributes_(NSMakeRect(x, y, w, h), textAttributes)
if index > NSMaxRange(_range):
break
path = NSBezierPath.bezierPath()
path.moveToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y))
path.lineToPoint_((bounds.origin.x + bounds.size.width, bounds.origin.y + bounds.size.height))
NSColor.grayColor().set()
path.stroke()
| {
"repo_name": "schriftgestalt/drawbot",
"path": "drawBot/ui/lineNumberRulerView.py",
"copies": "3",
"size": "7612",
"license": "bsd-2-clause",
"hash": -3555628811278889000,
"line_mean": 34.9056603774,
"line_max": 155,
"alpha_frac": 0.630189175,
"autogenerated": false,
"ratio": 4.139206090266449,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6269395265266449,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSMaxXEdge, NSMaxYEdge, NSMinXEdge, NSMinYEdge
from AppKit import *
from vanillaBase import VanillaBaseObject, _breakCycles
_drawerEdgeMap = {
"left": NSMinXEdge,
"right": NSMaxXEdge,
"top": NSMaxYEdge,
"bottom": NSMinYEdge,
}
class Drawer(VanillaBaseObject):
"""
A drawer attached to a window. Drawers are capable of containing controls.
To add a control to a drawer, simply set it as an attribute of the drawer.::
from vanilla import *
class DrawerDemo(object):
def __init__(self):
self.w = Window((200, 200))
self.w.button = Button((10, 10, -10, 20), "Toggle Drawer",
callback=self.toggleDrawer)
self.d = Drawer((100, 150), self.w)
self.d.textBox = TextBox((10, 10, -10, -10),
"This is a drawer.")
self.w.open()
self.d.open()
def toggleDrawer(self, sender):
self.d.toggle()
DrawerDemo()
No special naming is required for the attributes. However, each attribute must have a unique name.
**size** Tuple of form *(width, height)* representing the size of the drawer.
**parentWindow** The window that the drawer should be attached to.
**minSize** Tuple of form *(width, height)* representing the minimum size of the drawer.
**maxSize** Tuple of form *(width, height)* representing the maximum size of the drawer.
**preferredEdge** The preferred edge of the window that the drawe should be attached to. If the
drawer cannot be opened on the preferred edge, it will be opened on the opposite edge. The options are:
+----------+
| "left" |
+----------+
| "right" |
+----------+
| "top" |
+----------+
| "bottom" |
+----------+
**forceEdge** Boolean representing if the drawer should *always* be opened on the preferred edge.
**leadingOffset** Distance between the top or left edge of the drawer and the parent window.
**trailingOffset** Distance between the bottom or right edge of the drawer and the parent window.
"""
nsDrawerClass = NSDrawer
def __init__(self, size, parentWindow, minSize=None, maxSize=None,
preferredEdge="left", forceEdge=False, leadingOffset=20, trailingOffset=20):
from vanillaWindows import Window
self._preferredEdge = preferredEdge
self._forceEdge = forceEdge
drawer = self._nsObject = self.nsDrawerClass.alloc().initWithContentSize_preferredEdge_(
size, _drawerEdgeMap[preferredEdge])
drawer.setLeadingOffset_(leadingOffset)
drawer.setTrailingOffset_(trailingOffset)
if minSize:
drawer.setMinContentSize_(minSize)
if maxSize:
drawer.setMaxContentSize_(maxSize)
if isinstance(parentWindow, Window):
parentWindow = parentWindow._window
drawer.setParentWindow_(parentWindow)
def getNSDrawer(self):
"""
Return the *NSDrawer* that this object wraps.
"""
return self._nsObject
def _getContentView(self):
return self._nsObject.contentView()
def _breakCycles(self):
super(Drawer, self)._breakCycles()
view = self._getContentView()
if view is not None:
_breakCycles(view)
def open(self):
"""
Open the drawer.
"""
if self._forceEdge:
self._nsObject.openOnEdge_(_drawerEdgeMap[self._preferredEdge])
else:
self._nsObject.open()
def close(self):
"""
Close the drawer.
"""
self._nsObject.close()
def toggle(self):
"""
Open the drawer if it is closed. Close it if it is open.
"""
self._nsObject.toggle_(self)
def isOpen(self):
"""
Return True if the drawer is open, False if it is closed.
"""
return self._nsObject.isOpen()
| {
"repo_name": "bitforks/vanilla",
"path": "Lib/vanilla/vanillaDrawer.py",
"copies": "3",
"size": "4048",
"license": "mit",
"hash": -4163901866368052000,
"line_mean": 30.3798449612,
"line_max": 107,
"alpha_frac": 0.5946146245,
"autogenerated": false,
"ratio": 4.072434607645875,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6167049232145876,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSMaxXEdge, NSMaxYEdge, NSMinXEdge, NSMinYEdge
from AppKit import NSDrawer
from vanilla.vanillaBase import VanillaBaseObject, _breakCycles
_drawerEdgeMap = {
"left": NSMinXEdge,
"right": NSMaxXEdge,
"top": NSMaxYEdge,
"bottom": NSMinYEdge,
}
class Drawer(VanillaBaseObject):
"""
A drawer attached to a window. Drawers are capable of containing controls.
.. image:: /_images/Drawer.png
.. warning:: Drawers are deprecated and should not be used in modern macOS apps.
To add a control to a drawer, simply set it as an attribute of the drawer.
::
from vanilla import Window, Button, Drawer, TextBox
class DrawerDemo:
def __init__(self):
self.w = Window((200, 200))
self.w.button = Button((10, 10, -10, 20), "Toggle Drawer",
callback=self.toggleDrawer)
self.d = Drawer((100, 150), self.w)
self.d.textBox = TextBox((10, 10, -10, -10),
"This is a drawer.")
self.w.open()
self.d.open()
def toggleDrawer(self, sender):
self.d.toggle()
DrawerDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
**size** Tuple of form *(width, height)* representing the size of the drawer.
**parentWindow** The window that the drawer should be attached to.
**minSize** Tuple of form *(width, height)* representing the minimum size
of the drawer.
**maxSize** Tuple of form *(width, height)* representing the maximum size
of the drawer.
**preferredEdge** The preferred edge of the window that the drawer should be
attached to. If the drawer cannot be opened on the preferred edge, it will
be opened on the opposite edge. The options are:
+----------+
| "left" |
+----------+
| "right" |
+----------+
| "top" |
+----------+
| "bottom" |
+----------+
**forceEdge** Boolean representing if the drawer should *always* be opened
on the preferred edge.
**leadingOffset** Distance between the top or left edge of the drawer
and the parent window.
**trailingOffset** Distance between the bottom or right edge of the drawer
and the parent window.
"""
nsDrawerClass = NSDrawer
def __init__(self, size, parentWindow, minSize=None, maxSize=None,
preferredEdge="left", forceEdge=False, leadingOffset=20, trailingOffset=20):
from vanilla.vanillaWindows import Window
self._preferredEdge = preferredEdge
self._forceEdge = forceEdge
drawer = self._nsObject = self.nsDrawerClass.alloc().initWithContentSize_preferredEdge_(
size, _drawerEdgeMap[preferredEdge])
drawer.setLeadingOffset_(leadingOffset)
drawer.setTrailingOffset_(trailingOffset)
if minSize:
drawer.setMinContentSize_(minSize)
if maxSize:
drawer.setMaxContentSize_(maxSize)
if isinstance(parentWindow, Window):
parentWindow = parentWindow._window
drawer.setParentWindow_(parentWindow)
def getNSDrawer(self):
"""
Return the `NSDrawer`_ that this object wraps.
.. _NSDrawer: https://developer.apple.com/documentation/appkit/nsdrawer?language=objc
"""
return self._nsObject
def _getContentView(self):
return self._nsObject.contentView()
def _breakCycles(self):
super(Drawer, self)._breakCycles()
view = self._getContentView()
if view is not None:
_breakCycles(view)
def open(self):
"""
Open the drawer.
"""
if self._forceEdge:
self._nsObject.openOnEdge_(_drawerEdgeMap[self._preferredEdge])
else:
self._nsObject.open()
def close(self):
"""
Close the drawer.
"""
self._nsObject.close()
def toggle(self):
"""
Open the drawer if it is closed. Close it if it is open.
"""
self._nsObject.toggle_(self)
def isOpen(self):
"""
Return *True* if the drawer is open, *False* if it is closed.
"""
return self._nsObject.isOpen()
| {
"repo_name": "typesupply/vanilla",
"path": "Lib/vanilla/vanillaDrawer.py",
"copies": "1",
"size": "4350",
"license": "mit",
"hash": -7011963176605780000,
"line_mean": 29.2083333333,
"line_max": 96,
"alpha_frac": 0.5977011494,
"autogenerated": false,
"ratio": 4.027777777777778,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0005536457859800942,
"num_lines": 144
} |
from Foundation import NSObject
from AppKit import NSApplication, NSMenu, NSMenuItem, NSBundle
from PyObjCTools import AppHelper
class _VanillaMiniAppDelegate(NSObject):
def applicationShouldTerminateAfterLastWindowClosed_(self, notification):
return True
def executeVanillaTest(cls, nibPath=None, calls=None, **kwargs):
"""
Execute a Vanilla UI class in a mini application.
"""
app = NSApplication.sharedApplication()
delegate = _VanillaMiniAppDelegate.alloc().init()
app.setDelegate_(delegate)
if nibPath:
NSBundle.loadNibFile_externalNameTable_withZone_(nibPath, {}, None)
else:
mainMenu = NSMenu.alloc().initWithTitle_("Vanilla Test")
fileMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("File", None, "")
fileMenu = NSMenu.alloc().initWithTitle_("File")
fileMenuItem.setSubmenu_(fileMenu)
mainMenu.addItem_(fileMenuItem)
editMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Edit", None, "")
editMenu = NSMenu.alloc().initWithTitle_("Edit")
editMenuItem.setSubmenu_(editMenu)
mainMenu.addItem_(editMenuItem)
helpMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Help", None, "")
helpMenu = NSMenu.alloc().initWithTitle_("Help")
helpMenuItem.setSubmenu_(helpMenu)
mainMenu.addItem_(helpMenuItem)
app.setMainMenu_(mainMenu)
if cls is not None:
cls(**kwargs)
if calls is not None:
for call, kwargs in calls:
call(**kwargs)
app.activateIgnoringOtherApps_(True)
AppHelper.runEventLoop()
| {
"repo_name": "moyogo/vanilla",
"path": "Lib/vanilla/test/testTools.py",
"copies": "1",
"size": "1659",
"license": "mit",
"hash": -1904598765625577000,
"line_mean": 32.18,
"line_max": 95,
"alpha_frac": 0.6877637131,
"autogenerated": false,
"ratio": 3.796338672768879,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4984102385868878,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSObject
from AppKit import NSApplication, NSMenu, NSMenuItem, NSBundle
from PyObjCTools import AppHelper
class _VanillaMiniApp(NSApplication): pass
class _VanillaMiniAppDelegate(NSObject):
def applicationShouldTerminateAfterLastWindowClosed_(self, notification):
return True
def executeVanillaTest(cls, nibPath=None, calls=None, **kwargs):
"""
Execute a Vanilla UI class in a mini application.
"""
app = _VanillaMiniApp.sharedApplication()
delegate = _VanillaMiniAppDelegate.alloc().init()
app.setDelegate_(delegate)
if nibPath:
NSBundle.loadNibFile_externalNameTable_withZone_(nibPath, {}, None)
else:
mainMenu = NSMenu.alloc().initWithTitle_("Vanilla Test")
fileMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("File", None, "")
fileMenu = NSMenu.alloc().initWithTitle_("File")
fileMenuItem.setSubmenu_(fileMenu)
mainMenu.addItem_(fileMenuItem)
editMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Edit", None, "")
editMenu = NSMenu.alloc().initWithTitle_("Edit")
editMenuItem.setSubmenu_(editMenu)
mainMenu.addItem_(editMenuItem)
helpMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Help", None, "")
helpMenu = NSMenu.alloc().initWithTitle_("Help")
helpMenuItem.setSubmenu_(helpMenu)
mainMenu.addItem_(helpMenuItem)
app.setMainMenu_(mainMenu)
if cls is not None:
cls(**kwargs)
if calls is not None:
for call, kwargs in calls:
call(**kwargs)
app.activateIgnoringOtherApps_(True)
AppHelper.runEventLoop()
| {
"repo_name": "typesupply/vanilla",
"path": "Lib/vanilla/test/testTools.py",
"copies": "1",
"size": "1706",
"license": "mit",
"hash": 37817626497900696,
"line_mean": 31.1886792453,
"line_max": 95,
"alpha_frac": 0.6905041032,
"autogenerated": false,
"ratio": 3.7494505494505495,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9934812594730409,
"avg_score": 0.0010284115840280825,
"num_lines": 53
} |
from Foundation import NSObject
from AppKit import NSApp, NSWindow, NSPanel, NSScreen, NSWindowController, NSToolbar, NSToolbarItem, NSImage, NSNormalWindowLevel, NSFloatingWindowLevel, NSClosableWindowMask, NSMiniaturizableWindowMask, NSResizableWindowMask, NSTexturedBackgroundWindowMask, NSUnifiedTitleAndToolbarWindowMask, NSHUDWindowMask, NSUtilityWindowMask, NSTitledWindowMask, NSBorderlessWindowMask, NSBackingStoreBuffered, NSToolbarFlexibleSpaceItemIdentifier, NSToolbarSpaceItemIdentifier, NSToolbarSeparatorItemIdentifier, NSToolbarCustomizeToolbarItemIdentifier, NSToolbarPrintItemIdentifier, NSToolbarShowFontsItemIdentifier, NSToolbarShowColorsItemIdentifier, NSToolbarDisplayModeDefault, NSToolbarDisplayModeIconAndLabel, NSToolbarDisplayModeIconOnly, NSToolbarDisplayModeLabelOnly, NSToolbarSizeModeDefault, NSToolbarSizeModeRegular, NSToolbarSizeModeSmall
from objc import python_method
from vanilla.vanillaBase import _breakCycles, _calcFrame, _setAttr, _delAttr, _addAutoLayoutRules, _flipFrame, \
VanillaCallbackWrapper, VanillaError, VanillaWarning, VanillaBaseControl, \
osVersionCurrent, osVersion10_7, osVersion10_10
# PyObjC may not have these constants wrapped,
# so test and fallback if needed.
try:
from AppKit import NSWindowCollectionBehaviorFullScreenPrimary, NSWindowCollectionBehaviorFullScreenAuxiliary
except ImportError:
NSWindowCollectionBehaviorFullScreenPrimary = 1 << 7
NSWindowCollectionBehaviorFullScreenAuxiliary = 1 << 8
try:
from AppKit import NSWindowTitleVisible, NSWindowTitleHidden
except ImportError:
NSWindowTitleVisible = 0
NSWindowTitleHidden = 1
try:
from AppKit import NSFullSizeContentViewWindowMask
except ImportError:
NSFullSizeContentViewWindowMask = 1 << 15
class Window(NSObject):
"""
A window capable of containing controls.
.. image:: /_images/Window.png
To add a control to a window, simply set it as an attribute of the window.
::
from vanilla import Window, Button, TextBox
class WindowDemo:
def __init__(self):
self.w = Window((200, 70), "Window Demo")
self.w.myButton = Button((10, 10, -10, 20), "My Button")
self.w.myTextBox = TextBox((10, 40, -10, 17), "My Text Box")
self.w.open()
WindowDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
**posSize** Tuple of form *(left, top, width, height)* representing the
position and size of the window. It may also be a tuple of form *(width, height)*.
In this case, the window will be positioned on screen automatically.
**title** The title to be set in the title bar of the window.
**minSize** Tuple of the form *(width, height)* representing the minimum size
that the window can be resized to.
**maxSize** Tuple of the form *(width, height)* representing the maximum size
that the window can be resized to.
**textured** Boolean value representing if the window should have a textured
appearance or not.
**autosaveName** A string representing a unique name for the window.
If given, this name will be used to store the window position and size in
the application preferences.
**closable** Boolean value representing if the window should have a
close button in the title bar.
**miniaturizable** Boolean value representing if the window should have a
minimize button in the title bar.
**initiallyVisible** Boolean value representing if the window will be
initially visible. Default is *True*. If *False*, you can show the window later
by calling `window.show()`.
**fullScreenMode** An indication of the full screen mode. These are the options:
+---------------+---------------------------------------------------------------+
| *None* | The window does not allow full screen. |
+---------------+---------------------------------------------------------------+
| *"primary"* | Corresponds to NSWindowCollectionBehaviorFullScreenPrimary. |
+---------------+---------------------------------------------------------------+
| *"auxiliary"* | Corresponds to NSWindowCollectionBehaviorFullScreenAuxiliary. |
+---------------+---------------------------------------------------------------+
**titleVisible** Boolean value indicating if the window title should be displayed.
**fullSizeContentView** Boolean value indicating if the content view should be the
full size of the window, including the area underneath the titlebar and toolbar.
**screen** A `NSScreen`_ object indicating the screen that the window should be
drawn to. When None the window will be drawn to the main screen.
.. _NSScreen: https://developer.apple.com/documentation/appkit/nsscreen?language=objc
"""
def __new__(cls, *args, **kwargs):
return cls.alloc().init()
nsWindowStyleMask = NSTitledWindowMask | NSUnifiedTitleAndToolbarWindowMask
nsWindowClass = NSWindow
nsWindowLevel = NSNormalWindowLevel
def __init__(self, posSize, title="", minSize=None, maxSize=None, textured=False,
autosaveName=None, closable=True, miniaturizable=True, initiallyVisible=True,
fullScreenMode=None, titleVisible=True, fullSizeContentView=False, screen=None):
mask = self.nsWindowStyleMask
if closable:
mask = mask | NSClosableWindowMask
if miniaturizable:
mask = mask | NSMiniaturizableWindowMask
if minSize or maxSize:
mask = mask | NSResizableWindowMask
if textured:
mask = mask | NSTexturedBackgroundWindowMask
if fullSizeContentView and osVersionCurrent >= osVersion10_10:
mask = mask | NSFullSizeContentViewWindowMask
# start the window
## too magical?
if len(posSize) == 2:
l = t = 100
w, h = posSize
cascade = True
else:
l, t, w, h = posSize
cascade = False
if screen is None:
screen = NSScreen.mainScreen()
frame = _calcFrame(screen.visibleFrame(), ((l, t), (w, h)))
self._window = self.nsWindowClass.alloc().initWithContentRect_styleMask_backing_defer_screen_(
frame, mask, NSBackingStoreBuffered, False, screen)
if autosaveName is not None:
# This also sets the window frame if it was previously stored.
# Make sure we do this before cascading.
self._window.setFrameAutosaveName_(autosaveName)
if cascade:
self._cascade()
if minSize is not None:
self._window.setMinSize_(minSize)
if maxSize is not None:
self._window.setMaxSize_(maxSize)
self._window.setTitle_(title)
self._window.setLevel_(self.nsWindowLevel)
self._window.setReleasedWhenClosed_(False)
self._window.setDelegate_(self)
self._autoLayoutViews = {}
self._bindings = {}
self._initiallyVisible = initiallyVisible
# full screen mode
if osVersionCurrent >= osVersion10_7:
if fullScreenMode is None:
pass
elif fullScreenMode == "primary":
self._window.setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenPrimary)
elif fullScreenMode == "auxiliary":
self._window.setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenAuxiliary)
# titlebar visibility
if osVersionCurrent >= osVersion10_10:
if not titleVisible:
self._window.setTitleVisibility_(NSWindowTitleHidden)
else:
self._window.setTitleVisibility_(NSWindowTitleVisible)
# full size content view
if fullSizeContentView and osVersionCurrent >= osVersion10_10:
self._window.setTitlebarAppearsTransparent_(True)
def _testForDeprecatedAttributes(self):
from warnings import warn
if hasattr(self, "_nsWindowStyleMask"):
warn(DeprecationWarning("The _nsWindowStyleMask attribute is deprecated. Use the nsWindowStyleMask attribute."))
self.nsWindowStyleMask = self._nsWindowStyleMask
if hasattr(self, "_nsWindowClass"):
warn(DeprecationWarning("The _nsWindowClass attribute is deprecated. Use the nsWindowClass attribute."))
self.nsWindowClass = self._nsWindowClass
if hasattr(self, "_nsWindowLevel"):
warn(DeprecationWarning("The _nsWindowLevel attribute is deprecated. Use the nsWindowLevel attribute."))
self.nsWindowLevel = self._nsWindowLevel
def _cascade(self):
allLeftTop = []
for other in NSApp().orderedWindows():
if other == self._window:
continue
(oL, oB), (oW, oH) = other.frame()
allLeftTop.append((oL, oB + oH))
(sL, sB), (sW, sH) = self._window.frame()
leftTop = sL, sB + sH
while leftTop in allLeftTop:
leftTop = self._window.cascadeTopLeftFromPoint_(leftTop)
self._window.setFrameTopLeftPoint_(leftTop)
def _breakCycles(self):
_breakCycles(self._window.contentView())
drawers = self._window.drawers()
if drawers is not None:
for drawer in drawers:
_breakCycles(drawer.contentView())
def _getContentView(self):
return self._window.contentView()
def __setattr__(self, attr, value):
_setAttr(Window, self, attr, value)
def __delattr__(self, attr):
_delAttr(Window, self, attr)
@python_method
def assignToDocument(self, document):
"""
Add this window to the list of windows associated with a document.
**document** should be a `NSDocument`_ instance.
.. _NSDocument: https://developer.apple.com/documentation/appkit/nsdocument?language=objc
"""
document.addWindowController_(self.getNSWindowController())
def getNSWindow(self):
"""
Return the `NSWindow`_ that this Vanilla object wraps.
.. _NSWindow: https://developer.apple.com/documentation/appkit/nswindow?language=objc
"""
return self._window
def getNSWindowController(self):
"""
Return an `NSWindowController`_ for the `NSWindow`_ that this Vanilla
object wraps, creating a one if needed.
.. _NSWindowController: https://developer.apple.com/documentation/appkit/nswindowcontroller?language=objc
"""
controller = self._window.windowController()
if controller is None:
controller = NSWindowController.alloc().initWithWindow_(self._window)
return controller
def open(self):
"""
Open the window.
"""
if self._window is None:
raise ValueError("can't re-open a window")
if self._initiallyVisible:
self.show()
# We retain ourselves to ensure we don't go away, even if our
# caller doesn't keep a reference. It's balanced by a release
# in windowWillClose_().
self.retain()
self._validateMinMaxSize()
def _validateMinMaxSize(self):
# warn when the min size is bigger then the initial window size
# or when the max size is smaller then the initial window size
size = self._window.frame().size
minSize = self._window.minSize()
maxSize = self._window.maxSize()
if size.width < minSize.width or size.height < minSize.height:
from warnings import warn
warn("The windows `minSize` is bigger then the initial size.", VanillaWarning)
elif size.width > maxSize.width or size.height > maxSize.height:
from warnings import warn
warn("The windows `maxSize` is bigger then the initial size.", VanillaWarning)
def close(self):
"""
Close the window.
Once a window has been closed it can not be re-opened.
"""
if self._window.isSheet():
NSApp().endSheet_(self._window)
self._window.orderOut_(None)
self._window.close()
def hide(self):
"""
Hide the window.
"""
self._window.orderOut_(None)
def show(self):
"""
Show the window if it is hidden.
"""
self._window.makeKeyAndOrderFront_(None)
def makeKey(self):
"""
Make the window the key window.
"""
self._window.makeKeyWindow()
def makeMain(self):
"""
Make the window the main window.
"""
self._window.makeMainWindow()
@python_method
def setTitle(self, title):
"""
Set the title in the window's title bar.
**title** should be a string.
"""
self._window.setTitle_(title)
def getTitle(self):
"""
The title in the window's title bar.
"""
return self._window.title()
def select(self):
"""
Select the window if it is not the currently selected window.
"""
self._window.makeKeyWindow()
def isVisible(self):
"""
A boolean value representing if the window is visible or not.
"""
return self._window.isVisible()
def _calculateTitlebarHeight(self):
# Note: this will include the toolbar height if there is one
contentFrame = self._window.contentRectForFrameRect_(self._window.frame())
windowFrame = self._window.frame()
contentHeight = contentFrame.size[1]
windowHeight = windowFrame.size[1]
return windowHeight - contentHeight
def getPosSize(self):
"""
A tuple of form *(left, top, width, height)* representing the window's
position and size.
"""
frame = self._window.frame()
l, t, w, h = _flipFrame(self._window.screen().visibleFrame(), frame)
titlebarHeight = self._calculateTitlebarHeight()
t += titlebarHeight
h -= titlebarHeight
return (l, t, w, h)
@python_method
def setPosSize(self, posSize, animate=True):
"""
Set the position and size of the window.
**posSize** A tuple of form *(left, top, width, height)*.
"""
titlebarHeight = self._calculateTitlebarHeight()
l, t, w, h = posSize
t -= titlebarHeight
h += titlebarHeight
screenFrame = self._window.screen().visibleFrame()
# if the top is less than zero, force it to zero.
# otherwise the window will be thrown to the bottom
# of the screen.
if t < 0:
t = 0
# the screen frame could have a bottom
# value that is not zero. this will cause
# an error if (and only if) a window is
# being positioned at the top of the screen.
# so, adjust it.
(sL, sB), (sW, sH) = screenFrame
screenFrame = ((sL, 0), (sW, sH + sB))
frame = _calcFrame(screenFrame, ((l, t), (w, h)), absolutePositioning=True)
self._window.setFrame_display_animate_(frame, True, animate)
@python_method
def addAutoPosSizeRules(self, rules, metrics=None):
"""
Add auto layout rules for controls/view in this view.
**rules** must by a list of rule definitions.
Rule definitions may take two forms:
* strings that follow the `Visual Format Language`_
* dictionaries with the following key/value pairs:
+---------------------------+-------------------------------------------------------------+
| key | value |
+===========================+=============================================================+
| *"view1"* | The vanilla wrapped view for the left side of the rule. |
+---------------------------+-------------------------------------------------------------+
| *"attribute1"* | The attribute of the view for the left side of the rule. |
| | See below for options. |
+---------------------------+-------------------------------------------------------------+
| *"relation"* (optional) | The relationship between the left side of the rule |
| | and the right side of the rule. See below for options. |
| | The default value is `"=="`. |
+---------------------------+-------------------------------------------------------------+
| *"view2"* | The vanilla wrapped view for the right side of the rule. |
+---------------------------+-------------------------------------------------------------+
| *"attribute2"* | The attribute of the view for the right side of the rule. |
| | See below for options. |
+---------------------------+-------------------------------------------------------------+
| *"multiplier"* (optional) | The constant multiplied with the attribute on the right |
| | side of the rule as part of getting the modified attribute. |
| | The default value is `1`. |
+---------------------------+-------------------------------------------------------------+
| *"constant"* (optional) | The constant added to the multiplied attribute value on |
| | the right side of the rule to yield the final modified |
| | attribute. The default value is `0`. |
+---------------------------+-------------------------------------------------------------+
The `attribute1` and `attribute2` options are:
+-------------------+--------------------------------+
| value | AppKit equivalent |
+===================+================================+
| *"left"* | NSLayoutAttributeLeft |
+-------------------+--------------------------------+
| *"right"* | NSLayoutAttributeRight |
+-------------------+--------------------------------+
| *"top"* | NSLayoutAttributeTop |
+-------------------+--------------------------------+
| *"bottom"* | NSLayoutAttributeBottom |
+-------------------+--------------------------------+
| *"leading"* | NSLayoutAttributeLeading |
+-------------------+--------------------------------+
| *"trailing"* | NSLayoutAttributeTrailing |
+-------------------+--------------------------------+
| *"width"* | NSLayoutAttributeWidth |
+-------------------+--------------------------------+
| *"height"* | NSLayoutAttributeHeight |
+-------------------+--------------------------------+
| *"centerX"* | NSLayoutAttributeCenterX |
+-------------------+--------------------------------+
| *"centerY"* | NSLayoutAttributeCenterY |
+-------------------+--------------------------------+
| *"baseline"* | NSLayoutAttributeBaseline |
+-------------------+--------------------------------+
| *"lastBaseline"* | NSLayoutAttributeLastBaseline |
+-------------------+--------------------------------+
| *"firstBaseline"* | NSLayoutAttributeFirstBaseline |
+-------------------+--------------------------------+
Refer to the `NSLayoutAttribute documentation`_ for the information
about what each of these do.
The `relation` options are:
+--------+------------------------------------+
| value | AppKit equivalent |
+========+====================================+
| *"<="* | NSLayoutRelationLessThanOrEqual |
+--------+------------------------------------+
| *"=="* | NSLayoutRelationEqual |
+--------+------------------------------------+
| *">="* | NSLayoutRelationGreaterThanOrEqual |
+--------+------------------------------------+
Refer to the `NSLayoutRelation documentation`_ for the information
about what each of these do.
**metrics** may be either **None** or a dict containing
key value pairs representing metrics keywords used in the
rules defined with strings.
.. _Visual Format Language: https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html#//apple_ref/doc/uid/TP40010853-CH27-SW1
.. _NSLayoutAttribute documentation: https://developer.apple.com/documentation/uikit/nslayoutattribute?language=objc
.. _NSLayoutRelation documentation: https://developer.apple.com/documentation/uikit/nslayoutrelation?language=objc
"""
_addAutoLayoutRules(self, rules, metrics)
def center(self):
"""
Center the window within the screen.
"""
self._window.center()
@python_method
def move(self, x, y, animate=True):
"""
Move the window by **x** units and **y** units.
"""
(l, b), (w, h) = self._window.frame()
l = l + x
b = b - y
self._window.setFrame_display_animate_(((l, b), (w, h)), True, animate)
@python_method
def resize(self, width, height, animate=True):
"""
Change the size of the window to **width** and **height**.
"""
l, t, w, h = self.getPosSize()
self.setPosSize((l, t, width, height), animate)
@python_method
def setDefaultButton(self, button):
"""
Set the default button in the window.
**button** will be bound to the Return and Enter keys.
"""
if not isinstance(button, VanillaBaseControl):
raise VanillaError("invalid object")
cell = button._nsObject.cell()
self._window.setDefaultButtonCell_(cell)
@python_method
def bind(self, event, callback):
"""
Bind a callback to an event.
**event** A string representing the desired event. The options are:
+-------------------+----------------------------------------------------------------------+
| *"should close"* | Called when the user attempts to close the window. This must return |
| | a bool indicating if the window should be closed or not. |
+-------------------+----------------------------------------------------------------------+
| *"close"* | Called immediately before the window closes. |
+-------------------+----------------------------------------------------------------------+
| *"move"* | Called immediately after the window is moved. |
+-------------------+----------------------------------------------------------------------+
| *"resize"* | Called immediately after the window is resized. |
+-------------------+----------------------------------------------------------------------+
| *"became main"* | Called immediately after the window has become the main window. |
+-------------------+----------------------------------------------------------------------+
| *"resigned main"* | Called immediately after the window has lost its main window status. |
+-------------------+----------------------------------------------------------------------+
| *"became key"* | Called immediately after the window has become the key window. |
+-------------------+----------------------------------------------------------------------+
| *"resigned key"* | Called immediately after the window has lost its key window status. |
+-------------------+----------------------------------------------------------------------+
*For more information about main and key windows, refer to the Cocoa `documentation`_
on the subject.*
.. _documentation: https://developer.apple.com/documentation/Cocoa/Conceptual/WinPanel/Concepts/ChangingMainKeyWindow.html
**callback** The callback that will be called when the event occurs.
It should accept a *sender* argument which will be the Window that called the callback.
::
from vanilla import Window
class WindowBindDemo:
def __init__(self):
self.w = Window((200, 200))
self.w.bind("move", self.windowMoved)
self.w.open()
def windowMoved(self, sender):
print("window moved!", sender)
WindowBindDemo()
"""
if event not in self._bindings:
self._bindings[event] = []
self._bindings[event].append(callback)
@python_method
def unbind(self, event, callback):
"""
Unbind a callback from an event.
**event** A string representing the desired event.
Refer to *bind* for the options.
**callback** The callback that has been bound to the event.
"""
self._bindings[event].remove(callback)
@python_method
def _alertBindings(self, key):
# test to see if the attr exists.
# this is necessary because NSWindow
# can move the window (and therefore
# call the delegate method which calls
# this method) before the super
# call in __init__ is complete.
returnValues = []
if hasattr(self, "_bindings"):
if key in self._bindings:
for callback in self._bindings[key]:
value = callback(self)
if value is not None:
# elimitate None return value
returnValues.append(value)
return all(returnValues)
def windowWillClose_(self, notification):
self.hide()
self._alertBindings("close")
# remove all bindings to prevent circular refs
if hasattr(self, "_bindings"):
del self._bindings
self._breakCycles()
# We must make sure that the window does _not_ get deallocated during
# windowWillClose_, or weird things happen, such as that the window
# below this window doesn't always properly gets activated. (For reference:
# this happens when closing with cmd-W, but not when clicking the close
# control.)
# Yet we want to get rid of the NSWindow object here, mostly as a flag
# so we can disallow re-opening windows. So we retain/autorelease the
# NSWindow, then get rid of our own reference.
self._window.retain()
self._window.autorelease()
self._window = None # make sure we can't re-open the window
self.autorelease() # see self.open()
def windowDidBecomeKey_(self, notification):
self._alertBindings("became key")
def windowDidResignKey_(self, notification):
self._alertBindings("resigned key")
def windowDidBecomeMain_(self, notification):
self._alertBindings("became main")
def windowDidResignMain_(self, notification):
self._alertBindings("resigned main")
def windowDidMove_(self, notification):
self._alertBindings("move")
def windowDidResize_(self, notification):
self._alertBindings("resize")
def windowDidEnterFullScreen_(self, notification):
self._alertBindings("enter full screen")
def windowWillEnterFullScreen_(self, notification):
self._alertBindings("will enter full screen")
def windowDidExitFullScreen_(self, notification):
self._alertBindings("exit full screen")
def windowWillExitFullScreen_(self, notification):
self._alertBindings("will exit full screen")
def windowShouldClose_(self, notification):
shouldClose = self._alertBindings("should close")
if shouldClose is None:
shouldClose = True
return shouldClose
# -------
# Toolbar
# -------
# credit where credit is due: much of this was learned
# from the PyObjC demo: WSTConnectionWindowControllerClass
@python_method
def addToolbar(self, toolbarIdentifier, toolbarItems, addStandardItems=True, displayMode="default", sizeStyle="default"):
"""
Add a toolbar to the window.
**toolbarIdentifier** A string representing a unique name for the toolbar.
**toolbarItems** An ordered list of dictionaries containing the following items:
+-------------------------------+---------------------------------------------------------------------------+
| *itemIdentifier* | A unique string identifier for the item. This is only used internally. |
+-------------------------------+---------------------------------------------------------------------------+
| *label* (optional) | The text label for the item. Defaults to *None*. |
+-------------------------------+---------------------------------------------------------------------------+
| *paletteLabel* (optional) | The text label shown in the customization palette. Defaults to *label*. |
+-------------------------------+---------------------------------------------------------------------------+
| *toolTip* (optional) | The tool tip for the item. Defaults to *label*. |
+-------------------------------+---------------------------------------------------------------------------+
| *imagePath* (optional) | A file path to an image. Defaults to *None*. |
+-------------------------------+---------------------------------------------------------------------------+
| *imageNamed* (optional) | The name of an image already loaded as a `NSImage`_ by the application. |
| | Defaults to *None*. |
+-------------------------------+---------------------------------------------------------------------------+
| *imageObject* (optional) | A `NSImage`_ object. Defaults to *None*. |
+-------------------------------+---------------------------------------------------------------------------+
| *imageTemplate* (optional) | A boolean representing if the image should converted to a template image. |
+-------------------------------+---------------------------------------------------------------------------+
| *selectable* (optional) | A boolean representing if the item is selectable or not. The default |
| | value is _False_. For more information on selectable toolbar items, refer |
| | to Apple's documentation. |
+-------------------------------+---------------------------------------------------------------------------+
| *view* (optional) | A `NSView`_ object to be used instead of an image. Defaults to *None*. |
+-------------------------------+---------------------------------------------------------------------------+
| *visibleByDefault* (optional) | If the item should be visible by default pass True to this argument. |
| | If the item should be added to the toolbar only through the customization |
| | palette, use a value of _False_. Defaults to _True_. |
+-------------------------------+---------------------------------------------------------------------------+
.. _NSImage: https://developer.apple.com/documentation/appkit/nsimage?language=objc
**addStandardItems** A boolean, specifying whether the standard Cocoa toolbar items
should be added. Defaults to *True*. If you set it to *False*, you must specify any
standard items manually in *toolbarItems*, by using the constants from the AppKit module:
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarSeparatorItemIdentifier* | The Separator item. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarSpaceItemIdentifier* | The Space item. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarFlexibleSpaceItemIdentifier* | The Flexible Space item. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarShowColorsItemIdentifier* | The Colors item. Shows the color panel. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarShowFontsItemIdentifier* | The Fonts item. Shows the font panel. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarCustomizeToolbarItemIdentifier* | The Customize item. Shows the customization palette. |
+-------------------------------------------+----------------------------------------------------------------+
| *NSToolbarPrintItemIdentifier* | The Print item. Refer to Apple's *NSToolbarItem* documentation |
| | for more information. |
+-------------------------------------------+----------------------------------------------------------------+
**displayMode** A string representing the desired display mode for the toolbar.
+-------------+
| "default" |
+-------------+
| "iconLabel" |
+-------------+
| "icon" |
+-------------+
| "label" |
+-------------+
**sizeStyle** A string representing the desired size for the toolbar
+-----------+
| "default" |
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
Returns a dictionary containing the created toolbar items, mapped by itemIdentifier.
"""
STANDARD_TOOLBAR_ITEMS = [
NSToolbarFlexibleSpaceItemIdentifier,
NSToolbarSpaceItemIdentifier,
NSToolbarSeparatorItemIdentifier,
NSToolbarCustomizeToolbarItemIdentifier,
NSToolbarPrintItemIdentifier,
NSToolbarShowFontsItemIdentifier,
NSToolbarShowColorsItemIdentifier,
]
# create the reference structures
self._toolbarItems = {}
self._toolbarDefaultItemIdentifiers = []
self._toolbarAllowedItemIdentifiers = []
self._toolbarCallbackWrappers = {}
self._toolbarSelectableItemIdentifiers = []
# create the toolbar items
for itemData in toolbarItems:
self._createToolbarItem(itemData)
if addStandardItems:
for standardItem in STANDARD_TOOLBAR_ITEMS:
if standardItem not in self._toolbarAllowedItemIdentifiers:
self._toolbarAllowedItemIdentifiers.append(standardItem)
# create the toolbar
toolbar = NSToolbar.alloc().initWithIdentifier_(toolbarIdentifier)
toolbar.setDelegate_(self)
toolbar.setAllowsUserCustomization_(True)
toolbar.setAutosavesConfiguration_(True)
displayModeMap = dict(
default=NSToolbarDisplayModeDefault,
iconLabel=NSToolbarDisplayModeIconAndLabel,
icon=NSToolbarDisplayModeIconOnly,
label=NSToolbarDisplayModeLabelOnly,
)
toolbar.setDisplayMode_(displayModeMap[displayMode])
sizeStyleMap = dict(
default=NSToolbarSizeModeDefault,
regular=NSToolbarSizeModeRegular,
small=NSToolbarSizeModeSmall)
toolbar.setSizeMode_(sizeStyleMap[sizeStyle])
self._window.setToolbar_(toolbar)
# Return the dict of toolbar items, so our caller can choose to
# keep references to them if needed.
return self._toolbarItems
def getToolbarItems(self):
if hasattr(self, "_toolbarItems"):
return self._toolbarItems
return {}
@python_method
def addToolbarItem(self, itemData, index=None):
"""
Add a toolbar item to the windows toolbar.
**itemData** item description with the same format as a toolbarItem description in `addToolbar`
**index** An integer, specifying the place to insert the toolbar itemIdentifier.
"""
if not hasattr(self, "_toolbarItems"):
raise VanillaError("window has not toolbar")
itemIdentifier = itemData.get("itemIdentifier")
self._createToolbarItem(itemData)
if itemData.get("visibleByDefault", True):
if index is not None:
self._toolbarDefaultItemIdentifiers.remove(itemIdentifier)
self._toolbarDefaultItemIdentifiers.insert(index, itemIdentifier)
index = self._toolbarDefaultItemIdentifiers.index(itemIdentifier)
self._window.toolbar().insertItemWithItemIdentifier_atIndex_(itemIdentifier, index)
@python_method
def removeToolbarItem(self, itemIdentifier):
"""
Remove a toolbar item by his identifier.
**itemIdentifier** A unique string identifier for the removed item.
"""
if not hasattr(self, "_toolbarItems"):
raise VanillaError("window has not toolbar")
if itemIdentifier not in self._toolbarItems:
raise VanillaError("itemIdentifier %r not in toolbar" % itemIdentifier)
item = self._toolbarItems[itemIdentifier]
toolbarItems = self._window.toolbar().items()
if item in toolbarItems:
## it can happen a user changed the toolbar manually
index = toolbarItems.indexOfObject_(item)
self._window.toolbar().removeItemAtIndex_(index)
self._toolbarAllowedItemIdentifiers.remove(itemIdentifier)
self._toolbarDefaultItemIdentifiers.remove(itemIdentifier)
del self._toolbarItems[itemIdentifier]
@python_method
def _createToolbarItem(self, itemData):
itemIdentifier = itemData.get("itemIdentifier")
if itemIdentifier is None:
raise VanillaError("toolbar item data must contain a unique itemIdentifier string")
if itemIdentifier in self._toolbarItems:
raise VanillaError("toolbar itemIdentifier is not unique: %r" % itemIdentifier)
if itemIdentifier not in self._toolbarAllowedItemIdentifiers:
self._toolbarAllowedItemIdentifiers.append(itemIdentifier)
if itemData.get("visibleByDefault", True):
self._toolbarDefaultItemIdentifiers.append(itemIdentifier)
if itemIdentifier.startswith("NS"):
# no need to create an actual item for a standard Cocoa toolbar item
return
label = itemData.get("label")
paletteLabel = itemData.get("paletteLabel", label)
toolTip = itemData.get("toolTip", label)
imagePath = itemData.get("imagePath")
imageNamed = itemData.get("imageNamed")
imageObject = itemData.get("imageObject")
imageTemplate = itemData.get("imageTemplate")
view = itemData.get("view")
callback = itemData.get("callback", None)
# create the NSImage if needed
if imagePath is not None:
image = NSImage.alloc().initWithContentsOfFile_(imagePath)
elif imageNamed is not None:
image = NSImage.imageNamed_(imageNamed)
elif imageObject is not None:
image = imageObject
else:
image = None
toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(itemIdentifier)
toolbarItem.setLabel_(label)
toolbarItem.setPaletteLabel_(paletteLabel)
toolbarItem.setToolTip_(toolTip)
if image is not None:
if imageTemplate is not None:
# only change the image template setting if its either True or False
image.setTemplate_(imageTemplate)
toolbarItem.setImage_(image)
elif view is not None:
toolbarItem.setView_(view)
toolbarItem.setMinSize_(view.frame().size)
toolbarItem.setMaxSize_(view.frame().size)
if callback is not None:
target = VanillaCallbackWrapper(callback)
toolbarItem.setTarget_(target)
toolbarItem.setAction_("action:")
self._toolbarCallbackWrappers[itemIdentifier] = target
if itemData.get("selectable", False):
self._toolbarSelectableItemIdentifiers.append(itemIdentifier)
self._toolbarItems[itemIdentifier] = toolbarItem
# Toolbar delegate methods
def toolbarDefaultItemIdentifiers_(self, anIdentifier):
return self._toolbarDefaultItemIdentifiers
def toolbarAllowedItemIdentifiers_(self, anIdentifier):
return self._toolbarAllowedItemIdentifiers
def toolbar_itemForItemIdentifier_willBeInsertedIntoToolbar_(self, toolbar, itemIdentifier, flag):
return self._toolbarItems.get(itemIdentifier)
def toolbarSelectableItemIdentifiers_(self, toolbar):
return self._toolbarSelectableItemIdentifiers
class FloatingWindow(Window):
"""
A window that floats above all other windows.
.. image:: /_images/FloatingWindow.png
To add a control to a window, simply set it as an attribute of the window.
::
from vanilla import FloatingWindow, Button, TextBox
class FloatingWindowDemo:
def __init__(self):
self.w = FloatingWindow((200, 70), "FloatingWindow Demo")
self.w.myButton = Button((10, 10, -10, 20), "My Button")
self.w.myTextBox = TextBox((10, 40, -10, 17), "My Text Box")
self.w.open()
FloatingWindowDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
**posSize** Tuple of form *(left, top, width, height)* representing the position
and size of the window. It may also be a tuple of form *(width, height)*.
In this case, the window will be positioned on screen automatically.
**title** The title to be set in the title bar of the window.
**minSize** Tuple of the form *(width, height)* representing the minimum size
that the window can be resized to.
**maxSize** Tuple of the form *(width, height)* representing the maximum size
that the window can be resized to.
**textured** Boolean value representing if the window should have a textured
appearance or not.
**autosaveName** A string representing a unique name for the window. If given,
this name will be used to store the window position and size in the application
preferences.
**closable** Boolean value representing if the window should have a close button
in the title bar.
**screen** A `NSScreen`_ object indicating the screen that the window
should be drawn to. When None the window will be drawn to the main screen.
.. _NSScreen: https://developer.apple.com/documentation/appkit/nsscreen?language=objc
"""
nsWindowStyleMask = NSTitledWindowMask | NSUtilityWindowMask
nsWindowClass = NSPanel
nsWindowLevel = NSFloatingWindowLevel
def __init__(self, posSize, title="", minSize=None, maxSize=None,
textured=False, autosaveName=None, closable=True,
initiallyVisible=True, screen=None):
super(FloatingWindow, self).__init__(posSize, title, minSize, maxSize,
textured, autosaveName, closable, initiallyVisible=initiallyVisible, screen=screen)
self._window.setBecomesKeyOnlyIfNeeded_(True)
def show(self):
"""
Show the window if it is hidden.
"""
# don't make key!
self._window.orderFront_(None)
class HUDFloatingWindow(FloatingWindow):
"""
A window that floats above all other windows and has the HUD appearance.
.. image:: /_images/HUDFloatingWindow.png
To add a control to a window, simply set it as an attribute of the window.
::
from vanilla import *
class HUDFloatingWindowDemo:
def __init__(self):
self.w = HUDFloatingWindow((200, 70), "HUDFloatingWindow Demo")
self.w.myButton = Button((10, 10, -10, 20), "My Button")
self.w.myTextBox = TextBox((10, 40, -10, 17), "My Text Box")
self.w.open()
HUDFloatingWindowDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
**posSize** Tuple of form *(left, top, width, height)* representing the position
and size of the window. It may also be a tuple of form *(width, height)*.
In this case, the window will be positioned on screen automatically.
**title** The title to be set in the title bar of the window.
**minSize** Tuple of the form *(width, height)* representing the minimum size
that the window can be resized to.
**maxSize** Tuple of the form *(width, height)* representing the maximum size
that the window can be resized to.
**textured** Boolean value representing if the window should have a textured
appearance or not.
**autosaveName** A string representing a unique name for the window.
If given, this name will be used to store the window position and size in
the application preferences.
**closable** Boolean value representing if the window should have a close button
in the title bar.
**screen** A `NSScreen`_ object indicating the screen that the window
should be drawn to. When None the window will be drawn to the main screen.
.. _NSScreen: https://developer.apple.com/documentation/appkit/nsscreen?language=objc
"""
nsWindowStyleMask = NSHUDWindowMask | NSUtilityWindowMask | NSTitledWindowMask | NSBorderlessWindowMask
class Sheet(Window):
"""
A window that is attached to another window.
.. image:: /_images/Sheet.png
To add a control to a sheet, simply set it as an attribute of the sheet.::
from vanilla import Window, Sheet, Button
class SheetDemo:
def __init__(self):
self.w = Window((240, 140), "Sheet Demo")
self.w.openSheet = Button((10, -30, -10, 20),
"open sheet", callback=self.openSheetCallback)
self.w.open()
def openSheetCallback(self, sender):
self.sheet = Sheet((160, 70), self.w)
self.sheet.closeSheet = Button((10, -30, -10, 20),
"close sheet", callback=self.closeSheetCallback)
self.sheet.open()
def closeSheetCallback(self, sender):
self.sheet.close()
del self.sheet
SheetDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
**posSize** Tuple of form *(width, height)* representing the size of the sheet.
**parentWindow** The window that the sheet should be attached to.
**minSize** Tuple of the form *(width, height)* representing the minimum size
that the sheet can be resized to.
**maxSize** Tuple of the form *(width, height)* representing the maximum size
that the sheet can be resized to.
**autosaveName** A string representing a unique name for the sheet. If given,
this name will be used to store the sheet size in the application preferences.
"""
def __init__(self, posSize, parentWindow, minSize=None, maxSize=None,
autosaveName=None):
if isinstance(parentWindow, Window):
parentWindow = parentWindow._window
self.parentWindow = parentWindow
textured = bool(parentWindow.styleMask() & NSTexturedBackgroundWindowMask)
super(Sheet, self).__init__(posSize, "", minSize, maxSize, textured,
autosaveName=autosaveName)
def open(self):
"""
Open the window.
"""
parentWindow = self.parentWindow
NSApp().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(
self._window, parentWindow, None, None, 0)
# See Window.open():
self.retain()
self._validateMinMaxSize()
| {
"repo_name": "typesupply/vanilla",
"path": "Lib/vanilla/vanillaWindows.py",
"copies": "1",
"size": "49777",
"license": "mit",
"hash": -2328158993842472000,
"line_mean": 43.8441441441,
"line_max": 841,
"alpha_frac": 0.5451513751,
"autogenerated": false,
"ratio": 4.880098039215686,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0015160213697024644,
"num_lines": 1110
} |
from Foundation import NSObject
from AppKit import NSBeep
from grow.server import manager
class Pod(NSObject, manager.PodServer):
def __new__(cls, *args, **kwargs):
return cls.alloc().init()
class GrowLauncherModel(NSObject):
"""A delegate and a data source for NSTableView."""
def __init__(self):
self.servers = manager.PodServer.load()
def __new__(cls, *args, **kwargs):
return cls.alloc().init()
# NSTableViewDataSource methods.
def numberOfRowsInTableView_(self, view):
return len(self.servers)
def tableView_objectValueForTableColumn_row_(self, view, col, item):
pod = self.servers[item]
parts = {
'root': pod.root,
'port': pod.port,
'revision_status': pod.revision_status,
'server_status': pod.server_status,
}
return parts.get(col.identifier(), None)
def tableView_shouldEditTableColumn_item_(self, view, col, item):
return True
# NSOutlineViewDataSource methods.
def outlineView_numberOfChildrenOfItem_(self, view, item):
if item is None:
item = self.root
return len(item)
def outlineView_child_ofItem_(self, view, child, item):
if item is None:
item = self.root
return item.getChild(child)
def outlineView_isItemExpandable_(self, view, item):
if item is None:
item = self.root
return item.isExpandable()
def outlineView_objectValueForTableColumn_byItem_(self, view, col, item):
if item is None:
item = self.root
return getattr(item, col.identifier())
# Delegate methods.
def outlineView_shouldEditTableColumn_item_(self, view, col, item):
return item.isEditable()
| {
"repo_name": "jeremydw/macgrow",
"path": "macgrow/GrowLauncherModel.py",
"copies": "1",
"size": "1641",
"license": "mit",
"hash": 2544841794492075500,
"line_mean": 24.640625,
"line_max": 75,
"alpha_frac": 0.6825106642,
"autogenerated": false,
"ratio": 3.598684210526316,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.4781194874726316,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSObject
from AppKit import NSTabView, NSTabViewItem, NSNoTabsNoBorder, NSFont
from vanilla.vanillaBase import VanillaBaseObject, _breakCycles, _sizeStyleMap, VanillaCallbackWrapper, \
_reverseSizeStyleMap
class VanillaTabItem(VanillaBaseObject):
nsTabViewItemClass = NSTabViewItem
def __init__(self, title):
self._autoLayoutViews = {}
self._tabItem = self.nsTabViewItemClass.alloc().initWithIdentifier_(title)
self._tabItem.setLabel_(title)
def _getContentView(self):
return self._tabItem.view()
def _breakCycles(self):
_breakCycles(self._tabItem.view())
self._autoLayoutViews.clear()
class VanillaTabsDelegate(NSObject):
def tabView_didSelectTabViewItem_(self, tabView, tabViewItem):
if hasattr(self, "_target"):
self._target.action_(tabView.vanillaWrapper())
class Tabs(VanillaBaseObject):
"""
A set of tabs attached to a window. Each tab is capable of containing controls.
.. image:: /_images/Tabs.png
To add a control to a tab, simply set it as an attribute of the tab.
::
from vanilla import Window, Tabs, TextBox
class TabsDemo:
def __init__(self):
self.w = Window((250, 100))
self.w.tabs = Tabs((10, 10, -10, -10), ["Tab One", "Tab Two"])
tab1 = self.w.tabs[0]
tab1.text = TextBox((10, 10, -10, -10), "This is tab 1")
tab2 = self.w.tabs[1]
tab2.text = TextBox((10, 10, -10, -10), "This is tab 2")
self.w.open()
TabsDemo()
No special naming is required for the attributes. However, each attribute
must have a unique name.
To retrieve a particular tab, access it by index::
myTab = self.w.tabs[0]
**posSize** Tuple of form *(left, top, width, height)* or *"auto"* representing the position
and size of the tabs.
**titles** An ordered list of tab titles.
**callback** The method to be called when the user selects a new tab.
**sizeStyle** A string representing the desired size style of the tabs.
The options are:
+-----------+
| "regular" |
+-----------+
| "small" |
+-----------+
| "mini" |
+-----------+
"""
nsTabViewClass = NSTabView
vanillaTabViewItemClass = VanillaTabItem
allFrameAdjustments = {
# The sizeStyle will be part of the
# className used for the lookup here.
"Tabs-mini": (-7, -10, 14, 12),
"Tabs-small": (-7, -10, 14, 13),
"Tabs-regular": (-7, -10, 14, 16),
}
def __init__(self, posSize, titles=["Tab"], callback=None, sizeStyle="regular", showTabs=True):
self._setupView(self.nsTabViewClass, posSize) # hold off on setting callback
self._setSizeStyle(sizeStyle)
self._tabItems = []
for title in titles:
tab = self.vanillaTabViewItemClass(title)
self._tabItems.append(tab)
self._nsObject.addTabViewItem_(tab._tabItem)
if not showTabs:
self._nsObject.setTabViewType_(NSNoTabsNoBorder)
self._nsObject.setDrawsBackground_(False)
# now that the tabs are all set, set the callback.
# this is done because the callback will be called
# while the tabs are being added.
if callback is not None:
self._setCallback(callback)
def getNSTabView(self):
"""
Return the `NSTabView`_ that this object wraps.
.. _NSTabView: https://developer.apple.com/documentation/appkit/nstabview?language=objc
"""
return self._nsObject
def _adjustPosSize(self, frame):
if self._nsObject.tabViewType() == NSNoTabsNoBorder:
return frame
sizeStyle = _reverseSizeStyleMap[self._nsObject.controlSize()]
tabsType = "Tabs-" + sizeStyle
self.frameAdjustments = self.allFrameAdjustments[tabsType]
return super(Tabs, self)._adjustPosSize(frame)
def _setCallback(self, callback):
if callback is not None:
self._target = VanillaCallbackWrapper(callback)
delegate = self._nsObject.delegate()
if delegate is None:
self._delegate = delegate = VanillaTabsDelegate.alloc().init()
self._nsObject.setDelegate_(delegate)
delegate._target = self._target
def _setSizeStyle(self, value):
value = _sizeStyleMap[value]
self._nsObject.setControlSize_(value)
font = NSFont.systemFontOfSize_(NSFont.systemFontSizeForControlSize_(value))
self._nsObject.setFont_(font)
def __getitem__(self, index):
return self._tabItems[index]
def _breakCycles(self):
super(Tabs, self)._breakCycles()
for item in self._tabItems:
item._breakCycles()
def get(self):
"""
Get the index of the selected tab.
"""
item = self._nsObject.selectedTabViewItem()
index = self._nsObject.indexOfTabViewItem_(item)
return index
def set(self, value):
"""
Set the selected tab.
**value** The index of the tab to be selected.
"""
self._nsObject.selectTabViewItemAtIndex_(value)
| {
"repo_name": "typesupply/vanilla",
"path": "Lib/vanilla/vanillaTabs.py",
"copies": "1",
"size": "5287",
"license": "mit",
"hash": -1776383616702785500,
"line_mean": 31.237804878,
"line_max": 105,
"alpha_frac": 0.6075278986,
"autogenerated": false,
"ratio": 3.8732600732600733,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.9977757271262382,
"avg_score": 0.0006061401195380375,
"num_lines": 164
} |
from Foundation import NSObject
from AppKit import NSTextView, NSScrollView, NSBezelBorder, NSViewWidthSizable, NSViewHeightSizable
from vanilla.nsSubclasses import getNSSubclass
from vanilla.vanillaBase import VanillaBaseObject, VanillaCallbackWrapper
from vanilla.py23 import unicode
class VanillaTextEditorDelegate(NSObject):
def textDidChange_(self, notification):
if hasattr(self, "_target"):
textView = notification.object()
self._target.action_(textView)
class TextEditor(VanillaBaseObject):
"""
Standard long text entry control.::
from vanilla import *
class TextEditorDemo(object):
def __init__(self):
self.w = Window((200, 200))
self.w.textEditor = TextEditor((10, 10, -10, 22),
callback=self.textEditorCallback)
self.w.open()
def textEditorCallback(self, sender):
print("text entry!", sender.get())
TextEditorDemo()
**posSize** Tuple of form *(left, top, width, height)* representing
the position and size of the text entry control.
**text** The text to be displayed in the text entry control.
**callback** The method to be called when the user presses the text
entry control.
**readOnly** Boolean representing if the text can be edited or not.
**checksSpelling** Boolean representing if spelling should be automatically
checked or not.
"""
nsScrollViewClass = NSScrollView
nsTextViewClass = NSTextView
delegateClass = VanillaTextEditorDelegate
def __init__(self, posSize, text="", callback=None, readOnly=False, checksSpelling=False):
self._posSize = posSize
self._nsObject = self.nsScrollViewClass.alloc().init() # no need to do getNSSubclass() here
self._nsObject.setHasVerticalScroller_(True)
self._nsObject.setBorderType_(NSBezelBorder)
self._nsObject.setDrawsBackground_(True)
self._textView = getNSSubclass(self.nsTextViewClass)(self)
self._textView.setAllowsUndo_(True)
self._textView.setString_(text)
self._textView.setContinuousSpellCheckingEnabled_(checksSpelling)
self._textView.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable)
self._textView.setEditable_(not readOnly)
self._nsObject.setDocumentView_(self._textView)
# do the base object init methods
self._setCallback(callback)
self._setAutosizingFromPosSize(posSize)
def _testForDeprecatedAttributes(self):
super(TextEditor, self)._testForDeprecatedAttributes()
from warnings import warn
if hasattr(self, "_textViewClass"):
warn(DeprecationWarning("The _textViewClass attribute is deprecated. Use the nsTextViewClass attribute."))
self.nsTextViewClass = self._textViewClass
def getNSScrollView(self):
"""
Return the *NSScrollView* that this object wraps.
"""
return self._nsObject
def getNSTextView(self):
"""
Return the *NSTextView* that this object wraps.
"""
return self._textView
def _setCallback(self, callback):
if callback is not None:
self._target = VanillaCallbackWrapper(callback)
delegate = self._textView.delegate()
if delegate is None:
self._textViewDelegate = delegate = self.delegateClass.alloc().init()
self._textView.setDelegate_(delegate)
delegate._target = self._target
def get(self):
"""
Get the contents of the text entry control.
"""
return unicode(self._textView.string())
def set(self, value):
"""
Set the contents of the text box.
**value** A string representing the contents of the text box.
"""
self._textView.setString_(value)
def selectAll(self):
"""
Select all text in the text entry control.
"""
self._textView.selectAll_(None)
#def selectLine(self, lineNumber, charOffset=0):
# raise NotImplementedError
#
#def getSelection(self):
# """
# Get the selected text.
# """
# selStart, selEnd = self._textView.selectedRange()
# return selStart, selStart+selEnd
#
#def setSelection(self, selStart, selEnd):
# selEnd = selEnd - selStart
# self._textView.setSelectedRange_((selStart, selEnd))
#
#def getSelectedText(self):
# selStart, selEnd = self.getSelection()
# return self._textView.string()[selStart:selEnd]
#
#def expandSelection(self):
# raise NotImplementedError
#
#def insert(self, text):
# self._textView.insert_(text)
| {
"repo_name": "moyogo/vanilla",
"path": "Lib/vanilla/vanillaTextEditor.py",
"copies": "1",
"size": "4795",
"license": "mit",
"hash": 334249094878770300,
"line_mean": 33.0070921986,
"line_max": 118,
"alpha_frac": 0.6412930136,
"autogenerated": false,
"ratio": 4.105308219178082,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5246601232778082,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSObject
from objc import *
from AppKit import NSBezierPath
from fieldMath import *
#____________________________________________________________
class CGraphModel(NSObject):
def init(self):
self.field = [1.0, 1.12, 0.567]
self.phase = [degToRad(0), degToRad(152.6), degToRad(312.9-360)]
self.RMSGain = 0
self.spacing = degToRad(90)
return self
def getGraph(self):
path = NSBezierPath.bezierPath()
maxMag = 0
mag = self.fieldValue(0)
maxMag = max(maxMag, mag)
path.moveToPoint_(polarToRect((mag, 0)))
for deg in range(1, 359, 1):
r = (deg/180.0)*pi
mag = self.fieldValue(r)
maxMag = max(maxMag, mag)
path.lineToPoint_(polarToRect((mag, r)))
path.closePath()
return path, maxMag;
def fieldGain(self):
gain = 0
Et = self.field[0] + self.field[1] + self.field[2]
if Et: # Don't want to divide by zero in the pathological case
spacing = [0, self.spacing, 2*self.spacing]
# This could easily be optimized--but this is just anexample :-)
for i in range(3):
for j in range(3):
gain += self.field[i]*self.field[j] * cos(self.phase[j]-self.phase[i]) * bessel(spacing[j]-spacing[i])
gain = sqrt(gain) / Et
self.RMSGain = gain
return gain
def fieldValue(self, a):
# The intermedate values are used to more closely match standard field equations nomenclature
E0 = self.field[0]
E1 = self.field[1]
E2 = self.field[2]
B0 = self.phase[0]
B1 = self.phase[1] + self.spacing * cos(a)
B2 = self.phase[2] + 2 * self.spacing * cos(a)
phix = sin(B0) * E0 + sin(B1) * E1 + sin(B2) * E2
phiy = cos(B0) * E0 + cos(B1) * E1 + cos(B2) * E2
mag = hypot(phix, phiy)
return mag
def setField(self, tower, field):
self.field[tower] = field
def getField(self, tower):
return self.field[tower]
def setPhase(self, tower, phase):
self.phase[tower] = phase
def getPhase(self, tower):
return self.phase[tower]
def setSpacing(self, spacing):
self.spacing = spacing
def getSpacing(self):
return self.spacing
| {
"repo_name": "albertz/music-player",
"path": "mac/pyobjc-framework-Cocoa/Examples/AppKit/FieldGraph/CGraphModel.py",
"copies": "3",
"size": "2373",
"license": "bsd-2-clause",
"hash": -5393417703185170000,
"line_mean": 28.2962962963,
"line_max": 122,
"alpha_frac": 0.5465655289,
"autogenerated": false,
"ratio": 3.3564356435643563,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 1,
"avg_score": 0.0018060925232708813,
"num_lines": 81
} |
from Foundation import NSObject, NSBundle
from objc import selector, getClassList, objc_object, IBOutlet, IBAction
import objc
import AppKit
objc.setVerbose(1)
try:
import AddressBook
except ImportError:
pass
try:
import PreferencePanes
except ImportError:
pass
try:
import InterfaceBuilder
except ImportError:
pass
WRAPPED={}
class Wrapper (NSObject):
"""
NSOutlineView doesn't retain values, which means we cannot use normal
python values as values in an outline view.
"""
def init_(self, value):
self.value = value
return self
def __str__(self):
return '<Wrapper for %s>'%self.value
def description(self):
return str(self)
def wrap_object(obj):
if WRAPPED.has_key(obj):
return WRAPPED[obj]
else:
WRAPPED[obj] = Wrapper.alloc().init_(obj)
return WRAPPED[obj]
def unwrap_object(obj):
if obj is None:
return obj
return obj.value
methodIdentifier = {
'objc_method':0,
'python_method':1,
'signature':2
}
def classPath(cls):
if cls == objc_object:
return ''
elif cls.__bases__[0] == objc_object:
return cls.__name__
else:
return '%s : %s'%(classPath(cls.__bases__[0]), cls.__name__)
SYSFRAMEWORKS_DIR='/System/Library/Frameworks/'
def classBundle(cls):
framework = NSBundle.bundleForClass_(cls).bundlePath()
if framework.startswith(SYSFRAMEWORKS_DIR):
framework = framework[len(SYSFRAMEWORKS_DIR):]
if framework.endswith('.framework'):
framework = framework[:-len('.framework')]
return framework
class ClassesDataSource (NSObject):
__slots__ = ('_classList', '_classTree', '_methodInfo', '_classInfo')
classLabel = IBOutlet()
classTable = IBOutlet()
frameworkLabel = IBOutlet()
methodTable = IBOutlet()
searchBox = IBOutlet()
window = IBOutlet()
def clearClassInfo(self):
self._methodInfo = []
self.methodTable.reloadData()
self.window.setTitle_('iClass')
def setClassInfo(self, cls):
self.window.setTitle_('iClass: %s'%cls.__name__)
self.classLabel.setStringValue_(classPath(cls))
self.frameworkLabel.setStringValue_(classBundle(cls))
self._methodInfo = []
for nm, meth in cls.pyobjc_instanceMethods.__dict__.items():
if not isinstance(meth, selector):
continue
self._methodInfo.append(
('-'+meth.selector, nm, meth.signature))
for nm, meth in cls.pyobjc_classMethods.__dict__.items():
if not isinstance(meth, selector):
continue
self._methodInfo.append(
('+'+meth.selector, nm, meth.signature))
self._methodInfo.sort()
self.methodTable.reloadData()
def outlineViewSelectionDidChange_(self, notification):
rowNr = self.classTable.selectedRow()
if rowNr == -1:
self.clearClassInfo()
else:
item = self.classTable.itemAtRow_(rowNr)
self.setClassInfo(unwrap_object(item))
def showClass(self, cls):
# First expand the tree (to make item visible)
super = cls.__bases__[0]
if super == objc_object:
return
self.showClass(super)
item = wrap_object(super)
rowNr = self.classTable.rowForItem_(item)
self.classTable.expandItem_(item)
def selectClass(self, cls):
self.showClass(cls)
item = wrap_object(cls)
rowNr = self.classTable.rowForItem_(item)
self.classTable.scrollRowToVisible_(rowNr)
self.classTable.selectRow_byExtendingSelection_(rowNr, False)
@IBAction
def searchClass_(self, event):
val = self.searchBox.stringValue()
if not val:
return
found = None
for cls in self._classTree.keys():
if not cls: continue
if cls.__name__ == val:
self.setClassInfo(cls)
self.selectClass(cls)
return
elif cls.__name__.startswith(val):
if not found:
found = cls
elif len(cls.__name__) > len(found.__name__):
found = cls
# mvl 2009-03-02: fix case where no match is found caused exception:
if (found is None): return
self.setClassInfo(found)
self.selectClass(found)
def refreshClasses(self):
self._classList = getClassList()
self._classTree = {}
self._methodInfo = []
for cls in self._classList:
super = cls.__bases__[0]
if super == objc_object:
super = None
else:
super = super
if not self._classTree.has_key(cls):
self._classTree[cls] = []
if self._classTree.has_key(super):
self._classTree[super].append(cls)
else:
self._classTree[super] = [ cls ]
for lst in self._classTree.values():
lst.sort()
def init(self):
self._classInfo = getClassList()
self.refreshClasses()
return self
def awakeFromNib(self):
self._classInfo = getClassList()
self.refreshClasses()
def outlineView_child_ofItem_(self, outlineview, index, item):
return wrap_object(self._classTree[unwrap_object(item)][index])
def outlineView_isItemExpandable_(self, outlineview, item):
return len(self._classTree[unwrap_object(item)]) != 0
def outlineView_numberOfChildrenOfItem_(self, outlineview, item):
return len(self._classTree[unwrap_object(item)])
def outlineView_objectValueForTableColumn_byItem_(self, outlineview, column, item):
if item is None:
return '<None>'
else:
v = item.value
return v.__name__
def numberOfRowsInTableView_(self, aTableView):
return len(self._methodInfo)
def tableView_objectValueForTableColumn_row_(self,
aTableView, aTableColumn, rowIndex):
return self._methodInfo[rowIndex][methodIdentifier[aTableColumn.identifier()]]
| {
"repo_name": "Khan/pyobjc-framework-Cocoa",
"path": "Examples/AppKit/iClass/datasource.py",
"copies": "3",
"size": "6216",
"license": "mit",
"hash": 3254778077971088400,
"line_mean": 27.5137614679,
"line_max": 87,
"alpha_frac": 0.5937902188,
"autogenerated": false,
"ratio": 3.9795134443021767,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.6073303663102176,
"avg_score": null,
"num_lines": null
} |
from Foundation import NSURL
from AppKit import NSDragOperationNone, NSBezelBorder
from Quartz import PDFView, PDFThumbnailView, PDFDocument
from vanilla import Group
epsPasteBoardType = "CorePasteboardFlavorType 0x41494342"
class DrawBotPDFThumbnailView(PDFThumbnailView):
def draggingUpdated_(self, draggingInfo):
return NSDragOperationNone
class ThumbnailView(Group):
nsViewClass = DrawBotPDFThumbnailView
def setDrawView(self, view):
self.getNSView().setPDFView_(view.getNSView())
def getSelection(self):
try:
# sometimes this goes weirdly wrong...
selection = self.getNSView().selectedPages()
except:
return -1
if selection:
for page in selection:
document = page.document()
index = document.indexForPage_(page)
return index
return -1
class DrawBotPDFView(PDFView):
def performKeyEquivalent_(self, event):
# catch a bug in PDFView
# cmd + ` causes a traceback
# DrawBot[15705]: -[__NSCFConstantString characterAtIndex:]: Range or index out of bounds
try:
return super(DrawBotPDFView, self).performKeyEquivalent_(event)
except:
return False
class DrawView(Group):
nsViewClass = DrawBotPDFView
def __init__(self, posSize):
super(DrawView, self).__init__(posSize)
pdfView = self.getNSView()
pdfView.setAutoScales_(True)
view = pdfView.documentView()
if view is not None:
scrollview = view.enclosingScrollView()
scrollview.setBorderType_(NSBezelBorder)
def get(self):
pdf = self.getNSView().document()
if pdf is None:
return None
return pdf.dataRepresentation()
def set(self, pdfData):
pdf = PDFDocument.alloc().initWithData_(pdfData)
self.setPDFDocument(pdf)
def setPath(self, path):
url = NSURL.fileURLWithPath_(path)
document = PDFDocument.alloc().initWithURL_(url)
self.setPDFDocument(document)
def setPDFDocument(self, document):
if document is None:
document = PDFDocument.alloc().init()
self.getNSView().setDocument_(document)
def getPDFDocument(self):
return self.getNSView().document()
def setScale(self, scale):
self.getNSView().setScaleFactor_(scale)
def scale(self):
return self.getNSView().scaleFactor()
def scrollDown(self):
document = self.getNSView().documentView()
document.scrollPoint_((0, 0))
def scrollToPageIndex(self, index):
pdf = self.getPDFDocument()
if pdf is None:
self.scrollDown()
elif 0 <= index < pdf.pageCount():
try:
# sometimes this goes weirdly wrong...
page = pdf.pageAtIndex_(index)
self.getNSView().goToPage_(page)
except:
self.scrollDown()
else:
self.scrollDown()
| {
"repo_name": "schriftgestalt/drawbot",
"path": "drawBot/ui/drawView.py",
"copies": "4",
"size": "3054",
"license": "bsd-2-clause",
"hash": -8564963319781553000,
"line_mean": 27.5420560748,
"line_max": 97,
"alpha_frac": 0.6178781925,
"autogenerated": false,
"ratio": 4.0828877005347595,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.670076589303476,
"avg_score": null,
"num_lines": null
} |
from foundation.Message import Message
import logging
import FoundationException
import xml.dom.minidom
import uuid
'''
The Bid class defines methods required for the operation of the
offers, including values and decision variables, as well as
Id, service provider, and service to be offered.
'''
class Bid(object):
ACTIVE = 1
INACTIVE = 0
def __init__(self):
# These are the offered variables for customers.
self._decision_variables = {}
self._status = Bid.ACTIVE
self._unitaryCost = 0
self._unitaryProfit = 0
self._parent = None # Bids that origin this bid.
self._creation_period = 0
self._providerBid = None # bid that generates this bid.
self._numAncestors = 0 # This indicates how many ancestors a bid have.
# These are the specific requirements with respect to quality
# that providers should cover with own resources,
# if not defined are equal to those in specified in the decision variables.
self._qualityRequirements = {}
self._capacity = 0
'''
This method receives the offer Id, service provider Id, and
service Id as parameters and assigns to related variables.
'''
def setValues(self, bidId, provider, service):
self._provider = provider
self._service = service
self._bidId = bidId
'''
This method receives the offer Id as a parameter and assigns it.
'''
def setId(self, bidId):
self._bidId = bidId
'''
This method sets a value to the decision variable.
'''
def setDecisionVariable(self, decisionVariable, value):
self._decision_variables[decisionVariable] = value
'''
This method returns the decision variable.
'''
def getDecisionVariable(self, decisionVariableId):
#logging.debug('stating getDecisionVariable - Parameters:' + decisionVariableId)
if decisionVariableId in self._decision_variables:
return self._decision_variables[decisionVariableId]
else:
raise FoundationException("The Decision variable is not part of the offer")
'''
This method establishes the unitary cost of the offer.
'''
def setUnitaryCost(self, unitaryCost):
self._unitaryCost = unitaryCost
'''
This method returns the unitary cost of the offer.
'''
def getUnitaryCost(self):
return self._unitaryCost
'''
This method establishes the unitary profit of the offer
'''
def setUnitaryProfit(self, unitaryProfit):
self._unitaryProfit = unitaryProfit
'''
This method returns the unitary profit of the offer
'''
def getUnitaryProfit(self):
return self._unitaryProfit
'''
This method establishes the period when the bid was created
'''
def setCreationPeriod(self, creationPeriod):
self._creation_period = creationPeriod
'''
This method returns the period when the bid was created
'''
def getCreationPeriod(self):
return self._creation_period
'''
This method transform the object into XML.
'''
def getText(self, nodelist):
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc)
'''
This method assigns a name and value to a decision variable.
'''
def handleDecisionVariable(self, variableXmlNode):
nameElement = variableXmlNode.getElementsByTagName("Name")[0]
name = self.getText(nameElement.childNodes)
valueElement = variableXmlNode.getElementsByTagName("Value")[0]
value = float(self.getText(valueElement.childNodes))
self.setDecisionVariable(name, value)
'''
This method converts the object from XML to string.
'''
def setFromXmlNode(self,bidXmlNode):
bidIdElement = bidXmlNode.getElementsByTagName("Id")[0]
bidId = self.getText(bidIdElement.childNodes)
self._bidId = bidId
providerElement = bidXmlNode.getElementsByTagName("Provider")[0]
provider = self.getText(providerElement.childNodes)
self._provider = provider
serviceElement = bidXmlNode.getElementsByTagName("Service")[0]
service = self.getText(serviceElement.childNodes)
self._service = service
statusElement = bidXmlNode.getElementsByTagName("Status")[0]
status = self.getText(statusElement.childNodes)
if (status == "inactive"):
self._status = Bid.INACTIVE
else:
self._status = Bid.ACTIVE
parentBidElement = bidXmlNode.getElementsByTagName("ParentBid")[0]
parentBidId = self.getText(parentBidElement.childNodes)
if len(parentBidId) > 0:
parentBid = Bid()
parentBid.setId(parentBidId)
self.insertParentBid(parentBid)
variableXmlNodes = bidXmlNode.getElementsByTagName("Decision_Variable")
for variableXmlNode in variableXmlNodes:
self.handleDecisionVariable(variableXmlNode)
'''
This method gets offer Id.
'''
def getId(self):
return self._bidId
'''
This method gets the provider Id.
'''
def getProvider(self):
return self._provider
'''
This method returns the offer service.
'''
def getService(self):
return self._service
'''
This method sets the offer status.
'''
def setStatus(self, status):
self._status = status
def __str__(self):
val_return = 'Id:' + self._bidId + ' '
val_return = val_return + ':Provider:' + self._provider + ' '
val_return = val_return + ':Service:' + self._service + ' '
val_return = val_return + ':Status:' + self.getStatusStr() + ' '
for decisionVariable in self._decision_variables:
val_return = val_return + ':desc_var:' + decisionVariable + ':value:'+ str(self._decision_variables[decisionVariable]) + ' '
return val_return
'''
This method gets the offer status in a string format.
'''
def getStatusStr(self):
if self._status == Bid.INACTIVE:
return "inactive"
else:
return "active"
def isActive(self):
if self._status == Bid.INACTIVE:
return False
else:
return True
'''
This method creates the offer message to be sent to the
marketplace.
'''
def to_message(self):
messageBid = Message('')
messageBid.setMethod(Message.RECEIVE_BID)
messageBid.setParameter('Id', self._bidId)
messageBid.setParameter('Provider', self._provider)
messageBid.setParameter('Service', self._service)
messageBid.setParameter('Status', self.getStatusStr())
messageBid.setParameter('UnitaryProfit', str(self.getUnitaryProfit() ))
messageBid.setParameter('UnitaryCost', str(self.getUnitaryCost() ))
messageBid.setParameter('Capacity', str(self.getCapacity() ))
messageBid.setParameter('CreationPeriod', str(self.getCreationPeriod() ))
if (self._parent != None):
messageBid.setParameter('ParentBid', self._parent.getId())
else:
messageBid.setParameter('ParentBid', ' ')
for decisionVariable in self._decision_variables:
messageBid.setParameter(decisionVariable, str(self._decision_variables[decisionVariable]))
return messageBid
'''
Sets the general information
'''
def setFromMessage(self, service, message):
self.setValues(message.getParameter("Id"), message.getParameter("Provider"), message.getParameter("Service"))
status = message.getParameter("Status")
if (status == "inactive"):
self._status = Bid.INACTIVE
else:
self._status = Bid.ACTIVE
# Sets the decision variables
for decision_variable in service._decision_variables:
value = float(message.getParameter(decision_variable))
self.setDecisionVariable(decision_variable, value)
'''
This methods establish if the offer pass as parameter has the
same decision variables.
'''
def isEqual(self, bidtoCompare):
equal = True
for decisionVariable in self._decision_variables:
if ( self._decision_variables[decisionVariable] == bidtoCompare.getDecisionVariable(decisionVariable)):
pass
else:
equal = False
break
return equal
'''
This methods establish if the offer pass as parameter has the
same decision variables.
'''
def isAlmostEqual(self, bidtoCompare, rounddecimals):
equal = True
for decisionVariable in self._decision_variables:
myDecisionVar = round(self._decision_variables[decisionVariable], rounddecimals)
otherDecisionVar = round(bidtoCompare.getDecisionVariable(decisionVariable), rounddecimals)
if ( myDecisionVar == otherDecisionVar):
pass
else:
equal = False
break
return equal
'''
This method inserts the bid as parameter as a parent of this bid.
'''
def insertParentBid(self, bid):
self._parent = bid
'''
This method establishes the provider bid (object).
'''
def setProviderBid(self, providerBid):
self._providerBid = providerBid
'''
This method establishes the capacity for this bid (object).
'''
def setCapacity(self, capacity):
self._capacity = capacity
def getCapacity(self):
return self._capacity
def getParentBid(self):
return self._parent
'''
This method returns the associated bid of the provider that helps to create this bid.
'''
def getProviderBid(self):
return self._providerBid
'''
This method establihes a quality requirement for the bid.
'''
def setQualityRequirement(self, decisionVariable, value):
if decisionVariable in self._qualityRequirements:
raise FoundationException("Decision variable is already included")
else:
self._qualityRequirements[decisionVariable] = value
'''
This method returns the decision variable.
'''
def getQualityRequirement(self, decisionVariableId):
#logging.debug('stating getDecisionVariable - Parameters:' + decisionVariableId)
if decisionVariableId in self._qualityRequirements:
return self._qualityRequirements[decisionVariableId]
else:
if decisionVariableId in self._decision_variables:
return self._decision_variables[decisionVariableId]
else:
raise FoundationException("The Decision variable is not part of the offer")
def removeQualityRequirements(self):
(self._qualityRequirements).clear()
'''
This method gets the number of predecessor that a bid has
'''
def getNumberPredecessor(self):
return self._numAncestors
'''
This method increment by one the number of predecessor
'''
def incrementPredecessor(self):
self._numAncestors = self._numAncestors + 1
'''
This method establishes the number of predecessor
'''
def setNumberPredecessor(self, numPredecessor):
self._numAncestors = numPredecessor
| {
"repo_name": "lmarent/network_agents_ver2_python",
"path": "agents/foundation/Bid.py",
"copies": "1",
"size": "11557",
"license": "mit",
"hash": -7561416983152681000,
"line_mean": 32.6967930029,
"line_max": 136,
"alpha_frac": 0.633555421,
"autogenerated": false,
"ratio": 4.404344512195122,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.5537899933195122,
"avg_score": null,
"num_lines": null
} |
from fov import fov
import curses, random
DUNGEON = """
##### #########
#
# ###########
#
## ######### #
#
#
# ######## ######## #
# # #
# #
# # #
# ######### ### # #
# #
############### # #
#
# #
# #
############# ######
"""
HEIGHT, WIDTH = 22, 79
MAX_RADIUS = 80
COLOR = True
DEBUG = False
class Cell(object):
def __init__(self, char):
self.char = char
self.tag = 0
self.color = 0
class Grid(object):
def __init__(self, cells):
self.height, self.width = len(cells), len(cells[0])
self.cells = cells
def __contains__(self, yx):
y, x = yx
return 0 <= y < self.height and 0 <= x < self.width
def __getitem__(self, yx):
y, x = yx
if y < 0 or x < 0:
raise IndexError('negative index')
return self.cells[y][x]
def parse_grid(grid_str, width, height):
# Split the grid string into lines.
lines = [line.rstrip() for line in grid_str.splitlines()[1:]]
# Pad the top and bottom.
top = (height - len(lines)) // 2
bottom = (height - len(lines) + 1) // 2
lines = ([''] * top + lines + [''] * bottom)[:height]
# Pad the left and right sides.
max_len = max(len(line) for line in lines)
left = (width - max_len) // 2
lines = [' ' * left + line.ljust(width - left)[:width - left]
for line in lines]
# Create the grid.
cells = [[Cell(char) for char in line] for line in lines]
return Grid(cells)
class Engine(object):
def __init__(self, grid):
self.grid = grid
self.y = random.randrange(self.grid.height)
self.x = random.randrange(self.grid.width)
self.radius = 7
self.tag = 1
self.color = COLOR
self.debug = DEBUG
self.lights = 0
self.scans = 0
def move_cursor(self, dy, dx):
y, x = self.y + dy, self.x + dx
if (y, x) in self.grid:
self.y, self.x = y, x
def update_light(self):
self.tag += 1
self.lights = 0
self.scans = 0
def visit(y, x):
self.lights += 1
if (y, x) not in self.grid:
return True
cell = self.grid[y, x]
cell.tag = self.tag
cell.color = self.scans
return self.grid[y, x].char == '#'
def scan(*args):
self.scans += 1
fov(self.y, self.x, self.radius, visit, scan if self.debug else None)
def update_view(stdscr, engine):
# Update the grid view.
if engine.color:
colors = [curses.COLOR_RED, curses.COLOR_YELLOW, curses.COLOR_GREEN,
curses.COLOR_CYAN, curses.COLOR_BLUE, curses.COLOR_MAGENTA]
colors = [curses.COLOR_RED, curses.COLOR_YELLOW,
curses.COLOR_GREEN, curses.COLOR_BLUE]
for y, line in enumerate(engine.grid.cells):
for x, cell in enumerate(line):
char = (cell.char if cell.tag else ' ')
if char == ' ' and cell.tag == engine.tag:
if engine.debug and cell.color:
char = chr((ord('a') + (cell.color - 1) % 26))
else:
char = '.'
if engine.color:
if cell.tag == engine.tag:
if engine.debug:
color = colors[(cell.color - 1) % len(colors)]
else:
color = (curses.COLOR_YELLOW if char == '.'
else curses.COLOR_GREEN)
else:
color = (curses.COLOR_BLACK if engine.debug
else curses.COLOR_BLUE)
attr = curses.color_pair(color)
stdscr.addch(y, x, char, attr)
else:
stdscr.addch(y, x, char)
# Update the status lines.
blocked = (engine.grid[engine.y, engine.x].char == '#')
status_1 = ['[+-] Radius = %d' % engine.radius,
'[SPACE] %s' % ('Unblock' if blocked else 'Block')]
if COLOR:
status_1.append('[C]olor = %s' % 'NY'[engine.color])
status_1.append('[D]ebug = %s' % 'NY'[engine.debug])
status_1.append('[Q]uit')
status_2 = 'Lit %d cells' % engine.lights
if engine.debug:
status_2 += ' during %d scans' % engine.scans
stdscr.addstr(HEIGHT, 0, (' '.join(status_1)).ljust(WIDTH)[:WIDTH],
curses.A_STANDOUT)
stdscr.addstr(HEIGHT + 1, 0, (status_2 + '.').ljust(WIDTH)[:WIDTH])
# Update the cursor.
cell = engine.grid[engine.y, engine.x]
char = ('#' if cell.char == '#' else '@')
stdscr.addch(engine.y, engine.x, char)
stdscr.move(engine.y, engine.x)
def handle_command(key, engine):
# Move the cursor.
if key == ord('7'): engine.move_cursor(-1, -1)
if key in (ord('8'), curses.KEY_UP): engine.move_cursor(-1, 0)
if key == ord('9'): engine.move_cursor(-1, 1)
if key in (ord('4'), curses.KEY_LEFT): engine.move_cursor( 0, -1)
if key in (ord('6'), curses.KEY_RIGHT): engine.move_cursor( 0, 1)
if key == ord('1'): engine.move_cursor( 1, -1)
if key in (ord('2'), curses.KEY_DOWN): engine.move_cursor( 1, 0)
if key == ord('3'): engine.move_cursor( 1, 1)
# Change the light radius.
if key == ord('+'): engine.radius = min(MAX_RADIUS, engine.radius + 1)
if key == ord('-'): engine.radius = max(0, engine.radius - 1)
# Insert or delete a block at the cursor.
if key == ord(' '):
blocked = (engine.grid[engine.y, engine.x].char == '#')
engine.grid[engine.y, engine.x].char = (' ' if blocked else '#')
# Toggle options.
if key in (ord('c'), ord('C')) and COLOR: engine.color = not engine.color
if key in (ord('d'), ord('D')): engine.debug = not engine.debug
def main(stdscr):
if COLOR:
curses.use_default_colors()
for i in xrange(curses.COLOR_RED, curses.COLOR_WHITE + 1):
curses.init_pair(i, i, -1)
grid = parse_grid(DUNGEON, WIDTH, HEIGHT)
engine = Engine(grid)
while True:
engine.update_light()
update_view(stdscr, engine)
key = stdscr.getch()
if key in (ord('q'), ord('Q')):
break
handle_command(key, engine)
if __name__ == '__main__':
curses.wrapper(main)
| {
"repo_name": "elemel/python-fov",
"path": "src/fov_demo.py",
"copies": "1",
"size": "6872",
"license": "mit",
"hash": 7736111517944579000,
"line_mean": 32.0384615385,
"line_max": 77,
"alpha_frac": 0.4701688009,
"autogenerated": false,
"ratio": 3.63790365272631,
"config_test": false,
"has_no_keywords": false,
"few_assignments": false,
"quality_score": 0.46080724536263096,
"avg_score": null,
"num_lines": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.