def update_action(self, action=None, context=None): result = {} action_uid = self.params('action_uid') try: if action_uid: action = get_obj(int(action_uid)) else: action = self._get_start_action() except Exception: return {} context_uid = self.params('context_uid') try: if context_uid: context = get_obj(int(context_uid)) except Exception: pass dace_ui_api = get_current_registry().getUtility( IDaceUIAPI, 'dace_ui_api') body, resources = dace_ui_api.get_action_body( context, self.request, action, include_resources=True) result = {'body': body} result.update(get_components_data( **get_all_updated_data( action, self.request, context, self, resources=resources))) return result
def update_action(self, action=None, context=None): result = {} action_uid = self.params('action_uid') try: if action_uid: action = get_obj(int(action_uid)) else: action = self._get_start_action() except Exception: return {} context_uid = self.params('context_uid') try: if context_uid: context = get_obj(int(context_uid)) except Exception: pass dace_ui_api = get_current_registry().getUtility( IDaceUIAPI, 'dace_ui_api') body, resources = dace_ui_api.get_action_body(context, self.request, action, include_resources=True) result = {'body': body} result.update( get_components_data(**get_all_updated_data( action, self.request, context, self, resources=resources))) return result
def update(self): source_oid = self.params('source') targets_oid = self.params('targets') if targets_oid and source_oid: try: if not isinstance(targets_oid, (list, tuple)): targets_oid = [targets_oid] targets = [get_obj(int(t)) for t in targets_oid] source = get_obj(int(source_oid)) if targets and source: result = self.execute( {'source': source, 'targets': targets}) if result and result[0].get('error', False): view_error = ViewError() view_error.principalmessage = _("An error has occurred.") return self.failure(view_error) return HTTPFound( self.request.resource_url(source, '@@index')) except Exception as error: log.warning(error) return HTTPFound(self.request.resource_url(self.context, ''))
def evaluators(self, evaluation_type=None): if evaluation_type: return [get_obj(key) for value, key in self.allocated_tokens.byValue(evaluation_type)] return [get_obj(key) for key in self.allocated_tokens.keys()]
def get_explanation_data(cls, args): """Return the value of the intention""" result = {} for (k, value) in args.items(): if k in cls.parameters: try: if isinstance(value, list): listvalue = [] for val in value: obj = get_obj(int(val), True) if obj is None : raise Exception() listvalue.append(obj) result[k] = listvalue else: obj = get_obj(int(value), True) if obj is None : raise Exception() result[k] = obj except Exception: result[k] = value return result
def _get_adapted_content(self, user, text): """Return the appropriate text to the user""" soup = BeautifulSoup(text) corrections = soup.find_all("span", id='correction') if user is self.author: for correction in corrections: self._adapt_correction(correction, True) else: for correction in corrections: correction_data = self.corrections[correction["data-item"]] voters_favour = any((get_obj(v) is user \ for v in correction_data['favour'])) if voters_favour: self._adapt_correction(correction, True) continue voters_against = any((get_obj(v) is user \ for v in correction_data['against'])) if voters_against: self._adapt_correction(correction, False) registry = get_current_registry() text_analyzer = registry.getUtility(ITextAnalyzer,'text_analyzer') return text_analyzer.soup_to_text(soup)
def update(self): self.execute(None) user = self.context root = getSite() notes = [{ 'date': to_localized_time(date, self.request, translate=True), 'user': get_obj(value[0]), 'content': get_obj(value[1]), 'note': value[2], } for date, value in user._notes.items()] len_result = len(notes) index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) values = { 'notes': notes, 'member': self.context, 'time_constant': getattr(root, 'time_constant', 6), 'length': len_result, 'score': getattr(user, 'confidence_index', 0) } result = {} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): source_oid = self.params('source') targets_oid = self.params('targets') if targets_oid and source_oid: try: if not isinstance(targets_oid, (list, tuple)): targets_oid = [targets_oid] targets = [get_obj(int(t)) for t in targets_oid] source = get_obj(int(source_oid)) if targets and source: result = self.execute({ 'source': source, 'targets': targets }) if result: values = result[0] values['context'] = source body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result = {} result['coordinates'] = {self.coordinates: [item]} return result except Exception as error: log.warning(error) view_error = ViewError() view_error.principalmessage = _("An error has occurred.") return self.failure(view_error)
def update(self): source_oid = self.params('source') targets_oid = self.params('targets') if targets_oid and source_oid: try: if not isinstance(targets_oid, (list, tuple)): targets_oid = [targets_oid] targets = [get_obj(int(t)) for t in targets_oid] source = get_obj(int(source_oid)) if targets and source: result = self.execute({ 'source': source, 'targets': targets }) if result and result[0].get('error', False): view_error = ViewError() view_error.principalmessage = _( "An error has occurred.") return self.failure(view_error) return HTTPFound( self.request.resource_url(source, '@@index')) except Exception as error: log.warning(error) return HTTPFound(self.request.resource_url(self.context, ''))
def _get_adapted_content(self, user, text): """Return the appropriate text to the user""" user_ = self.proposal.working_group.get_member(user) user_ = user_ or user soup = BeautifulSoup(text) corrections = soup.find_all("span", id='correction') # if user is self.author: # for correction in corrections: # self._adapt_correction(correction, True) # else: for correction in corrections: correction_data = self.corrections[correction["data-item"]] voters_favour = any((get_obj(v) is user_ for v in correction_data['favour'])) if voters_favour: self._adapt_correction(correction, True) continue voters_against = any((get_obj(v) is user_ for v in correction_data['against'])) if voters_against: self._adapt_correction(correction, False) return html_diff_wrapper.soup_to_text(soup)
def get_instance(cls, context, request, **kw): action_uid = request.params.get('action_uid', None) source_action = None if action_uid: source_action = get_obj(int(action_uid)) if source_action and \ source_action._class_ is cls and \ source_action.validate(context, request): return source_action instances = getBusinessAction(context, request, cls.node_definition.process.id, cls.node_definition.__name__, action_type=cls, validate=kw.get('validate', True)) if instances is None: return None isstart = request.params.get('isstart', False) if isstart: for inst in instances: if inst.isstart: return inst return instances[0]
def evolve_examined_tokens(root, registry): from novaideo.views.filter import find_entities from novaideo.content.interface import Iidea, IProposal from BTrees.OOBTree import OOBTree request = get_current_request() request.root = root # needed when executing the step via sd_evolve script contents = find_entities( interfaces=[Iidea, IProposal], metadata_filter={'states': ['examined']} ) evaluations = { 1: 'support', -1: 'withdraw', 0: 'oppose' } for index, node in enumerate(contents): if hasattr(node, '_support_history'): history = sorted(node._support_history, key=lambda e: e[1]) node.allocated_tokens = OOBTree() node.len_allocated_tokens = PersistentDict({}) for value in history: user, date, evaluation = value user = get_obj(user) evaluation = evaluations[evaluation] if evaluation == 'withdraw': node.remove_token(user) else: node.add_token(user, evaluation) node.reindex() log.info('Tokens evolved.')
def get_artist_form(self): artist_id = self.params('artist_id') if artist_id: try: artist = get_obj(int(artist_id), None) except Exception: artist = None artist_data = None if artist: artist_data = artist.get_data(ArtistFormView.schema.get('artist')) artist_data['id'] = artist_id artist_data['origin_oid'] = int(artist_id) if artist_data['picture']: picture = artist_data['picture'] artist_data['picture'] = picture.get_data(None) else: artist_data = {'id': artist_id, 'title': artist_id, 'origin_oid': 0} form = ArtistFormView(self.context, self.request) form.artist_data = artist_data result = form.update() body = result['coordinates'][form.coordinates][0]['body'] return {'body': body}
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() artist = appstruct['_object_data'] root.addtoproperty('artists', artist) artist.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', artist), )) artist.setproperty('author', user) artist.add_contributors(context.contributors) artist.add_contributors([user]) artist.setproperty('original', context) artist.set_metadata(appstruct) artist.hash_picture_fp() artist.hash_artist_data() source = request.GET.get('source', '') if source: source_artist = get_obj(int(source)) if source_artist: replaced = source_artist.replace_by(artist) if replaced: request.registry.notify(ObjectReplaced( old_object=source_artist, new_object=artist )) root.delfromproperty('artists', source_artist) artist.reindex() request.registry.notify(ActivityExecuted(self, [artist], user)) return {'newcontext': artist}
def calculate_votes(self, votes): """Return the result of ballot""" result = {} for subject in self.report.subjects: try: subject_id = get_oid(subject) except Exception: subject_id = subject result[subject_id] = 0 for vote in votes: subject = get_obj(vote.value) if subject is None: subject = vote.value try: subject_id = get_oid(vote.value) except Exception: subject_id = vote.value if subject in self.report.subjects: result[subject_id] += 1 return result
def update(self): comment_id = self.params('comment_id') user = get_current() comment = None try: obj = get_obj(int(comment_id)) if comment_id else None if isinstance(obj, Comment) and can_access(user, obj): comment = obj except Exception as error: log.warning(error) comment_body = '' if comment: comment_body = render_listing_obj( self.request, comment, user) values = { 'comment_body': comment_body } result = {} body = self.content( args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} result = merge_dicts(self.requirements_copy, result) return result
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() artist = appstruct['_object_data'] root.addtoproperty('artists', artist) artist.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', artist), )) artist.setproperty('author', user) artist.add_contributors(context.contributors) artist.add_contributors([user]) artist.setproperty('original', context) artist.set_metadata(appstruct) artist.hash_picture_fp() artist.hash_artist_data() source = request.GET.get('source', '') if source: source_artist = get_obj(int(source)) if source_artist: replaced = source_artist.replace_by(artist) if replaced: request.registry.notify( ObjectReplaced(old_object=source_artist, new_object=artist)) root.delfromproperty('artists', source_artist) artist.reindex() request.registry.notify(ActivityExecuted(self, [artist], user)) return {'newcontext': artist}
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() venue = appstruct['_object_data'] root.addtoproperty('venues', venue) venue.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', venue), )) venue.setproperty('author', user) venue.add_contributors(context.contributors) venue.add_contributors([user]) venue.setproperty('original', context) venue.set_metadata(appstruct) venue.hash_venue_data() source = request.GET.get('source', '') if source: source_venue = get_obj(int(source)) if source_venue: replaced = source_venue.replace_by(venue) if replaced: request.registry.notify(ObjectReplaced( old_object=source_venue, new_object=venue )) root.delfromproperty('venues', source_venue) venue.reindex() request.registry.notify(ActivityExecuted(self, [venue], user)) return {'newcontext': venue}
def venue_address_coordinates_synchronizing(self): venue_oid = self.params('context_id') if venue_oid: venue = get_obj(int(venue_oid)) self._coordinates_synchronizing(venue) return {}
def deserialize(self, field, pstruct): form = field.get_root() form.stores = getattr(form, 'stores', []) form.stores.append(self.tmpstore) data = super(FileWidget, self).deserialize(field, pstruct) file_oid = pstruct.get(OBJECT_OID, 'None') file_oid = file_oid if file_oid != 'None' else None if pstruct.get('_object_removed', 'false') == 'true': return null if data is null and not file_oid: return null elif data is null: data = {} if file_oid: try: data[OBJECT_OID] = file_oid if 'fp' not in data: file_obj = get_obj(int(file_oid)) data['fp'] = file_obj.fp except Exception: pass try: if 'fp' in data: data['fp'].seek(0) except Exception: pass if not data: return null return data
def get_description(self, field, cstruct): description_template = 'novaideo:views/amendment_management/templates/description_amendments.pt' oid = cstruct[OBJECT_OID] current_user = get_current() try: subject = get_obj(int(oid)) values = {'amendment': subject, 'is_proposal': False, 'current_user': current_user, 'field': field} if isinstance(subject, Proposal): amendments = [a.text for a in self.subjects if not isinstance(a, Proposal)] values['text'] = get_trimed_proposal_text( subject.text, amendments) values['is_proposal'] = True else: values['text'] = get_trimed_amendment_text( getattr(subject, 'text_diff', '')) body = self.content(args=values, template=description_template)['body'] return body except Exception as e: log.exception(e) return '<dic class="has-error"></div>'
def get_title(control): try: obj = get_obj(int(control)) except: return control return obj.title if obj else control
def get_electeds(self, result): """Return the elected subject""" len_voters = len(self.report.voters) if len_voters == 0: return None judgments = sorted(list(self.judgments.keys()), key=lambda o: self.judgments[o]) object_results = dict([(oid, 0) for oid in result.keys()]) for oid in result.keys(): object_result = 0 for judgment in judgments: object_result += float(result[oid][judgment]) / \ float(len_voters) * 100 if object_result >= 50: object_results[oid] = self.judgments[judgment] break sorted_results = sorted(list(object_results.keys()), key=lambda o: object_results[o], reverse=True) if sorted_results: try: elected = get_obj(sorted_results[0]) return [elected] except Exception: return None return None
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() venue = appstruct['_object_data'] root.addtoproperty('venues', venue) venue.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', venue), )) venue.setproperty('author', user) venue.add_contributors(context.contributors) venue.add_contributors([user]) venue.setproperty('original', context) venue.set_metadata(appstruct) venue.hash_venue_data() source = request.GET.get('source', '') if source: source_venue = get_obj(int(source)) if source_venue: replaced = source_venue.replace_by(venue) if replaced: request.registry.notify( ObjectReplaced(old_object=source_venue, new_object=venue)) root.delfromproperty('venues', source_venue) venue.reindex() request.registry.notify(ActivityExecuted(self, [venue], user)) return {'newcontext': venue}
def address_coordinates_synchronizing(self): schedule_oid = self.params('context_id') if schedule_oid: schedule = get_obj(int(schedule_oid)) self._coordinates_synchronizing(schedule.venue) return {}
def get_organizations_by_evaluations( filter_, user, root, date_from, date_to): novaideo_catalog = find_catalog('novaideo') date_index = novaideo_catalog['published_at'] query = None if date_from: date_from = datetime.datetime.combine( date_from, datetime.datetime.min.time()) date_from = date_from.replace(tzinfo=pytz.UTC) query = date_index.gt(date_from) if date_to: date_to = datetime.datetime.combine( date_to, datetime.datetime.min.time()) date_to = date_to.replace(tzinfo=pytz.UTC) if query is None: query = date_index.lt(date_to) else: query = query & date_index.lt(date_to) objects = find_entities( user=user, add_query=query, **filter_) index = novaideo_catalog['organizations'] support = novaideo_catalog['support'] oppose = novaideo_catalog['oppose'] intersection = index.family.IF.intersection object_ids = getattr(objects, 'ids', objects) if isinstance(object_ids, (list, types.GeneratorType)): object_ids = index.family.IF.Set(object_ids) # calculate sum of support / sum of opposition result = {} for struct_id, oids in index._fwd_index.items(): struct = get_obj(struct_id) if struct: structoids = intersection(oids, object_ids) support_nb = 0 for nb, supportoids in support._fwd_index.items(): if nb > 0: support_nb += nb * len(intersection(supportoids, structoids)) oppose_nb = 0 for nb, opposeoids in oppose._fwd_index.items(): if nb > 0: oppose_nb += nb * len(intersection(opposeoids, structoids)) result[struct_id] = { 'support': support_nb, 'opposition': oppose_nb } return result, object_ids.__len__()
def title_getter(oid): author = None try: author = get_obj(int(oid)) except Exception: return oid title = getattr(author, 'title', author.__name__) return title
def title_getter(id): try: obj = get_obj(int(id), None) if obj: return obj.title else: return id except Exception as e: log.warning(e) return id
def update(self): img_id = self.params('img_id') if not img_id: return HTTPFound(self.request.resource_url(self.request.root, '')) img = get_obj(int(img_id)) if img: url = img.url return HTTPFound(url) return HTTPFound(self.request.resource_url(self.request.root, ''))
def title_getter(oid): author = None try: author = get_obj(int(oid)) except Exception: return oid title = getattr(author, 'title', author.__name__) if authors_data: title += ' ('+str(authors_data.get(oid, 0))+')' return title
def deserialize(self, field, pstruct): if pstruct in (null, self.null_value): return null if not getattr(self, 'multiple', False) and \ isinstance(pstruct, (list, tuple)): pstruct = pstruct[0] try: return get_obj(int(pstruct)) except ValueError: return pstruct
def title_getter(oid): challenge = None try: challenge = get_obj(int(oid)) except Exception: return oid title = getattr(challenge, 'title', challenge.__name__) if challenges_data: title += ' ('+str(challenges_data.get(oid, 0))+')' return title
def default_data(self): source = self.params('source') context = self.context if source: context = get_obj(int(source)) result = context.get_data( omit(self.schema, ['_csrf_token_', '__objectoid__'])) if result['picture']: picture = result['picture'] result['picture'] = picture.get_data(None) return result
def title_getter(obj): if not isinstance(obj, str): return getattr(obj, 'title', obj) else: try: obj = get_obj(int(obj), None) if obj: return obj.title else: return obj except Exception as e: log.warning(e) return obj
def update(self): oid = self.params('oid') if oid: try: newsletter = get_obj(int(oid)) user = self.params('user') result = self.execute({'newsletter': newsletter, 'user': user}) return result[0] except Exception as error: log.warning(error) root = getSite() return HTTPFound(self.request.resource_url(root, ""))
def default_data(self): source = self.params('source') context = self.context if source: context = get_obj(int(source)) result = context.get_data(omit(self.schema, ['_csrf_token_', '__objectoid__'])) if result['picture']: picture = result['picture'] result['picture'] = picture.get_data(None) return result
def find_entities_by_artist(self): user = get_current() artist_id = self.params('artist') if not artist_id: objects = [] else: artist = get_obj(int(artist_id), None) if not artist: objects = [] else: objects = find_entities( user=user, metadata_filter={'states': ['published']}, contribution_filter={'artists_ids': [artist]}, sort_on='release_date', reverse=True, include_site=True) batch = Batch(objects, self.request, url=self.request.url, default_size=core.BATCH_DEFAULT_SIZE) batch.target = "#results" len_result = batch.seqlen result_body = [] for obj in batch: object_values = {'object': obj, 'current_user': user, 'state': None} body = self.content(args=object_values, template=obj.templates['default'])['body'] result_body.append(body) values = { 'bodies': result_body, 'batch': batch, } body = self.content(args=values, template=self.template)['body'] len_result = len(objects) index = str(len_result) if len_result > 1: index = '*' title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) values = { 'body': body, 'title': title } body = self.content(args=values, template=self.wrapper_template)['body'] return {'body': body}
def update_action(self, action=None, context=None): result = {} action_uid = self.params('action_uid') try: if action_uid is not None: action = get_obj(int(action_uid )) else: action = self._get_start_action() except Exception: return {}#message erreur context_uid = self.params('context_uid') try: if context_uid is not None: context = get_obj(int(context_uid)) except Exception: pass dace_ui_api = get_current_registry().getUtility(IDaceUIAPI, 'dace_ui_api') result['body'] = dace_ui_api.get_action_body(context, self.request, action) return result
def init_graph(self, calculated=[]): result = self.get_nodes_data() self.graph = PersistentDict(result[0]) oid = self.get_node_id() newcalculated = list(calculated) newcalculated.append(oid) for node in self.graph: if node not in newcalculated: node_obj = get_obj(self.graph[node]['oid']) if node_obj: graph, newcalculated = node_obj.init_graph( newcalculated) return self.graph, newcalculated