rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
fields = ['study_type', 'study_design', 'phase']
fields = ['study_design', 'phase']
def clean(self): return super(forms.ModelForm,self).clean()
study_type = forms.ModelChoiceField(label=_('Study Type'), queryset=StudyType.objects.all())
def clean(self): return super(forms.ModelForm,self).clean()
return render_to_response('registry/trial_form_step_4.html',
return render_to_response('registry/trial_form_step_5.html',
def step_5(request, trial_pk): ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) if request.POST: form = RecruitmentForm(request.POST, instance=ct) if form.is_valid(): form.save() if request.POST.has_key('submit_next'): return HttpResponseRedirect("/rg/step_6/%s/" % trial_pk) # FIXME: use dynamic url return Ht...
return render_to_response('registry/trial_form_step_4.html',
return render_to_response('registry/trial_form_step_6.html',
def step_6(request, trial_pk): ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) if request.POST: form = StudyTypeForm(request.POST, instance=ct) if form.is_valid(): form.save() if request.POST.has_key('submit_next'): return HttpResponseRedirect("/rg/step_7/%s/" % trial_pk) # FIXME: use dynamic url return Http...
'host': request.get_host()},
'host': request.get_host(), 'scientific_title': scientific_title},
def trial_registered(request, trial_fossil_id, trial_version=None): ''' show details of a trial registered ''' try: fossil = Fossil.objects.get(pk=trial_fossil_id) except Fossil.DoesNotExist: try: qs = Fossil.objects.indexed(trial_id=trial_fossil_id) if trial_version: fossil = qs.get(revision_sequential=trial_version) ...
fossil.create_indexer(key='recruitment_status', value=instance.recruitment_status.label)
if value=instance.recruitment_status: fossil.create_indexer(key='recruitment_status', value=instance.recruitment_status.label)
def clinicaltrial_post_save(sender, instance, signal, **kwargs): # This signal calls validation method to validate the instance according to # rules made with mandatory fields but aren't obligatory on the model trial_validator.validate(instance) # Creates a fossil if the status is equal to 'published' if instance.stat...
profile = RegistrationProfile.objects.get(user=user)
def resend_activation_email(request): email = request.GET.get('email', '') users = User.objects.filter(email=email) if len(users) > 0: user = users[0] profile = RegistrationProfile.objects.get(user=user) else: user = None profile = None if user: if user.is_active: return HttpResponseRedirect(reverse('reviewapp.passw...
user = None profile = None if user: if user.is_active: return HttpResponseRedirect(reverse('reviewapp.password_reset')+'?email='+email) else:
return render_to_response('reviewapp/resend_activation_email.html', {'user_exist': False, 'email': email}, context_instance=RequestContext(request)) if user.is_active: return HttpResponseRedirect(reverse('reviewapp.password_reset')+'?email='+email) else: profiles = RegistrationProfile.objects.filter(user=user) if le...
def resend_activation_email(request): email = request.GET.get('email', '') users = User.objects.filter(email=email) if len(users) > 0: user = users[0] profile = RegistrationProfile.objects.get(user=user) else: user = None profile = None if user: if user.is_active: return HttpResponseRedirect(reverse('reviewapp.passw...
messages.warning(request, unicode(_('You cannot modify this trial because it has not the status "Draft".')))
messages.warning(request, unicode(_('You cannot modify this trial because it is being revised.')))
def _inner(request, trial_pk, *args, **kwargs): request.ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) request.can_change_trial = True
self.client.login(username='admin',passowrd='qazwsx')
self.client.login(username='admin',password='123456')
def test_submit(self): self.client.login(username='admin',passowrd='qazwsx') response = self.client.post('/rg/step_3/1/',{ 'hc_freetext':'test text to step 3', 'g-0-vocabulary':'DeCS', 'g-0-code':'C02', 'g-0-text':'Virus diseases', 's-0-vocabulary':'DeCS', 's-0-code':'C03.752.530', 's-0-text':'Malaria', }) self.failUnl...
'hc_freetext':'test text to step 3', 'g-0-vocabulary':'DeCS', 'g-0-code':'C02', 'g-0-text':'Virus diseases', 's-0-vocabulary':'DeCS', 's-0-code':'C03.752.530', 's-0-text':'Malaria',
'hc_freetext': 'test text to step 3', 'hc_freetext|pt-br': '', 'hc_freetext|es': '', 'g-TOTAL_FORMS': 1, 'g-INITIAL_FORMS': 0, 'g-0-vocabulary': 'DeCS', 'g-0-code': 'C02', 'g-0-text': 'Virus diseases', 'g-0-text|pt-br': 'Viroses', 'g-0-text|es': 'Virosis', 's-TOTAL_FORMS': 1, 's-INITIAL_FORMS': 0, 's-0-vocabulary': 'De...
def test_submit(self): self.client.login(username='admin',passowrd='qazwsx') response = self.client.post('/rg/step_3/1/',{ 'hc_freetext':'test text to step 3', 'g-0-vocabulary':'DeCS', 'g-0-code':'C02', 'g-0-text':'Virus diseases', 's-0-vocabulary':'DeCS', 's-0-code':'C03.752.530', 's-0-text':'Malaria', }) self.failUnl...
print self.client.content
def test_submit(self): self.client.login(username='admin',passowrd='qazwsx') response = self.client.post('/rg/step_3/1/',{ 'hc_freetext':'test text to step 3', 'g-0-vocabulary':'DeCS', 'g-0-code':'C02', 'g-0-text':'Virus diseases', 's-0-vocabulary':'DeCS', 's-0-code':'C03.752.530', 's-0-text':'Malaria', }) self.failUnl...
return render_to_response('repository/trial_form.html',
return render_to_response('repository/step_4.html',
def step_4(request, trial_pk): ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) DescriptorFormSet = modelformset_factory(Descriptor, form=InterventionDescriptorForm, extra=EXTRA_FORMS) queryset = Descriptor.objects.filter(trial=trial_pk, aspect=choices.TRIAL_ASPECT[1][0], level=choices.DESCRIPTOR_LEVEL[0][0]) ...
lang=self.display_language, model=FieldHelp, object_id=help_record.pk,
lang=get_language(), model=FieldHelp, object_id=help_record.pk,
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
app = get_app(appname) app_list[app] = None
if request.POST: for appname in request.POST.getlist('apps'): app = get_app(appname) app_list[app] = None appname = 'choices' else: app = get_app(appname) app_list[app] = None
def dump_data(request,appname): app_list = SortedDict() try: app = get_app(appname) app_list[app] = None except ImproperlyConfigured: if appname == 'all': for app in get_apps(): app_list[app] = None if(len(app_list) > 0): objects = [] for model in sort_dependencies(app_list.items()): if not model._meta.proxy and rout...
return render_to_response('diagnostic/dumpdata.html')
return render_to_response('diagnostic/dumpdata.html',context_instance=RequestContext(request))
def dump_data(request,appname): app_list = SortedDict() try: app = get_app(appname) app_list[app] = None except ImproperlyConfigured: if appname == 'all': for app in get_apps(): app_list[app] = None if(len(app_list) > 0): objects = [] for model in sort_dependencies(app_list.items()): if not model._meta.proxy and rout...
'id_number': sponsor.institution.name,
'institution': serialize_institution(sponsor.institution, as_string=False),
def serialize_trialsecondarysponsor(sponsor, as_string=True): """ Serializes a given trial number object to JSON """ json = { 'id_number': sponsor.institution.name, } if as_string: json = simplejson.dumps(json) return json
obj = super(RecruitmentForm, self).save(commit=False, *args, **kwargs)
obj = super(RecruitmentForm, self).save(commit=True, *args, **kwargs)
def save(self, commit=True, *args, **kwargs): obj = super(RecruitmentForm, self).save(commit=False, *args, **kwargs)
max_length=255, db_index=True, choices=TrialNumberIssuingAuthority.choices())
max_length=255, db_index=True,)
def secondary_outcomes(self): ''' return set of Secondary Outcomes related to this trial with ''' return self.outcome_set.filter(interest='secondary').select_related()
ordered_languages = get_ordered_languages(display_language, lower=True)
available_languages = None if self.var_available_languages: available_languages = self.var_available_languages.resolve(context) if not available_languages: available_languages = get_ordered_languages(display_language, lower=True)
def render(self, context): # It depends on 'request' template context processor display_language = context['request'].user.get_profile().preferred_language.lower()
if len(ordered_languages) <= 1:
if len(available_languages) <= 1:
def render(self, context): # It depends on 'request' template context processor display_language = context['request'].user.get_profile().preferred_language.lower()
default_second_language = ordered_languages[1]
default_second_language = available_languages[1]
def render(self, context): # It depends on 'request' template context processor display_language = context['request'].user.get_profile().preferred_language.lower()
};"""%(ordered_languages, default_second_language, display_language)
};"""%(simplejson.dumps(available_languages), default_second_language, display_language)
def render(self, context): # It depends on 'request' template context processor display_language = context['request'].user.get_profile().preferred_language.lower()
return JSConstantsNode()
parts = token.split_contents() return JSConstantsNode(len(parts) > 1 and parts[1] or None)
def polyglot_js_constants(parser, token): return JSConstantsNode()
self.date_registration = datetime.today()
self.date_registration = datetime.now()
def save(self): if self.id: self.updated = datetime.now() if self.status == choices.PUBLISHED_STATUS and not self.trial_id: # assigns the date of publication/registration self.date_registration = datetime.today() for i in range(TRIAL_ID_TRIES): self.trial_id = generate_trial_id(TRIAL_ID_PREFIX, TRIAL_ID_DIGITS) try: s...
'target_sample_size', 'phase', 'inclusion_criteria', 'gender',
'target_sample_size', 'inclusion_criteria', 'gender',
def as_table(self): "Returns this form rendered as HTML <tr>s -- excluding the <table></table>." normal_row = u''' <tr><th>%(label)s</th> <td>%(errors)s%(field)s</td> <td>%(help_text)s <div class="issue">%(issue)s</div> </td></tr> ''' return self._html_output(normal_row=normal_row, error_row=u'<tr><td colspan="3">%s</t...
if user_form.is_valid() and password_form.is_valid():
if user_form.is_valid():
def user_profile(request): if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) password_form = PasswordChangeForm(request.user,request.POST) if user_form.is_valid() and password_form.is_valid(): user_form.save() password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashb...
password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashboard'))
if password_form.changed_data: if password_form.is_valid(): password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashboard')) else: return HttpResponseRedirect(reverse('reviewapp.dashboard'))
def user_profile(request): if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) password_form = PasswordChangeForm(request.user,request.POST) if user_form.is_valid() and password_form.is_valid(): user_form.save() password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashb...
forms = [user_form, password_form]
def user_profile(request): if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) password_form = PasswordChangeForm(request.user,request.POST) if user_form.is_valid() and password_form.is_valid(): user_form.save() password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashb...
'forms': forms,
'user_form': user_form, 'password_form': password_form,
def user_profile(request): if request.method == 'POST': user_form = UserForm(request.POST,instance=request.user) password_form = PasswordChangeForm(request.user,request.POST) if user_form.is_valid() and password_form.is_valid(): user_form.save() password_form.save() return HttpResponseRedirect(reverse('reviewapp.dashb...
trial_forms.append(remarks)
if remarks: trial_forms.append(remarks)
def trial_view(request, trial_pk): ''' show details of a trial of a user logged ''' if request.user.is_staff: ct = get_object_or_404(ClinicalTrial, id=int(trial_pk)) else: ct = get_object_or_404(ClinicalTrial, id=int(trial_pk), submission__creator=request.user) translations = [t for t in ct.translations.all()] trial_fo...
'help_id': 'help%s' % help_record.pk,
'help_id': 'id_%s-help%s' % ((self.prefix or name),help_record.pk),
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
'help_id': 'help%s' % help_record.pk,
'help_id': 'id_%s-help%s' % (self.prefix,help_record.pk),
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
<table border="1"> <tr><th>id</th><td>%(site.pk)r</td></tr> <tr><th>domain</th><td>%(site.domain)r</td></tr> <tr><th>name</th><td>%(site.name)r</td></tr>
<table> <tr><th>id</th><td>%(site.pk)s</td></tr> <tr><th>domain</th><td>%(site.domain)s</td></tr> <tr><th>name</th><td>%(site.name)s</td></tr>
def sys_info(request): template = u''' <h1>Site.objects.get_current()</h1> <table border="1"> <tr><th>id</th><td>%(site.pk)r</td></tr> <tr><th>domain</th><td>%(site.domain)r</td></tr> <tr><th>name</th><td>%(site.name)r</td></tr> </table> <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>svn info</h1> <pre>%(svninf...
svnout, svnerr = Popen(['svn', 'info', settings.PROJECT_PATH], stdout=PIPE).communicate()
svnout, svnerr = Popen(['svn', 'info', '-r', 'HEAD', settings.PROJECT_PATH], stdout=PIPE).communicate() svnout = svnout.decode('utf-8') if svnout else u'' svnerr = svnerr.decode('utf-8') if svnerr else u''
def sys_info(request): template = u''' <h1>Site.objects.get_current()</h1> <table border="1"> <tr><th>id</th><td>%(site.pk)r</td></tr> <tr><th>domain</th><td>%(site.domain)r</td></tr> <tr><th>name</th><td>%(site.name)r</td></tr> </table> <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>svn info</h1> <pre>%(svninf...
'svninfo':svnout.decode('utf-8') or svnerr.decode('utf-8')})
'svninfo':svnout + svnerr})
def sys_info(request): template = u''' <h1>Site.objects.get_current()</h1> <table border="1"> <tr><th>id</th><td>%(site.pk)r</td></tr> <tr><th>domain</th><td>%(site.domain)r</td></tr> <tr><th>name</th><td>%(site.name)r</td></tr> </table> <h1>settings path</h1> <pre>%(settingspath)s</pre> <h1>svn info</h1> <pre>%(svninf...
self.base_fields[field_name] = MultilingualCharField(max_length=self.base_fields[field_name].max_length) else: self.base_fields[field_name] = MultilingualTextField()
if isinstance(self.base_fields[field_name].widget,forms.Textarea): self.base_fields[field_name] = MultilingualTextField( required=self.base_fields[field_name].required) else: self.base_fields[field_name] = MultilingualCharField( required=self.base_fields[field_name].required, max_length=self.base_fields[field_name].max...
def __init__(self, *args, **kwargs): # Gets multilingual fields from translation class self.multilingual_fields = get_multilingual_fields(self._meta.model) # FIXME, to remove #if self.__class__ == TrialIdentificationForm: # self.multilingual_fields = ('scientific_title','public_title',)
print "
def render(self, context): # It depends on 'request' template context processor display_language = context['request'].user.get_profile().preferred_language.lower()
choices=settings.TARGET_LANGUAGES)
choices=CHOICES_TARGET_LANGUAGES)
def get_translation_for_object(self, lang, obj=None, model=None, object_id=None, returns_default=False, create_if_not_exist=False): """Returns the translation object for a given object and language. Before call database, checks if there is a cached data for this."""
targets = set(value for value, label in settings.TARGET_LANGUAGES)
targets = set(value for value, label in CHOICES_TARGET_LANGUAGES)
def missing(content_object): ''' returns missing translation codes for a content object''' targets = set(value for value, label in settings.TARGET_LANGUAGES) done = set(t.language for t in content_object.translations.all()) return targets-done
help_text = help_text + u' ' + force_unicode(help_text)
help_text = u'' + force_unicode(help_text)
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row): "Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
if value == instance.recruitment_status:
if instance.recruitment_status:
def clinicaltrial_post_save(sender, instance, signal, **kwargs): # This signal calls validation method to validate the instance according to # rules made with mandatory fields but aren't obligatory on the model trial_validator.validate(instance) # Creates a fossil if the status is equal to 'published' if instance.stat...
label=_('Planned Date of First Enrollment'), required=False)
label=_('Planned Date of First Enrollment'))
def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.get_queryset(): return []
context[self.varname] = News.objects.all().order_by('-created',)[:self.num]
context[self.varname] = News.objects.filter(status__exact='published').order_by('-created',)[:self.num]
def render(self, context): context[self.varname] = News.objects.all().order_by('-created',)[:self.num] return ''
return self.indexed(recruitment_status='recruiting').published()
return self.indexed(recruitment_status='recruiting').filter(is_most_recent=True)
def recruiting(self): return self.indexed(recruitment_status='recruiting').published()
if isinstance(cond.function, DrtApplicationExpression) and (isinstance(cond.function.argument, DrtStateVariableExpression) or isinstance(cond.function.argument, DrtEventVariableExpression)):
if isinstance(cond.function, DrtApplicationExpression) and not isinstance(cond.function, DrtTimeApplicationExpression) and \ isinstance(cond.argument, DrtIndividualVariableExpression) and not isinstance(cond.argument, DrtTimeVariableExpression):
def collect_event_data(self, cond, event_data_map, event_strings_map): if isinstance(cond.function, DrtApplicationExpression) and (isinstance(cond.function.argument, DrtStateVariableExpression) or isinstance(cond.function.argument, DrtEventVariableExpression)): event_data_map.setdefault(cond.argument.variable,[]).appen...
elif cond.__class__ == DrtApplicationExpression and \ (isinstance(cond.argument, DrtEventVariableExpression) or isinstance(cond.argument, DrtStateVariableExpression)): assert cond.argument not in event_strings_map event_strings_map[cond.argument] = cond.function.variable.name
def collect_event_data(self, cond, event_data_map, event_strings_map): if isinstance(cond.function, DrtApplicationExpression) and (isinstance(cond.function.argument, DrtStateVariableExpression) or isinstance(cond.function.argument, DrtEventVariableExpression)): event_data_map.setdefault(cond.argument.variable,[]).appen...
for individual in event_data_map.keys():
for individual in event_data_map:
def _enrich_event_data_map(self, event_data_map, event_strings_map): # TODO: for individual in event_data_map.keys(): new_event_list = [] for event_tuple in event_data_map[individual]: new_event_list.append((event_tuple[0], event_tuple[1], event_strings_map.get(event_tuple[0], None))) event_data_map[individual] = new_e...
def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_ref, condition_index):
def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_cond, condition_index):
def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_ref, condition_index): self.presupp_drs = presupp_drs self.presupp_variable = presupp_variable self.presupp_funcname = presupp_funcname self.antecedent_ref = antecedent_ref self.condition_index = condition_index
self.antecedent_ref = antecedent_ref
self.antecedent_cond = antecedent_cond
def __init__(self, presupp_drs, presupp_variable, presupp_funcname, antecedent_ref, condition_index): self.presupp_drs = presupp_drs self.presupp_variable = presupp_variable self.presupp_funcname = presupp_funcname self.antecedent_ref = antecedent_ref self.condition_index = condition_index
and replace the presupposition condition referent in them with antecedent_ref"""
and replace the presupposition condition referent in them with antecedent referent"""
def __call__(self, drs): """Put all conditions from the presupposition DRS (if presupposition condition is a proper name: except the proper name itself) into the drs, and replace the presupposition condition referent in them with antecedent_ref""" #print "BINDING, drs", drs newdrs = self.presupp_drs.replace(self.presup...
newdrs = self.presupp_drs.replace(self.presupp_variable, self.antecedent_ref, True)
newdrs = self.presupp_drs.replace(self.presupp_variable, self.antecedent_cond.argument, True)
def __call__(self, drs): """Put all conditions from the presupposition DRS (if presupposition condition is a proper name: except the proper name itself) into the drs, and replace the presupposition condition referent in them with antecedent_ref""" #print "BINDING, drs", drs newdrs = self.presupp_drs.replace(self.presup...
if ref != self.antecedent_ref.variable])
if ref != self.antecedent_cond.argument.variable]) move_presupp_condition = True if self.antecedent_cond.function.variable.name != self.presupp_funcname else False
def __call__(self, drs): """Put all conditions from the presupposition DRS (if presupposition condition is a proper name: except the proper name itself) into the drs, and replace the presupposition condition referent in them with antecedent_ref""" #print "BINDING, drs", drs newdrs = self.presupp_drs.replace(self.presup...
if not is_unary_predicate(cond) or cond.function.variable.name != self.presupp_funcname]
if move_presupp_condition or not is_unary_predicate(cond) or cond.function.variable.name != self.presupp_funcname]
def __call__(self, drs): """Put all conditions from the presupposition DRS (if presupposition condition is a proper name: except the proper name itself) into the drs, and replace the presupposition condition referent in them with antecedent_ref""" #print "BINDING, drs", drs newdrs = self.presupp_drs.replace(self.presup...
def binding_reading(self, inner_drs, target_drs, antecedent_ref, trail, temporal_conditions=None, local_drs=None):
def binding_reading(self, inner_drs, target_drs, antecedent_cond, trail, temporal_conditions=None, local_drs=None):
def binding_reading(self, inner_drs, target_drs, antecedent_ref, trail, temporal_conditions=None, local_drs=None): condition_index = self._get_condition_index(target_drs, trail) binder = self.Bind(self, self.variable, self.function_name, antecedent_ref, condition_index) inner_replacer = self.InnerReplace(self.variable,...
binder = self.Bind(self, self.variable, self.function_name, antecedent_ref, condition_index) inner_replacer = self.InnerReplace(self.variable, antecedent_ref)
binder = self.Bind(self, self.variable, self.function_name, antecedent_cond, condition_index) inner_replacer = self.InnerReplace(self.variable, antecedent_cond.argument)
def binding_reading(self, inner_drs, target_drs, antecedent_ref, trail, temporal_conditions=None, local_drs=None): condition_index = self._get_condition_index(target_drs, trail) binder = self.Bind(self, self.variable, self.function_name, antecedent_ref, condition_index) inner_replacer = self.InnerReplace(self.variable,...
antecedent_ref = possible_bindings[0].argument return [self.binding_reading(inner_drs, outer_drs, antecedent_ref, trail)], True
return [self.binding_reading(inner_drs, outer_drs, possible_bindings[0], trail)], True
def _presupposition_readings(self, trail=[]): """A proper name always yields one reading: it is either global binding or global accommodation (if binding is not possible)""" outer_drs = self._find_outer_drs(trail) inner_drs = trail[-1] possible_bindings = self.find_bindings([outer_drs]) assert len(possible_bindings) <...
cond.argument, trail, temporal_conditions, local_drs))
cond, trail, temporal_conditions, local_drs))
def _presupposition_readings(self, trail=[]): #trail[0].draw() """ If a dog barks, every cat likes the dog. For binding, we need to look for antecedents in the whole trail (i.e. in all candidate drss, see filter_trail) But what about accommodation? If a dog barks, every cat likes the mouse. See Mathematical Methods in ...
class DrtStateApplicationExpression(DrtApplicationExpression):
class DrtEventualityApplicationExpression(DrtApplicationExpression):
def deepcopy(self, operations=[]): return self.__class__(self.function.deepcopy(operations), self.argument.deepcopy(operations))
utter_time_search = False
def _readings(self, trail=[]): """Reverses trail list""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): """Reverses refs list""" search_list = drs.refs if self.argument.variable in drs.refs: search_list = drs.refs[:drs.refs.index(self.argument.variable)] for ref in ReverseI...
if isinstance(refex, DrtTimeVariableExpression) and \
if not utter_time_search and isinstance(refex, DrtTimeVariableExpression) and \
def _readings(self, trail=[]): """Reverses trail list""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): """Reverses refs list""" search_list = drs.refs if self.argument.variable in drs.refs: search_list = drs.refs[:drs.refs.index(self.argument.variable)] for ref in ReverseI...
if any(isinstance(c, DrtApplicationExpression) and isinstance(c.function, DrtApplicationExpression) and \ c.function.argument == refex and (c.function.function.variable.name == DrtTokens.OVERLAP or \ c.function.function.variable.name == DrtTokens.INCLUDE) for c in drs.conds): utter_time_search = True else: """Return f...
def _readings(self, trail=[]): """Reverses trail list""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): """Reverses refs list""" search_list = drs.refs if self.argument.variable in drs.refs: search_list = drs.refs[:drs.refs.index(self.argument.variable)] for ref in ReverseI...
if self.argument.variable in search_list:
if drs is trail[-1]:
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
search_list = search_list[:search_list.index(self.argument.variable)]
search_list = drs.refs[:drs.refs.index(self.argument.variable)]
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
for ref in ReverseIterator(search_list): """search for the most recent reference""" refex = DrtVariableExpression(ref)
for ref in ReverseIterator(search_list): """search for the most recent reference""" refex = DrtVariableExpression(ref) if isinstance(refex, DrtEventVariableExpression) and \ not (refex == self.argument) and not self.function.variable.name == DrtTokens.PERF: if isinstance(self.argument,DrtEventVariableExpression): """...
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
if isinstance(refex, DrtEventVariableExpression) and \ not (refex == self.argument) and not self.function.variable.name == DrtTokens.PERF: if isinstance(self.argument,DrtEventVariableExpression): """In case given eventuality is an event, return earlier""" return [Reading([(trail[-1], DrtFindEventualityExpression.Repla...
elif not state_reference_point and \ isinstance(refex, DrtStateVariableExpression) and \ not (refex == self.argument): """In case no event is found, locate the most recent state""" state_reference_point = refex
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(trail[-1].conds.index(self), DrtStateApplicationExpression(DrtStateApplicationExpression(self.make_ConstantExpression(DrtTokens.ABUT),self.argument),state_reference_point)))])], False
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(index, self.combine(DrtTokens.ABUT,self.argument,state_reference_point)))])], False
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
termination_point = DrtEventVariableExpression(unique_variable(Variable("e"))) conds = [DrtEqualityExpression(termination_point,DrtApplicationExpression(self.make_ConstantExpression(DrtTokens.END),self.argument)), DrtStateApplicationExpression(DrtStateApplicationExpression(self.make_ConstantExpression(DrtTokens.ABUT),t...
termination_point = unique_variable(Variable("e")) conds = [DrtEqualityExpression(DrtEventVariableExpression(termination_point),DrtApplicationExpression(self.make_ConstantExpression(DrtTokens.END),self.argument)), self.combine(DrtTokens.ABUT,DrtEventVariableExpression(termination_point),state_reference_point)] return [...
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(trail[-1].conds.index(self), DrtStateApplicationExpression(DrtStateApplicationExpression(self.make_ConstantExpression(DrtTokens.OVERLAP),state_reference_point),self.argument)))])], False
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(index, self.combine(DrtTokens.OVERLAP,state_reference_point,self.argument)))])], False
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(trail[-1].conds.index(self), DrtStateApplicationExpression(DrtStateApplicationExpression(self.make_ConstantExpression(DrtTokens.INCLUDE),state_reference_point),self.argument)))])], False
return [Reading([(trail[-1], DrtFindEventualityExpression.Replacer(index, self.combine(DrtTokens.INCLUDE,state_reference_point,self.argument)))])], False
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
return [Reading([(trail[-1],PresuppositionDRS.Remover(trail[-1].conds.index(self)))])], False
return [Reading([(trail[-1],PresuppositionDRS.Remover(index))])], False
def _readings(self, trail=[]): state_reference_point = None """state reference point in case there are no previous events""" for drs in (ancestor for ancestor in ReverseIterator(trail) if isinstance(ancestor, DRS)): search_list = drs.refs if self.argument.variable in search_list: """Described eventuality in the objec...
def __init__(self, ref, conds):
def __init__(self, ref, index, conds):
def __init__(self, ref, conds): self.conds = conds self.ref = ref
def combine(self,cond, arg1, arg2): """Combines two arguments into a DrtEventualityApplicationExpression that has another DrtEventualityApplicationExpression as its functor""" return DrtEventualityApplicationExpression(DrtEventualityApplicationExpression(self.make_ConstantExpression(cond),arg1),arg2)
def make_ConstantExpression(self,name): return DrtConstantExpression(Variable(name))
elif isinstance(argument, DrtStateVariableExpression): return DrtStateApplicationExpression(function, argument)
elif isinstance(argument, DrtStateVariableExpression) or \ isinstance(argument, DrtEventVariableExpression): return DrtEventualityApplicationExpression(function, argument)
def make_ApplicationExpression(self, function, argument): """If statement added returning DrtTimeApplicationExpression""" """ Is self of the form "LOCPRO(t)"? """ if isinstance(function, DrtAbstractVariableExpression) and \ function.variable.name == DrtTokens.LOCATION_TIME and \ isinstance(argument, DrtTimeVariableExpr...
def test_4(): import util import nltkfixtemporal tester = util.Tester('file:../data/grammar.fcfg', DrtParser) expr = tester.parse('Mary does walk', utter=True)
def test_4(): from util import Tester tester = Tester('file:../data/grammar.fcfg', DrtParser) expr = tester.parse("Mary lived and Mary owns a car", utter=True).simplify()
def test_4(): import util import nltkfixtemporal tester = util.Tester('file:../data/grammar.fcfg', DrtParser) expr = tester.parse('Mary does walk', utter=True) print expr for reading in expr.readings(): print reading #reading.draw()
reading.draw()
def test_4(): import util import nltkfixtemporal tester = util.Tester('file:../data/grammar.fcfg', DrtParser) expr = tester.parse('Mary does walk', utter=True) print expr for reading in expr.readings(): print reading #reading.draw()
for ref in expression.get_refs(): if ref in discourse.get_refs(): newref = drt.DrtVariableExpression(drt.unique_variable(ref)) expression = expression.replace(ref,newref,True)
def interpret(expr_1, expr_2, bk=False): """Interprets a new expression with respect to some previous discourse and background knowledge. The function first generates relevant background knowledge and then performs inference check on readings generated by the readings() method. It returns a list of admissible interpret...
'married' : r'all x y.((married(x) & THEME(x,y)) -> exists v z.(own(v) & AGENT(v,y) & PATIENT(v,z) & (husband(z) | wife(z))))',
'married' : r'all x y.((married(x) & THEME(x,y)) -> exists v z.(own(v) & AGENT(v,y) & PATIENT(v,z) & husband(z)))',
def test_1(): #with ontology bk_0 = {'earlier' : r'all x y z.(earlier(x,y) & earlier(y,z) -> earlier(x,z)) & all x y.(earlier(x,y) -> -overlap(x,y))', 'include' : r'all x y z.((include(x,y) & include(z,y)) -> (overlap(x,z)))', 'die' : r'all x z y.((die(x) & AGENT(x,y) & die(z) & AGENT(z,y)) -> x = z)', 'dead' : r'all ...
interpretation.draw()
print interpretation
def test_1(): #with ontology bk_0 = {'earlier' : r'all x y z.(earlier(x,y) & earlier(y,z) -> earlier(x,z)) & all x y.(earlier(x,y) -> -overlap(x,y))', 'include' : r'all x y z.((include(x,y) & include(z,y)) -> (overlap(x,z)))', 'die' : r'all x z y.((die(x) & AGENT(x,y) & die(z) & AGENT(z,y)) -> x = z)', 'dead' : r'all ...
utter = args.get("utter", False)
utter = args.get("utter", True)
def parse(self, text, **args): sentences = text.split('.') utter = args.get("utter", False) show_interim = args.get("show_interim", False) drs = (utter and self.logic_parser.parse('DRS([n],[])')) or [] for sentence in sentences: sentence = sentence.lstrip() if sentence: new_words = [] split = sentence.split() for word...
expected_drs = self.logic_parser.parse(expected)
expected_drs = local_DrtParser().parse(expected).readings()[0]
def test(self, cases, **args): for number, sentence, expected, error in cases: if expected is not None: expected_drs = self.logic_parser.parse(expected) else: expected_drs = None
drs_list.append(self.parse(sentence, args)) drs_list.append(drs_list[-1].resolve()) drs_list.append(drs_list[-1].resolve())
drs_list.append(self.parse(sentence, utter=True)) readings.append(drs_list[-1].readings()[0])
def test(self, cases, **args): for number, sentence, expected, error in cases: if expected is not None: expected_drs = self.logic_parser.parse(expected) else: expected_drs = None
if drs_list[-1] == expected_drs: print("%s. %s %s" % (number, sentence, drs_list[-1]))
if readings[-1] == expected_drs: print("%s. %s %s" % (number, sentence, readings[-1]))
def test(self, cases, **args): for number, sentence, expected, error in cases: if expected is not None: expected_drs = self.logic_parser.parse(expected) else: expected_drs = None
print("%s. !comparison failed %s != %s" % (number, drs_list[-1], expected_drs))
print("%s. !comparison failed %s != %s" % (number, readings[-1], expected_drs))
def test(self, cases, **args): for number, sentence, expected, error in cases: if expected is not None: expected_drs = self.logic_parser.parse(expected) else: expected_drs = None
if drs_list[-1] == expected_drs: print("%s. *%s %s (%s)" % (number, sentence, drs_list[-1], e))
if readings[-1] == expected_drs: print("%s. *%s %s (%s)" % (number, sentence, readings[-1], e))
def test(self, cases, **args): for number, sentence, expected, error in cases: if expected is not None: expected_drs = self.logic_parser.parse(expected) else: expected_drs = None
PresuppositionDRS._one_cond(super(PronounDRS, self)._get_presupp_data(check))
super(PronounDRS, self)._get_presupp_data(check) self._one_cond()
def check(cond): return cond.function.variable.name in PronounDRS.PRONOUNS
PresuppositionDRS._one_cond(super(ProperNameDRS, self)._get_presupp_data(check))
super(ProperNameDRS, self)._get_presupp_data(check) self._one_cond()
def check(cond): return cond.is_propername()
elif not bk and not isinstance(bk, dict):
elif bk and not isinstance(bk, dict):
def interpret(self, expr_1, expr_2, bk=False,verbose=False): """Interprets a new expression with respect to some previous discourse and background knowledge. The function first generates relevant background knowledge and then performs inference check on readings generated by the readings() method. It returns a list of ...
lp = LogicParser().parse parser_obj = local_DrtParser() try: for formula in get_bk(new_discourse, bk): if background_knowledge: try: background_knowledge = AndExpression(background_knowledge, parser_obj.parse(formula).fol()) except ParseException:
if bk: lp = LogicParser().parse parser_obj = local_DrtParser() try: for formula in get_bk(new_discourse, bk): if background_knowledge:
def interpret(self, expr_1, expr_2, bk=False,verbose=False): """Interprets a new expression with respect to some previous discourse and background knowledge. The function first generates relevant background knowledge and then performs inference check on readings generated by the readings() method. It returns a list of ...
background_knowledge = AndExpression(background_knowledge, lp(formula)) except Exception: print Exception else: try: background_knowledge = parser_obj.parse(formula).fol() except ParseException:
background_knowledge = AndExpression(background_knowledge, parser_obj.parse(formula).fol()) except ParseException: try: background_knowledge = AndExpression(background_knowledge, lp(formula)) except Exception: print Exception else:
def interpret(self, expr_1, expr_2, bk=False,verbose=False): """Interprets a new expression with respect to some previous discourse and background knowledge. The function first generates relevant background knowledge and then performs inference check on readings generated by the readings() method. It returns a list of ...
background_knowledge = lp(formula) except Exception: print Exception if verbose: print "Generated background knowledge:\n%s" % background_knowledge interpretations = [] index = 1 for reading in new_discourse.readings(): print "\nGenerated reading (%s):" % index index = index + 1 interpretation = None try: interpretat...
background_knowledge = parser_obj.parse(formula).fol() except ParseException: try: background_knowledge = lp(formula) except Exception: print Exception if verbose: print "Generated background knowledge:\n%s" % background_knowledge except AssertionError as e: print e interpretations = [] index = 1 for reading in ne...
def interpret(self, expr_1, expr_2, bk=False,verbose=False): """Interprets a new expression with respect to some previous discourse and background knowledge. The function first generates relevant background knowledge and then performs inference check on readings generated by the readings() method. It returns a list of ...
@staticmethod def _one_cond(presupp_data):
def _one_cond(self):
def _get_presupp_data(self, check=None): """ Return the referent, features and function name of the presupposition condition. Make sure it passes the check. @param check: a boolean function; a check that the presupposition condition must pass.""" """In DRSs representing sentences like 'John, who owns a dog, feeds it', ...
presupp_data = list(presupp_data) if not isinstance (presupp_data[2], str): assert isinstance(presupp_data[2], set) and len(presupp_data[2]) == 1 presupp_data[2] = presupp_data[2].pop() return tuple(presupp_data)
if not isinstance (self.funcname, str): assert isinstance(self.funcname, set) and len(self.funcname) == 1 self.funcname = self.funcname.pop()
def _one_cond(presupp_data): """Some subclasses of PresuppositionalDrs (e.g. PronounDrs, ProperNameDrs) will expect only one presuppositional condition, while for other subclasses it may be the case that we can't find the head of the presuppositional NP, e.g. sad(x) and boy(x) will look the same to us if no features ar...
self.variable self.features self.funcname
def accommodation(drs): condition_index = self._get_condition_index(drs, trail) return Reading([(drs, NonPronPresuppositionDRS.Accommodation(self, condition_index))])
return self.is_unary_predicate(cond) and self.has_same_features(cond) and cond.argument.__class__ is DrtIndividualVariableExpression
return is_unary_predicate(cond) and self.has_same_features(cond) and cond.argument.__class__ is DrtIndividualVariableExpression
def is_possible_binding(self, cond): return self.is_unary_predicate(cond) and self.has_same_features(cond) and cond.argument.__class__ is DrtIndividualVariableExpression
def is_unary_predicate(self, cond): return isinstance(cond, DrtApplicationExpression) and isinstance(cond.function, DrtAbstractVariableExpression)
def collect_event_data(self, cond): if isinstance(cond, DrtApplicationExpression) and\ isinstance(cond.function, DrtApplicationExpression) and\ isinstance(cond.function.argument, DrtIndividualVariableExpression): return (cond.function.argument, cond.function.function)
presupp_cond_list = [cond for cond in self.conds if self.is_unary_predicate(cond) and cond.argument.variable == self.refs[0] and self.is_presupposition_cond(cond)]
presupp_cond_list = [cond for cond in self.conds if is_unary_predicate(cond) and cond.argument.variable == self.refs[0] and self.is_presupposition_cond(cond)]
def _init_presupp_data(self): """ Return the referent, features and function name of the presupposition condition. Make sure it passes the check. @param check: a boolean function; a check that the presupposition condition must pass.""" """In DRSs representing sentences like 'John, who owns a dog, feeds it', there will ...
if not self.is_unary_predicate(cond) or cond.function.variable.name != self.presupp_funcname]
if not is_unary_predicate(cond) or cond.function.variable.name != self.presupp_funcname]
def __call__(self, drs): """Put all conditions from the presupposition DRS (if presupposition condition is a proper name: except the proper name itself) into the drs, and replace the presupposition condition referent in them with antecedent_ref""" #print "BINDING, drs", drs newdrs = self.presupp_drs.replace(self.presup...
possible_bindings = self.find_bindings(self, [outer_drs])
possible_bindings = self.find_bindings([outer_drs])
def _presupposition_readings(self, trail=[]): """A proper name always yields one reading: it is either global binding or global accommodation (if binding is not possible)""" outer_drs = self._find_outer_drs(trail) inner_drs = trail[-1] possible_bindings = self.find_bindings(self, [outer_drs]) assert len(possible_bindin...
antecedent_ref = possible_bindings[0].argument.variable
antecedent_ref = possible_bindings[0].argument
def _presupposition_readings(self, trail=[]): """A proper name always yields one reading: it is either global binding or global accommodation (if binding is not possible)""" outer_drs = self._find_outer_drs(trail) inner_drs = trail[-1] possible_bindings = self.find_bindings(self, [outer_drs]) assert len(possible_bindin...