def test_list_permission(self): """Testing permission listing.""" person_id = self.db_tools.create_person(self.person_ds().next()) account_id = self.db_tools.create_account(self.account_ds().next()) ou_id = self.db_tools.create_ou({ 'name': 'ephorte-test', 'acronym': 'ET', 'short_name': 'ePhorte-test', 'display_name': 'Test OU for ePhorte' }) self.assertFalse(self._ep.list_permission(), 'Listed permission, should be none') self._ep.add_permission(person_id, self._co.ephorte_perm_ar, ou_id, account_id) self._ep.add_permission(person_id, self._co.ephorte_perm_ua, ou_id, account_id) self.assertEqual(self._ep.list_permission(person_id), [(person_id, self._co.ephorte_perm_ar, ou_id, account_id, DateTime.today(), None), (person_id, self._co.ephorte_perm_ua, ou_id, account_id, DateTime.today(), None)], 'Failed listing added roles for person') self.assertEqual(len(self._ep.list_permission()), 2, 'Number of permissions listed not equal')
def test_list_permission(self): """Testing permission listing.""" person_id = self.db_tools.create_person(self.person_ds().next()) account_id = self.db_tools.create_account(self.account_ds().next()) ou_id = self.db_tools.create_ou( {'name': 'ephorte-test', 'acronym': 'ET', 'short_name': 'ePhorte-test', 'display_name': 'Test OU for ePhorte'}) self.assertFalse(self._ep.list_permission(), 'Listed permission, should be none') self._ep.add_permission( person_id, self._co.ephorte_perm_ar, ou_id, account_id) self._ep.add_permission( person_id, self._co.ephorte_perm_ua, ou_id, account_id) self.assertEqual( self._ep.list_permission(person_id), [(person_id, self._co.ephorte_perm_ar, ou_id, account_id, DateTime.today(), None), (person_id, self._co.ephorte_perm_ua, ou_id, account_id, DateTime.today(), None)], 'Failed listing added roles for person') self.assertEqual(len(self._ep.list_permission()), 2, 'Number of permissions listed not equal')
def Ymd(date=None): if date is None: return DateTime.today() elif type(date) in (str, unicode): return DateTime.strptime(date, '%Y-%m-%d') elif type(date) in (type(DateTime.today()), datetime.datetime): return date.strftime('%Y-%m-%d')
def __init__(self, db, const): self._db = db self.co = const midnight = DateTime.today() now = DateTime.now() # if we are past 22:00 this day, schedule for tomorrow evening if (now - midnight) > DateTime.TimeDeltaFrom(hours=22): self.batch_time = midnight + DateTime.TimeDeltaFrom(days=1, hours=22) # ... otherwise, schedule for this day else: self.batch_time = midnight + DateTime.TimeDeltaFrom(hours=22) self.now = now # "None" means _no_ conflicts, there can even be several of # that op pending. All other ops implicitly conflict with # themselves, so there can only be one of each op. self.conflicts = { int(const.bofh_move_user): [ const.bofh_move_student, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_student): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_user_now): [ const.bofh_move_student, const.bofh_move_user, const.bofh_move_request, const.bofh_delete_user ], int(const.bofh_move_request): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ], int(const.bofh_move_give): None, int(const.bofh_archive_user): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ], int(const.bofh_delete_user): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_email_create ], int(const.bofh_email_create): [const.bofh_email_delete, const.bofh_delete_user], int(const.bofh_email_delete): [const.bofh_email_create], int(const.bofh_email_convert): [const.bofh_email_delete], int(const.bofh_sympa_create): [const.bofh_sympa_remove], int(const.bofh_sympa_remove): [const.bofh_sympa_create], int(const.bofh_quarantine_refresh): None, int(const.bofh_email_restore): [const.bofh_email_create], int(const.bofh_homedir_restore): [ const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user ] }
def mail_warnings(mailto, debug=False): """ If warnings of certain types occur, send those as mail to address specified in mailto. If cereconf.EPHORTE_MAIL_TIME is specified, just send if time when script is run matches with specified time. """ # Check if we should send mail today mail_today = False today = DateTime.today() for day in getattr(cereconf, 'EPHORTE_MAIL_TIME', []): if getattr(DateTime, day, None) == today.day_of_week: mail_today = True if mail_today and (ou_mismatch_warnings['ephorte'] or ou_mismatch_warnings['pols']): pols_warnings = '\n'.join( ["%6s %s" % x for x in ou_mismatch_warnings['pols']]) ephorte_warnings = '\n'.join( ["%6s %s" % x for x in ou_mismatch_warnings['ephorte']]) substitute = { 'POLS_WARNINGS': pols_warnings, 'EPHORTE_WARNINGS': ephorte_warnings } send_mail(mailto, cereconf.EPHORTE_MAIL_WARNINGS2, substitute, debug=debug)
def get_date(self, payment, line): """Return the right OPAE Line date""" if not line : return unicode(DateTime.today().strftime("%y%m%d")) to_return = DateTime.today() if payment.date_prefered == 'due' and line.ml_maturity_date : to_return = DateTime.strptime(line.ml_maturity_date, '%Y-%m-%d') if payment.date_prefered == 'fixed' and payment.date_planned : to_return = DateTime.strptime(payment.date_planned, '%Y-%M-%d') if to_return < DateTime.today(): raise wizard.except_wizard( _('Error'), _('Payment date must be at least today\n \ Today used instead.') ) return unicode(to_return.strftime("%y%m%d"))
def set_quaran(cer_ou_tab): """Set quarantine on OUs that are no longer in the data source. All the OUs that were in Cerebrum before an import is run are compared with the data files. Those OUs that are no longer present in the data source are marked as invalid. FIXME: How does it work with multiple data sources? :Parameters: cer_ou_tab : dictionary ou_id -> sko (basestring) mapping, containing the OUs that should be removed from Cerebrum (i.e. the OUs that are in Cerebrum, but not in the data source). """ ous = OU_class(db) today = DateTime.today() acc = Factory.get("Account")(db) acc.find_by_name(cereconf.INITIAL_ACCOUNTNAME) for k in cer_ou_tab.keys(): ous.clear() ous.find(k) if (ous.get_entity_quarantine(qtype=co.quarantine_ou_notvalid) == []): ous.add_entity_quarantine(co.quarantine_ou_notvalid, acc.entity_id, description='import_OU', start=today) db.commit()
def setTime(self, target, from_or_till): today = DateTime.today() col = self._template.getColumn((target, from_or_till)) row = self.getRowForDate(today) now = DateTime.now() value = now.abstime / 60 / 60 / 24 print "+ %s %s: Setting time at (%s, %s) to %s" % (from_or_till, target, row, col, now) self._xlSheet.setCell(row, col, value)
def __init__(self, db, const, id=None): self._db = db self.co = const midnight = DateTime.today() now = DateTime.now() # if we are past 22:00 this day, schedule for tomorrow evening if (now - midnight) > DateTime.TimeDeltaFrom(hours=22): self.batch_time = midnight + DateTime.TimeDeltaFrom(days=1, hours=22) # ... otherwise, schedule for this day else: self.batch_time = midnight + DateTime.TimeDeltaFrom(hours=22) self.now = now # "None" means _no_ conflicts, there can even be several of # that op pending. All other ops implicitly conflict with # themselves, so there can only be one of each op. self.conflicts = { int(const.bofh_move_user): [const.bofh_move_student, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user], int(const.bofh_move_student): [const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_request, const.bofh_delete_user], int(const.bofh_move_user_now): [const.bofh_move_student, const.bofh_move_user, const.bofh_move_request, const.bofh_delete_user], int(const.bofh_move_request): [const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user], int(const.bofh_move_give): None, int(const.bofh_archive_user): [const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user], int(const.bofh_delete_user): [const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_email_create], int(const.bofh_email_create): [const.bofh_email_delete, const.bofh_delete_user], int(const.bofh_email_delete): [const.bofh_email_create], int(const.bofh_email_convert): [const.bofh_email_delete], int(const.bofh_sympa_create): [const.bofh_sympa_remove], int(const.bofh_sympa_remove): [const.bofh_sympa_create], int(const.bofh_quarantine_refresh): None, int(const.bofh_email_restore): [const.bofh_email_create], int(const.bofh_homedir_restore): [const.bofh_move_user, const.bofh_move_user_now, const.bofh_move_student, const.bofh_delete_user] }
def test_expire_permission(self): """Testing if expired test works.""" person_id = self.db_tools.create_person(self.person_ds().next()) account_id = self.db_tools.create_account(self.account_ds().next()) ou_id = self.db_tools.create_ou( {'name': 'ephorte-test', 'acronym': 'ET', 'short_name': 'ePhorte-test', 'display_name': 'Test OU for ePhorte'}) self._ep.add_permission( person_id, self._co.ephorte_perm_ar, ou_id, account_id) self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id) self.assertFalse( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired w/o date') self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id, DateTime.today() - 1) self.assertFalse( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired with date') self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id, DateTime.today() + 1) self.assertTrue( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired with date in fututre')
def test_expire_permission(self): """Testing if expired test works.""" person_id = self.db_tools.create_person(self.person_ds().next()) account_id = self.db_tools.create_account(self.account_ds().next()) ou_id = self.db_tools.create_ou({ 'name': 'ephorte-test', 'acronym': 'ET', 'short_name': 'ePhorte-test', 'display_name': 'Test OU for ePhorte' }) self._ep.add_permission(person_id, self._co.ephorte_perm_ar, ou_id, account_id) self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id) self.assertFalse( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired w/o date') self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id, DateTime.today() - 1) self.assertFalse( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired with date') self._ep.expire_permission(person_id, self._co.ephorte_perm_ar, ou_id, DateTime.today() + 1) self.assertTrue( self._ep.list_permission(person_id, self._co.ephorte_perm_ar, ou_id, filter_expired=True), 'Permission could not be expired with date in fututre')
def __init__(self, TASK=None, CATEGORY1=None, STARTDATE=None, CATEGORY3=None, CATEGORY2=None, CATEGORY5=None, CATEGORY4=None, CATEGORY7=None, CATEGORY6=None, CATEGORY9=None, CATEGORY8=None, NUMPERSON=None, PERSON2=None, PERSON3=None, COST=None, EXTERNALID=None, DEPENDS9=None, PERSON4=None, PERSON5=None, DUEDATESTRING=None, ICONINDEX=None, CREATIONDATESTRING=None, PERSON9=None, WEBCOLOR=None, PERSON8=None, LASTMOD=None, TIMEESTUNITS=None, COLOR=None, TITLE=None, LASTMODSTRING=None, PRIORITYWEBCOLOR=None, POS=None, ID=None, PRIORITY=None, CALCTIMESPENT=None, DEPENDS=None, NUMCATEGORY=None, DONEDATESTRING=None, CREATIONDATE=None, PERCENTDONE=None, TIMEESTIMATE=None, STATUS=None, DEPENDS7=None, ALLOCATEDBY=None, DONEDATE=None, RISK=None, STARTDATESTRING=None, TEXTCOLOR=None, NUMDEPENDS=None, CALCPERCENTDONE=None, FLAG=None, VERSION=None, TIMESPENT=None, TEXTWEBCOLOR=None, PRIORITYCOLOR=None, FILEREFPATH=None, DUEDATE=None, CALCTIMEESTIMATE=None, CATEGORY=None, DEPENDS6=None, DEPENDS5=None, DEPENDS4=None, DEPENDS3=None, DEPENDS2=None, DEPENDS1=None, CUSTOMCOMMENTS=None, TIMESPENTUNITS=None, COMMENTS=None, DEPENDS8=None, PERSON=None, PERSON1=None, CALCCOST=None, PERSON6=None, COMMENTSTYPE=None, PERSON7=None, valueOf_=''): supermod.TASK.__init__(self, CATEGORY1, STARTDATE, CATEGORY3, CATEGORY2, CATEGORY5, CATEGORY4, CATEGORY7, CATEGORY6, CATEGORY9, CATEGORY8, NUMPERSON, PERSON2, PERSON3, COST, EXTERNALID, DEPENDS9, PERSON4, PERSON5, DUEDATESTRING, ICONINDEX, CREATIONDATESTRING, PERSON9, WEBCOLOR, PERSON8, LASTMOD, TIMEESTUNITS, COLOR, TITLE, LASTMODSTRING, PRIORITYWEBCOLOR, POS, ID, PRIORITY, CALCTIMESPENT, DEPENDS, NUMCATEGORY, DONEDATESTRING, CREATIONDATE, PERCENTDONE, TIMEESTIMATE, STATUS, DEPENDS7, ALLOCATEDBY, DONEDATE, RISK, STARTDATESTRING, TEXTCOLOR, NUMDEPENDS, CALCPERCENTDONE, FLAG, VERSION, TIMESPENT, TEXTWEBCOLOR, PRIORITYCOLOR, FILEREFPATH, DUEDATE, CALCTIMEESTIMATE, CATEGORY, DEPENDS6, DEPENDS5, DEPENDS4, DEPENDS3, DEPENDS2, DEPENDS1, CUSTOMCOMMENTS, TIMESPENTUNITS, COMMENTS, DEPENDS8, PERSON, PERSON1, CALCCOST, PERSON6, COMMENTSTYPE, PERSON7, valueOf_) if TASK is None: self.TASK = [] else: self.TASK = TASK if PRIORITYCOLOR is None or PRIORITYWEBCOLOR is None: self.PRIORITYCOLOR = "15732480" self.PRIORITYWEBCOLOR = "#000FF0" else: self.PRIORITYCOLOR = PRIORITYCOLOR self.PRIORITYWEBCOLOR = PRIORITYWEBCOLOR if COST is None: self.COST = '0.00000000' else: self.COST = COST if CREATIONDATE is None or CREATIONDATESTRING is None: td = DateTime.today() self.CREATIONDATE = td.COMDate() self.CREATIONDATESTRING = td.strftime('%m/%d/%Y') else: self.CREATIONDATE = CREATIONDATE self.CREATIONDATESTRING = CREATIONDATESTRING if CALCCOST is None: self.CALCCOST = '0.00000000' else: self.CALCCOST = CALCCOST if ICONINDEX is None: self.ICONINDEX = -1 else: self.ICONINDEX = ICONINDEX if PERCENTDONE is None: self.PERCENTDONE = 0 else: self.PERCENTDONE = PERCENTDONE if PRIORITY is None: self.PRIORITY = 5 else: self.PRIORITY = PRIORITY if RISK is None: self.RISK = 0 else: self.RISK = RISK if STARTDATE is None or sTARTDATESTRING is None: self.STARTDATE = self.CREATIONDATE self.STARTDATESTRING = self.CREATIONDATESTRING else: self.STARTDATE = STARTDATE self.STARTDATESTRING = STARTDATESTRING
def release_guest(self, guest, operator_id): """Release a guest account from temporary owner. Make sure that the guest account specified actually exists and release it from owner. The guest account is now in release_quarantine and will be available for new allocations when the quarantine period is due. @param guest: uname of guest account @type guest: str @param operator_id: entity id of operator @type operator_id: int """ ac = Factory.get('Account')(self.db) ac.find_by_name(guest) trait = ac.get_trait(self.co.trait_uio_guest_owner) if trait is None: raise GuestAccountException("%s is not a guest" % guest) elif trait['target_id'] is None: raise GuestAccountException("%s is already available" % guest) # Clear the password so that the account can't be used ac.delete_password() # delete_password() writes its changes directly # Remove owner, i.e set owner_trait to None ac.populate_trait(self.co.trait_uio_guest_owner, target_id=None) self.logger.debug("Removed owner_id in owner_trait for %s" % guest) # Remove quarantine set by _alloc_guest and set a new # quarantine that kicks in now. if ac.get_entity_quarantine(self.co.quarantine_guest_release): ac.delete_entity_quarantine(self.co.quarantine_guest_release) ac.add_entity_quarantine(self.co.quarantine_guest_release, operator_id, "Guest user released", start=DateTime.today()) self.logger.debug("%s is now in release_quarantine" % guest) ac.write_db() self.update_group_memberships(ac.entity_id) self.logger.debug("Updating group memberships for %s" % guest) # Finally, register a request to archive the home directory. # A new directory will be created when archival has been done. br = BofhdRequests(self.db, self.co) br.add_request(operator_id, br.now, self.co.bofh_archive_user, ac.entity_id, None, state_data=int(self.co.spread_uio_nis_user)) self.logger.debug("Added archive_user request for %s" % guest)
def user_request_guest(self, operator, nr, date, groupname, comment): """ Request a number of guest users for a certain time. """ # date checking start_date, end_date = self._parse_date_from_to(date) today = DateTime.today() if start_date < today: raise CerebrumError("Start date shouldn't be in the past") # end_date in allowed interval? if end_date < start_date: raise CerebrumError("End date can't be earlier than start_date") max_date = start_date + DateTime.RelativeDateTime( days=cereconf.GUESTS_MAX_PERIOD) if end_date > max_date: raise CerebrumError("End date can't be later than %s" % max_date.date) if not nr.isdigit(): raise CerebrumError( "'Number of accounts' requested must be a number;" " %r isn't." % nr) try: self.ba.can_request_guests(operator.get_entity_id(), groupname) except Errors.NotFoundError: raise CerebrumError("Group %r not found" % groupname) owner = self.util.get_target(groupname, default_lookup="group") try: user_list = self.bgu.request_guest_users( int(nr), end_date, comment, owner.entity_id, operator.get_entity_id()) for uname, comment, e_id, passwd in user_list: operator.store_state("new_account_passwd", {'account_id': e_id, 'password': passwd}) ret = "OK, reserved guest users:\n%s\n" % \ self._pretty_print([x[0] for x in user_list]) ret += "Please use misc list_passwords to view the passwords\n" ret += "or use misc print_passwords to print the passwords." return ret except GuestAccountException as e: raise CerebrumError(e)
def user_request_guest(self, operator, nr, date, groupname, comment): """ Request a number of guest users for a certain time. """ # date checking start_date, end_date = self._parse_date_from_to(date) today = DateTime.today() if start_date < today: raise CerebrumError("Start date shouldn't be in the past") # end_date in allowed interval? if end_date < start_date: raise CerebrumError("End date can't be earlier than start_date") max_date = start_date + DateTime.RelativeDateTime( days=cereconf.GUESTS_MAX_PERIOD) if end_date > max_date: raise CerebrumError( "End date can't be later than %s" % max_date.date) if not nr.isdigit(): raise CerebrumError( "'Number of accounts' requested must be a number;" " '%s' isn't." % nr) try: self.ba.can_request_guests(operator.get_entity_id(), groupname) except Errors.NotFoundError: raise CerebrumError("Group '%s' not found" % groupname) owner = self.util.get_target(groupname, default_lookup="group") try: user_list = self.bgu.request_guest_users( int(nr), end_date, comment, owner.entity_id, operator.get_entity_id()) for uname, comment, e_id, passwd in user_list: operator.store_state("new_account_passwd", {'account_id': e_id, 'password': passwd}) ret = "OK, reserved guest users:\n%s\n" % \ self._pretty_print([x[0] for x in user_list]) ret += "Please use misc list_passwords to view the passwords\n" ret += "or use misc print_passwords to print the passwords." return ret except GuestAccountException, e: raise CerebrumError(str(e))
def _get_age(self, cr, uid, ids, field_name, arg, context={}): # print 'JE PASSE PAR _GET_AGE et CONTEXT is:', context _logger.info('in _get_age ...') res = {} records = self.browse(cr, uid, ids, context) date = DateTime.today() for record in records: age = '' res[record.id] = { 'age': '', } birthdate = False if record.dob: birthdate = DateTime.strptime(record.dob, '%Y-%m-%d') year, month, day = birthdate.year, birthdate.month, birthdate.day if birthdate: day = int(day) month = int(month) year = int(year) if (date.month > month) or (date.month == month and date.day >= day): if (date.year - year) >= 2: age = str(date.year - year) + _(' YO') else: if date.year == year: age = str(date.month - month) + _(' month') else: age = str(12 + date.month - month) + _(' month') else: if (date.year - year - 1) >= 2: age = str(date.year - year - 1) + _(' YO') else: months = date.month - month if date.month == month: months = -1 if date.year == year: age = str(months) + _(' month') elif date.year == year + 1: age = str(12 + months) + _(' month') elif date.year == year + 2: age = str(24 + months) + _(' month') res[record.id]['age'] += age return res
def thread_sendDataFunction(): global gotDataException,sentSimulatedData print 'thead_sendDataFunction started' while 1: lastTime=time.time() lt=time.localtime() # NASDAQ open? x=lt[3]*100+lt[4] if DateTime.today().day_of_week>=5 or x<930 or x>1600 or gotDataException>3 or alwaysSimulate: sleepTime=NASDAQ_MINSWEEPTIME sendSimulatedData() else: sleepTime=NASDAQ_MINSWEEPTIME/2 sendAllChangedTickerData() if (time.time()-lastTime)<sleepTime: time.sleep(max(sleepTime-time.time()+lastTime,1))
def release_guest(self, guest, operator_id): """Release a guest account from temporary owner. Make sure that the guest account specified actually exists and release it from owner. The guest account is now in release_quarantine and will be available for new allocations when the quarantine period is due. @param guest: uname of guest account @type guest: str @param operator_id: entity id of operator @type operator_id: int """ ac = Factory.get('Account')(self.db) ac.find_by_name(guest) trait = ac.get_trait(self.co.trait_uio_guest_owner) if trait is None: raise GuestAccountException("%s is not a guest" % guest) elif trait['target_id'] is None: raise GuestAccountException("%s is already available" % guest) # Remove owner, i.e set owner_trait to None ac.populate_trait(self.co.trait_uio_guest_owner, target_id=None) self.logger.debug("Removed owner_id in owner_trait for %s" % guest) # Remove quarantine set by _alloc_guest and set a new # quarantine that kicks in now. if ac.get_entity_quarantine(self.co.quarantine_guest_release): ac.delete_entity_quarantine(self.co.quarantine_guest_release) ac.add_entity_quarantine(self.co.quarantine_guest_release, operator_id, "Guest user released", start=DateTime.today()) self.logger.debug("%s is now in release_quarantine" % guest) ac.set_password(ac.make_passwd(guest)) ac.write_db() self.update_group_memberships(ac.entity_id) self.logger.debug("Updating group memberships for %s" % guest) # Finally, register a request to archive the home directory. # A new directory will be created when archival has been done. br = BofhdRequests(self.db, self.co) br.add_request(operator_id, br.now, self.co.bofh_archive_user, ac.entity_id, None, state_data=int(self.co.spread_uio_nis_user)) self.logger.debug("Added archive_user request for %s" % guest)
def thread_sendDataFunction(): global gotDataException, sentSimulatedData print 'thead_sendDataFunction started' while 1: lastTime = time.time() lt = time.localtime() # NASDAQ open? x = lt[3] * 100 + lt[4] if DateTime.today( ).day_of_week >= 5 or x < 930 or x > 1600 or gotDataException > 3 or alwaysSimulate: sleepTime = NASDAQ_MINSWEEPTIME sendSimulatedData() else: sleepTime = NASDAQ_MINSWEEPTIME / 2 sendAllChangedTickerData() if (time.time() - lastTime) < sleepTime: time.sleep(max(sleepTime - time.time() + lastTime, 1))
def mail_warnings(mailto, debug=False): """ If warnings of certain types occur, send those as mail to address specified in mailto. If cereconf.EPHORTE_MAIL_TIME is specified, just send if time when script is run matches with specified time. """ # Check if we should send mail today mail_today = False today = DateTime.today() for day in getattr(cereconf, 'EPHORTE_MAIL_TIME', []): if getattr(DateTime, day, None) == today.day_of_week: mail_today = True if mail_today and (ou_mismatch_warnings['ephorte'] or ou_mismatch_warnings['pols']): pols_warnings = '\n'.join(["%6s %s" % x for x in ou_mismatch_warnings['pols']]) ephorte_warnings = '\n'.join(["%6s %s" % x for x in ou_mismatch_warnings['ephorte']]) substitute = {'POLS_WARNINGS': pols_warnings, 'EPHORTE_WARNINGS': ephorte_warnings} send_mail(mailto, cereconf.EPHORTE_MAIL_WARNINGS2, substitute, debug=debug)
def _default_date(*args): res = mdt.today() + mdt.oneDay return res.strftime('%Y-%m-%d 09:00:00')
def generate_task_realisasi_bulanan(self, cr, uid, ids, context=None): if context is None: context = {} task = {} task_pool = self.pool.get('project.task') stage_pool = self.pool.get('project.task.type') for task_generate in self.browse(cr, uid, ids, context=context): #check Duplicate #Init Field target_category='bulanan' description='' lama_kegiatan=task_generate.lama_kegiatan user_id = task_generate.user_id.id target_period_year = task_generate.target_period_year target_period_month='xx' date_start='xx' date_end='xx' company_id=None currency_id=None user_id_bkd=None employee = self.get_employee_from_user_id( cr, uid, task_generate); if user_id!=uid: raise osv.except_osv(_('Invalid Action!'), _('Anda Tidak Memiliki Priviledge Untuk Proses Ini.')) if not employee : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Ada Beberapa Informasi Kepegawaian Belum Diisi, Khususnya Data Pejabat Penilai Dan Atasan Banding.')) else : company = employee.company_id company_id = company.id currency_id= employee.company_id.currency_id #print "company_id : ",company_id,' - ',currency_id if not company_id : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Unit Dinas Pegawai Belum Dilengkapi.')) #print "employee parent : ",employee.parent_id if not task_generate.user_id_bkd: if not company.user_id_bkd : raise osv.except_osv(_('Invalid Action, Data Dinas Kurang Lengkap'), _('Staff Pemeriksa Dari BKD Tidak Tersedia Untuk Unit Anda, Silahkan hubungi Admin Atau isi Data Pemeriksa.')) else : user_id_bkd = company.user_id_bkd.id else : user_id_bkd=task_generate.user_id_bkd.id if not employee.user_id_atasan : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Penilai Belum Terisi.')) if not employee.user_id_banding : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Pengajuan Banding.')) user_id_atasan =task_generate.user_id_atasan.id user_id_banding=task_generate.user_id_banding.id if not task_generate.user_id_atasan.id : user_id_atasan = employee.user_id_atasan.user_id.id if not task_generate.user_id_banding.id : user_id_banding = employee.user_id_banding.user_id.id task.update({ 'project_id':None, 'user_id':user_id, 'company_id':company_id, 'description':description, 'name': task_generate.name, 'code': None, 'target_category': target_category, #'sequence': target_obj.priority, 'target_type_id':task_generate.target_type_id, 'target_period_year': target_period_year, 'user_id_atasan': user_id_atasan or False, 'user_id_banding':user_id_banding or False, 'user_id_bkd':user_id_bkd or False, 'priority':'2', 'currency_id':currency_id, 'target_waktu' : 0, 'target_kualitas' : 0, 'target_jumlah_kuantitas_output' : 0, 'task_category':'non_skp', }) #Update Task Target Bulanan now=DateTime.today(); first_task_id=None if task_generate.date_start : curr_date = DateTime.strptime(task_generate.date_start,'%Y-%m-%d') else : january=DateTime.Date(now.year,1,1) curr_date = DateTime.strptime(january.strftime('%Y-%m-%d'),'%Y-%m-%d') first_date =curr_date #print "THIS IS A DATE ",curr_date for i in range(0,lama_kegiatan): next_date = curr_date + DateTime.RelativeDateTime(months=i) target_period_month=next_date.strftime('%m') task.update({ 'target_period_month':target_period_month, 'name': '%s %s' % (task_generate.name,target_period_month), }) #Check Duplicate Do Not Create task_ids = task_pool.search(cr, uid, [('user_id','=',user_id),('target_period_month','=',target_period_month),('target_period_year','=',target_period_year), ('target_type_id','=',task_generate.target_type_id),('work_state','!=','draft')], context=None) if task_ids: continue; else : #Delete Duplicate task_ids = task_pool.search(cr, uid, [('user_id','=',user_id),('target_period_month','=',target_period_month),('target_period_year','=',target_period_year), ('target_type_id','=',task_generate.target_type_id),('work_state','=','draft')], context=None) task_pool.unlink(cr, uid, task_ids, context=None) date_start='xx' date_end='xx' stage_ids = stage_pool.search(cr,uid,[('sequence','=',0)], context=None) work_state='draft'; if stage_ids : task.update({ 'stage_id': stage_ids[0], 'work_state':work_state, 'state':'draft', 'currency_id':currency_id }) #insert task task_id = task_pool.create(cr, uid, task) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'notification.generate.task', 'target': 'new', 'context': context,#['notif_booking'], }
def pquota_info(self, operator, person): person_id = self.bu.find_person(person) try: ppq_info = self.bu.get_pquota_status(person_id) except errors.UserHasNoQuota as e: return "%s: %s" % (person, e) has_quota = ppq_info['has_quota'] has_blocked_quota = ppq_info['has_blocked_quota'] import math paid_quota = int(math.floor(1/printer_quota.PAGE_COST * float(ppq_info['kroner']))) total_available_quota = (paid_quota + ppq_info['free_quota'] + ppq_info['accum_quota']) if has_quota == 'T': if has_blocked_quota == 'T': try: bdate, pnum = self.bu.get_bdate_and_pnum(person_id) except errors.NotFoundError: # TBD: Can this happen? return person + ": Quota has been blocked, person not in FS" try: fs = database.connect(user=cereconf.FS_USER, service=cereconf.FS_DATABASE_NAME, DB_driver=cereconf.DB_DRIVER_ORACLE) except database.DatabaseError as e: self.logger.warn("Can't connect to FS (%s)" % e) raise CerebrumError("Can't connect to FS, try later") # Estimate when Cerebrum was updated from FS last. We # assume it happens every morning at 07:00. # # We make some effort to get daylight saving and # timezone right since DCOracle2.Timestamp doesn't. this_morning = DateTime.now() if this_morning.hour < 7: this_morning = DateTime.today() + DateTime.RelativeDateTime(hour=7) reason = ["%s: Printer quota has been blocked due to:" % person] from Cerebrum.modules.no.access_FS import Student student = Student(fs) reg = student.get_semreg(bdate, pnum) if not reg: reason.append(' * Semester fee has not been paid, and ' 'semester registration is missing') elif reg[0]['regformkode'] == 'KUNBETALT': reason.append(' * Semester fee is paid, but semester ' 'registration is missing') elif reg[0]['dato_regform_endret'] > this_morning: reason.append(' * Semester registration was done today, ' 'please wait for nightly update') from Cerebrum.modules.no.uio.access_FS import UiOBetaling bet = UiOBetaling(fs) if not bet.list_kopiavgift_data(kun_fritak=False, fodselsdato=bdate, personnr=pnum): reason.append(" * Copy fee has not been paid") if len(reason) == 1: reason.append(" * Please wait for nightly update") return "\n".join(reason) if total_available_quota == 0: return "%s: No prints available" % person elif total_available_quota < 0: return ("%s: No prints available, overdraft is %d prints" % (person, abs(total_available_quota))) return "%s: %d prints available" % (person, total_available_quota) else: return "%s: Printer quota is unlimited" % person
# along with X4GA. If not, see <http://www.gnu.org/licenses/>. # ------------------------------------------------------------------------------ import wx import wx.lib.masked as masked import wx.calendar from mx import DateTime from awc.controls import evt_DATECHANGED, EVT_DATECHANGED from awc.controls import evt_DATEFOCUSLOST, EVT_DATEFOCUSLOST import awc.controls.windows as aw import awc.controls.mixin as cmix import awc.util as awu YEAR_DEFAULT = DateTime.today().year def SetYearDefault(yd): global YEAR_DEFAULT YEAR_DEFAULT = yd class DateChangedEvent(wx.PyCommandEvent): def __init__(self, *args, **kwargs): wx.PyCommandEvent.__init__(self, *args, **kwargs) self._date = None def SetValue(self, date): self._date = date
def set_quarantine(pids, quar, offset, quarantined): """Quarantine the given persons' accounts. :param list pids: Person IDs that will be evaluated for quarantine. :param _QuarantineCode quar: The quarantine that will be set on accounts referenced in `pids`. :param int offset: The number of days until the quarantine starts. :param set quarantined: Account IDs for those already in any active quarantine. Any account in here will neither be warned nor quarantined. :rtype: set :return: The account IDs for those that were quarantined in this round. """ ac.clear() ac.find_by_name(cereconf.INITIAL_ACCOUNTNAME) creator = ac.entity_id success = set() failed_notify = 0 no_processed = 0 date = DateTime.today() + offset # Cache what entities has the target quarantine: with_target_quar = set( r['entity_id'] for r in ac.list_entity_quarantines(quarantine_types=quar, only_active=False, entity_types=co.entity_account) if r['start_date'] <= date) logger.debug2('Accounts with target quarantine: %d', len(with_target_quar)) # Cache the owner to account relationship: pid2acs = {} for row in ac.search(owner_type=co.entity_person): pid2acs.setdefault(row['owner_id'], []).append(row) logger.debug2('Mapped %d persons to accounts', len(pid2acs)) for pid in pids: for row in pid2acs.get(pid, ()): if row['account_id'] in quarantined or row['account_id'] in success: continue no_processed += 1 if row['account_id'] in with_target_quar: logger.debug2('Already got the quarantine: %s', row['name']) continue ac.clear() ac.find(row['account_id']) # We will not send any warning if # - In dryrun mode # - No mail template is set # - The account is reserved, i.e. has no spreads. # This is in effect, at least for the user, # about the same as being in quarantine. if ac.is_reserved() or not email_info or dryrun: notified = True else: notified = notify_user(ac, offset) if notified: ac.delete_entity_quarantine(quar) ac.add_entity_quarantine(quar, creator, start=date) # Commiting here to avoid that users get multiple emails if the # script is stopped before it's done. ac.commit() logger.info('Added %s quarantine for: %s', quar, ac.account_name) success.add(ac.entity_id) else: failed_notify += 1 logger.debug('Accounts processed: %d', no_processed) logger.debug('Quarantines added: %d', len(success)) logger.debug('Accounts failed: %d', failed_notify) return success
def generate_task_realisasi_bulanan(self, cr, uid, ids, context=None): if context is None: context = {} task = {} task_pool = self.pool.get('project.task') stage_pool = self.pool.get('project.task.type') for task_generate in self.browse(cr, uid, ids, context=context): #check Duplicate #Init Field target_category = 'bulanan' description = '' lama_kegiatan = task_generate.lama_kegiatan user_id = task_generate.user_id.id target_period_year = task_generate.target_period_year target_period_month = 'xx' date_start = 'xx' date_end = 'xx' company_id = None currency_id = None user_id_bkd = None employee = self.get_employee_from_user_id(cr, uid, task_generate) if user_id != uid: raise osv.except_osv( _('Invalid Action!'), _('Anda Tidak Memiliki Priviledge Untuk Proses Ini.')) if not employee: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Ada Beberapa Informasi Kepegawaian Belum Diisi, Khususnya Data Pejabat Penilai Dan Atasan Banding.' )) else: company = employee.company_id company_id = company.id currency_id = employee.company_id.currency_id #print "company_id : ",company_id,' - ',currency_id if not company_id: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Unit Dinas Pegawai Belum Dilengkapi.' )) #print "employee parent : ",employee.parent_id if not task_generate.user_id_bkd: if not company.user_id_bkd: raise osv.except_osv( _('Invalid Action, Data Dinas Kurang Lengkap'), _('Staff Pemeriksa Dari BKD Tidak Tersedia Untuk Unit Anda, Silahkan hubungi Admin Atau isi Data Pemeriksa.' )) else: user_id_bkd = company.user_id_bkd.id else: user_id_bkd = task_generate.user_id_bkd.id if not employee.user_id_atasan: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Penilai Belum Terisi.' )) if not employee.user_id_banding: raise osv.except_osv( _('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Pengajuan Banding.' )) user_id_atasan = task_generate.user_id_atasan.id user_id_banding = task_generate.user_id_banding.id if not task_generate.user_id_atasan.id: user_id_atasan = employee.user_id_atasan.user_id.id if not task_generate.user_id_banding.id: user_id_banding = employee.user_id_banding.user_id.id task.update({ 'project_id': None, 'user_id': user_id, 'company_id': company_id, 'description': description, 'name': task_generate.name, 'code': None, 'target_category': target_category, #'sequence': target_obj.priority, 'target_type_id': task_generate.target_type_id, 'target_period_year': target_period_year, 'user_id_atasan': user_id_atasan or False, 'user_id_banding': user_id_banding or False, 'user_id_bkd': user_id_bkd or False, 'priority': '2', 'currency_id': currency_id, 'target_waktu': 0, 'target_kualitas': 0, 'target_jumlah_kuantitas_output': 0, 'task_category': 'non_skp', }) #Update Task Target Bulanan now = DateTime.today() first_task_id = None if task_generate.date_start: curr_date = DateTime.strptime(task_generate.date_start, '%Y-%m-%d') else: january = DateTime.Date(now.year, 1, 1) curr_date = DateTime.strptime(january.strftime('%Y-%m-%d'), '%Y-%m-%d') first_date = curr_date #print "THIS IS A DATE ",curr_date for i in range(0, lama_kegiatan): next_date = curr_date + DateTime.RelativeDateTime(months=i) target_period_month = next_date.strftime('%m') task.update({ 'target_period_month': target_period_month, 'name': '%s %s' % (task_generate.name, target_period_month), }) #Check Duplicate Do Not Create task_ids = task_pool.search( cr, uid, [('user_id', '=', user_id), ('target_period_month', '=', target_period_month), ('target_period_year', '=', target_period_year), ('target_type_id', '=', task_generate.target_type_id), ('work_state', '!=', 'draft')], context=None) if task_ids: continue else: #Delete Duplicate task_ids = task_pool.search( cr, uid, [('user_id', '=', user_id), ('target_period_month', '=', target_period_month), ('target_period_year', '=', target_period_year), ('target_type_id', '=', task_generate.target_type_id), ('work_state', '=', 'draft')], context=None) task_pool.unlink(cr, uid, task_ids, context=None) date_start = 'xx' date_end = 'xx' stage_ids = stage_pool.search(cr, uid, [('sequence', '=', 0)], context=None) work_state = 'draft' if stage_ids: task.update({ 'stage_id': stage_ids[0], 'work_state': work_state, 'state': 'draft', 'currency_id': currency_id }) #insert task task_id = task_pool.create(cr, uid, task) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'notification.generate.task', 'target': 'new', 'context': context, #['notif_booking'], }
# ------------------------------------------------------------------------------ import wx import wx.lib.masked as masked import wx.calendar from mx import DateTime from awc.controls import evt_DATECHANGED, EVT_DATECHANGED from awc.controls import evt_DATEFOCUSLOST, EVT_DATEFOCUSLOST import awc.controls.windows as aw import awc.controls.mixin as cmix import awc.util as awu YEAR_DEFAULT = DateTime.today().year def SetYearDefault(yd): global YEAR_DEFAULT YEAR_DEFAULT = yd class DateChangedEvent(wx.PyCommandEvent): def __init__(self, *args, **kwargs): wx.PyCommandEvent.__init__(self, *args, **kwargs) self._date = None def SetValue(self, date): self._date = date def GetValue(self): return self._date class DateFocusLostEvent(wx.PyCommandEvent):
import cereconf from Cerebrum import Errors from Cerebrum.Utils import Factory from Cerebrum.utils.context import entity, entitise from Cerebrum.modules.bofhd_requests.request import BofhdRequests logger = Factory.get_logger("cronjob") database = Factory.get("Database")() database.cl_init(change_program="deactivate-qua") constants = Factory.get("Constants")(database) # we could probably generalise and use entity here, but for now we # need only look at accounts account = Factory.get("Account")(database) person = Factory.get("Person")(database) today = dt.today() account.find_by_name(cereconf.INITIAL_ACCOUNTNAME) operator_id = account.entity_id account.clear() def fetch_all_relevant_accounts(qua_type, since, ignore_affs, system_accounts): """Fetch all accounts that matches the criterias for deactivation. :param QuarantineCode qua_type: The quarantine that the accounts must have to be targeted. :param int since: The number of days a quarantine must have been active for the account to be targeted.
def __init__(self, model, axis, fields, attrs): self.glade = gtk.glade.XML(common.terp_path("openerp.glade"),'widget_view_calendar', gettext.textdomain()) self.widget = self.glade.get_widget('widget_view_calendar') self._label_current = self.glade.get_widget('label_current') self._radio_month = self.glade.get_widget('radio_month') self._radio_week = self.glade.get_widget('radio_week') self._radio_day = self.glade.get_widget('radio_day') self._small_calendar = self.glade.get_widget('calendar_small') self._calendar_treeview = self.glade.get_widget('calendar_treeview') self._radio_month.set_active(True) self.mode = 'month' self.fields = fields self.attrs = attrs self.axis = axis self.screen = None self.cal_model = TinyCalModel() self.cal_view = Calendar.Calendar(self.cal_model) self.cal_view.connect('event-clicked', self._on_event_clicked) self.cal_view.connect('do_month_back_forward', self._back_forward) self.cal_view.connect('day-selected', self._change_small) vbox = self.glade.get_widget('cal_vbox') vbox.pack_start(self.cal_view) vbox.show_all() self.process = False self.glade.signal_connect('on_but_forward_clicked', self._back_forward, 1) self.glade.signal_connect('on_but_back_clicked', self._back_forward, -1) self.glade.signal_connect('on_but_today_clicked', self._today) self.glade.signal_connect('on_calendar_small_day_selected_double_click', self._change_small) self.glade.signal_connect('on_button_day_clicked', self._change_view, 'day') self.glade.signal_connect('on_button_week_clicked', self._change_view, 'week') self.glade.signal_connect('on_button_month_clicked', self._change_view, 'month') self.date = DateTime.today() self.string = attrs.get('string', '') self.date_start = attrs.get('date_start') self.date_delay = attrs.get('date_delay') self.date_stop = attrs.get('date_stop') self.color_field = attrs.get('color') self.day_length = int(attrs.get('day_length', 8)) self.colors = {} self.models = None if self.color_field: model = gtk.ListStore(str, str, str) self._calendar_treeview.set_model(model) self._calendar_treeview.get_selection().set_mode(gtk.SELECTION_NONE) for c in (self.TV_COL_ID, self.TV_COL_COLOR): column = gtk.TreeViewColumn(None, gtk.CellRendererText(), text=c) self._calendar_treeview.append_column(column) column.set_visible(False) renderer = gtk.CellRendererText() column = gtk.TreeViewColumn(None, renderer, text=self.TV_COL_LABEL) col_label = gtk.Label('') col_label.set_markup('<b>%s</b>' % self.fields[self.color_field]['string']) col_label.show() column.set_widget(col_label) column.set_cell_data_func(renderer, self._treeview_setter) self._calendar_treeview.append_column(column)
def _today(self, widget, *args, **argv): self.date = DateTime.today() self.display(None)
def set_quarantine(pids, quar, offset, quarantined): """Quarantine the given persons' accounts. :param list pids: Person IDs that will be evaluated for quarantine. :param _QuarantineCode quar: The quarantine that will be set on accounts referenced in `pids`. :param int offset: The number of days until the quarantine starts. :param set quarantined: Account IDs for those already in any active quarantine. Any account in here will neither be warned nor quarantined. :rtype: set :return: The account IDs for those that were quarantined in this round. """ ac.clear() ac.find_by_name(cereconf.INITIAL_ACCOUNTNAME) creator = ac.entity_id success = set() failed_notify = 0 no_processed = 0 date = DateTime.today() + offset # Cache what entities has the target quarantine: with_target_quar = set( r['entity_id'] for r in ac.list_entity_quarantines(quarantine_types=quar, only_active=False, entity_types=co.entity_account) if r['start_date'] <= date) logger.debug2('Accounts with target quarantine: %d', len(with_target_quar)) # Cache the owner to account relationship: pid2acs = {} for row in ac.search(owner_type=co.entity_person): pid2acs.setdefault(row['owner_id'], []).append(row) logger.debug2('Mapped %d persons to accounts', len(pid2acs)) for pid in pids: for row in pid2acs.get(pid, ()): if (row['account_id'] in quarantined) or (row['account_id'] in success): continue no_processed += 1 if row['account_id'] in with_target_quar: logger.debug2('Already got the quarantine: %s', row['name']) continue ac.clear() ac.find(row['account_id']) # We will not send any warning if # - In dryrun mode # - No mail template is set # - The account is reserved, i.e. has no spreads. # This is in effect, at least for the user, # about the same as being in quarantine. if ac.is_reserved() or not email_info or dryrun: notified = True else: notified = notify_user(ac, offset) if notified: ac.delete_entity_quarantine(quar) ac.add_entity_quarantine(quar, creator, start=date) # Commiting here to avoid that users get multiple emails if the # script is stopped before it's done. ac.commit() logger.info('Added %s quarantine for: %s', quar, ac.account_name) success.add(ac.entity_id) else: failed_notify += 1 logger.debug('Accounts processed: %d', no_processed) logger.debug('Quarantines added: %d', len(success)) logger.debug('Accounts failed: %d', failed_notify) return success
def __init__(self, fmt, age_years=False): self.fmt = to_fmt(fmt) self.fix_year = '%y' in self.fmt and age_years if self.fix_year: self.year_adj = DateTime.RelativeDate(years=100) self.year_cutoff = DateTime.today().year + 1
def get_regular_date(sentence): datelist=[] rdatelist=[] base_date=DateTime.today() regxp1 = "(" + prep + " (" + day + "))" reg1=re.compile(regxp1) reg2=re.compile(rel_day) found = reg1.findall(sentence) found = [a[0] for a in found if len(a) > 1] for item in found: datelist.append(item) found = reg2.findall(sentence) for item in found: datelist.append(item) #日期->YYYY-MM-DD for item in datelist: if re.match(r'today', item): item = str(base_date) item = re.sub(r'\s.*', '', item) rdatelist.append(item) elif re.match(r'tomorrow',item): item=str(base_date + DateTime.RelativeDateTime(days=+1)) item = re.sub(r'\s.*', '', item) rdatelist.append(item) elif re.match(r'the day after tomorrow',item): item=str(base_date+DateTime.RelativeDateTime(days=+2)) item = re.sub(r'\s.*', '', item) rdatelist.append(item) # Weekday in the current week. elif re.match(r'this ' + day, item): days = hashweekdays[item.split()[1]] item = str(base_date + DateTime.RelativeDateTime(weeks=0, \ weekday=(days,0))) item = re.sub(r'\s.*', '', item) rdatelist.append(item) # Weekday in the following week. elif re.match(r'next ' + day, item): days = hashweekdays[item.split()[1]] item = str(base_date + DateTime.RelativeDateTime(weeks=+1, \ weekday=(days,0))) item = re.sub(r'\s.*', '', item) rdatelist.append(item) else: continue return rdatelist
import cereconf from Cerebrum import Errors from Cerebrum.Utils import Factory from Cerebrum.utils.context import entity, entitise from Cerebrum.modules.bofhd.utils import BofhdRequests logger = Factory.get_logger("cronjob") database = Factory.get("Database")() database.cl_init(change_program="deactivate-qua") constants = Factory.get("Constants")(database) # we could probably generalise and use entity here, but for now we # need only look at accounts account = Factory.get("Account")(database) person = Factory.get("Person")(database) today = dt.today() account.find_by_name(cereconf.INITIAL_ACCOUNTNAME) operator_id = account.entity_id account.clear() def fetch_all_relevant_accounts(qua_type, since, ignore_affs, system_accounts): """Fetch all accounts that matches the criterias for deactivation. :param QuarantineCode qua_type: The quarantine that the accounts must have to be targeted. :param int since: The number of days a quarantine must have been active for the account
def parser(sentence): resultdict={'starttime':0,'endtime':0,'people':0,'building':0,'floor':0} message="null" starttime=0 endtime=0 people=0 building=0 floor=0 rsentence=preproccess(sentence) precise_time_list=get_regular_precise_time(sentence) if len(precise_time_list)==0: message= "Can not find 'specific time', nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." elif len(precise_time_list)==1: date_list=get_regular_date(rsentence) if len(date_list)==0: date=str(DateTime.today())#未提供日期时默认是今天 date=re.sub(r'\s.*', '', date) starttime=date+" "+precise_time_list[0] #print starttime starttime=time.mktime(time.strptime(starttime,"%Y-%m-%d %H:%M")) continue_time_list=get_regular_continued_time(sentence) if len(continue_time_list)==0: #message= "No duration found, how long the meeting lasts? I Booked an hour for you as default, please send me email if it is not correct." endtime=starttime+3600 elif len(continue_time_list)==1: endtime=starttime+continue_time_list[0] else: message= "More than one duration found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." resultdict['starttime']=starttime resultdict['endtime']=endtime elif len(date_list)==1: date=date_list[0] starttime=date+" "+precise_time_list[0] starttime=time.mktime(time.strptime(starttime,"%Y-%m-%d %H:%M")) continue_time_list=get_regular_continued_time(sentence) if len(continue_time_list)==0: #message= "No duration found, how long the meeting lasts? I Booked an hour for you as default, please send me email if it is not correct." endtime=starttime+3600 elif len(continue_time_list)==1: endtime=starttime+continue_time_list[0] else: message= "More than one duration found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." resultdict['starttime']=starttime resultdict['endtime']=endtime else: message= "More than one 'date' found, is there a cross-day query? Nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." elif len(precise_time_list)==2: date_list=get_regular_date(rsentence) if len(date_list)==0: date=str(DateTime.today())#未提供日期时默认是今天 date=re.sub(r'\s.*', '', date) time1=date+" "+precise_time_list[0] time2=date+" "+precise_time_list[1] time1=time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M")) time2=time.mktime(time.strptime(time2,"%Y-%m-%d %H:%M")) if time1>=time2: endtime=time1 starttime=time2 else: endtime=time2 starttime=time1 resultdict['starttime']=starttime resultdict['endtime']=endtime elif len(date_list)==1: date=date_list[0] time1=date+" "+precise_time_list[0] time2=date+" "+precise_time_list[1] time1=time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M")) time2=time.mktime(time.strptime(time2,"%Y-%m-%d %H:%M")) if time1>=time2: endtime=time1 starttime=time2 else: endtime=time2 starttime=time1 resultdict['starttime']=starttime resultdict['endtime']=endtime else: message= "More than one 'date' found, is there a cross-day query? Nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." else: message= "More than one 'specific time' found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people." #找楼号 building_list=get_building(sentence) if len(building_list)==0: building='NULL' elif len(building_list)==1: building=building_list[0] else: message= "More than one 'building number' found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people in building A on 7F." resultdict['building']=building #找人数 people_list=get_people(sentence) if len(people_list)==0: people='NULL' elif len(people_list)==1: people=people_list[0] else: message= "More than one 'number of participants' found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people in building A on 7F." resultdict['people']=people #找楼层 floor_list=get_floor(sentence) if len(floor_list)==0: floor='NULL' elif len(floor_list)==1: floor=floor_list[0] else: message= "More than one 'floor' found, nlp process can not be carried out, please try to follow the example sentence."+"\n"+"example sentence: I want to book a meeting room from 11am to 3pm for 5 people in building A on 7F." resultdict['floor']=floor return resultdict,message
def generate_revisi_target_realisasi_bulanan(self, cr, uid, ids, context=None): if context is None: context = {} task = {} member = {} target_pool = self.pool.get('project.project') member_pool = self.pool.get('project.user.rel') task_pool = self.pool.get('project.task') stage_pool = self.pool.get('project.task.type') for target_obj in self.browse(cr, uid, ids, context=context): task_ids = task_pool.search(cr, uid, [('project_id','=',target_obj.id),('work_state','in',('draft','realisasi','cancelled'))], context=None) task_pool.unlink(cr, uid, task_ids, context=None) task_exist_ids = task_pool.search(cr, uid, [('project_id','=',target_obj.id),('work_state','not in',('draft','realisasi','cancelled'))], context=None) #print "Target Name : ",target_obj.name target_category='bulanan' description=target_obj.name lama_kegiatan=target_obj.lama_kegiatan user_id = target_obj.user_id.id target_period_month='xx' date_start='xx' date_end='xx' company_id=None currency_id=None user_id_bkd=None employee = self.get_employee_from_user_id( cr, uid, target_obj); if user_id!=uid: raise osv.except_osv(_('Invalid Action!'), _('Anda Tidak Memiliki Priviledge Untuk Proses Ini.')) if not employee : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Ada Beberapa Informasi Kepegawaian Belum Diisi, Khususnya Data Pejabat Penilai Dan Atasan Banding.')) else : company = employee.company_id company_id = company.id currency_id= employee.company_id.currency_id #print "company_id : ",company_id,' - ',currency_id if not company_id : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Unit Dinas Pegawai Belum Dilengkapi.')) #print "employee parent : ",employee.parent_id if not target_obj.user_id_bkd: if not company.user_id_bkd : raise osv.except_osv(_('Invalid Action, Data Dinas Kurang Lengkap'), _('Staff Pemeriksa Dari BKD Tidak Tersedia Untuk Unit Anda, Silahkan hubungi Admin Atau isi Data Pemeriksa.')) else : user_id_bkd = company.user_id_bkd.id else : user_id_bkd=target_obj.user_id_bkd.id if not employee.user_id_atasan : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Penilai Belum Terisi.')) if not employee.user_id_banding : raise osv.except_osv(_('Invalid Action, Data Pegawai Tidak Lengkap'), _('Proses Tidak Dapat Dilanjutkan Karena Data Pejabat Pengajuan Banding.')) user_id_atasan =target_obj.user_id_atasan.id user_id_banding=target_obj.user_id_banding.id if not target_obj.user_id_atasan.id : user_id_atasan = employee.user_id_atasan.user_id.id if not target_obj.user_id_banding.id : user_id_banding = employee.user_id_banding.user_id.id color=1; if target_obj.target_type_id in ('dipa_apbn','dpa_opd_biro','sotk'): color=3; if target_obj.target_type_id in ('lain_lain'): color=4 if target_obj.target_type_id in ('tambahan'): color=5 if target_obj.target_type_id in ('perilaku'): color=6 task.update({ 'project_id':target_obj.id, 'user_id':user_id, 'company_id':company_id, 'description':description, 'name': target_obj.name, 'code': target_obj.code, 'target_category': target_category, 'sequnce': target_obj.priority, 'target_type_id':target_obj.target_type_id, 'target_period_year': target_obj.target_period_year, 'target_jumlah_kuantitas_output' : target_obj.target_jumlah_kuantitas_output, 'target_satuan_kuantitas_output' : target_obj.target_satuan_kuantitas_output.id or None, 'target_angka_kredit' : target_obj.target_angka_kredit, 'target_kualitas' : target_obj.target_kualitas, 'target_waktu' : target_obj.target_waktu, 'target_satuan_waktu' : 'hari', 'target_biaya' : target_obj.target_biaya, 'target_lainlain' : target_obj.target_lainlain, 'user_id_atasan': user_id_atasan or False, 'user_id_banding':user_id_banding or False, 'user_id_bkd':user_id_bkd or False, 'priority':'2', 'notes':'-', 'currency_id':currency_id, 'task_category':'skp', }) #Update Task Target Bulanan old_kualitas,old_biaya,old_ak = self.get_total_target_aspect_task(cr,uid,task_exist_ids,context=None) now=DateTime.today(); part_jumlah_kuantitas_output=0 part_angka_kredit=0 part_biaya=0 kuantitas=target_obj.target_jumlah_kuantitas_output - old_kualitas ang_kredit=target_obj.target_angka_kredit - old_ak biaya=target_obj.target_biaya - old_biaya part_lama_kegiatan = lama_kegiatan - len(task_exist_ids) x_kuantitas=kuantitas/part_lama_kegiatan y_kuantitas =kuantitas%part_lama_kegiatan x_kredit=ang_kredit/part_lama_kegiatan y_kredit =ang_kredit%part_lama_kegiatan x_biaya=biaya/part_lama_kegiatan y_biaya =biaya%part_lama_kegiatan first_task_id=None sum_of_balance_biaya=0 if target_obj.date_start : curr_date = DateTime.strptime(target_obj.date_start,'%Y-%m-%d') else : january=DateTime.Date(now.year,1,1) curr_date = DateTime.strptime(january.strftime('%Y-%m-%d'),'%Y-%m-%d') first_date =curr_date #print "THIS IS A DATE ",curr_date for i in range(0,lama_kegiatan): next_date = curr_date + DateTime.RelativeDateTime(months=i) target_period_month=next_date.strftime('%m') if self.is_exist_task_in_month(cr,uid,task_exist_ids,target_period_month,target_obj.target_period_year,context=None): #print "Break In Month %s %s",target_period_month,target_obj.target_period_year, continue; #Jumlah Kuantitas Output if kuantitas >0 : if i < y_kuantitas : part_jumlah_kuantitas_output=x_kuantitas+1 else : part_jumlah_kuantitas_output=x_kuantitas #angka Kredit #if ang_kredit >0 : # if i < y_kredit : # part_angka_kredit=x_kredit+1 # else : part_angka_kredit=x_kredit #Biaya if biaya >0 : part_biaya=round(x_biaya) sum_of_balance_biaya+=part_biaya task.update({ 'target_period_month':target_period_month, 'target_jumlah_kuantitas_output' : part_jumlah_kuantitas_output, 'target_waktu' : 20, 'target_angka_kredit' : part_angka_kredit, 'target_biaya' : part_biaya, }) date_start='xx' date_end='xx' stage_ids = stage_pool.search(cr,uid,[('sequence','=',0)], context=None) #print "stage_id : ",stage_ids work_state='draft'; if stage_ids : task.update({ 'stage_id': stage_ids[0], 'work_state':work_state, 'state':'draft', 'currency_id':currency_id }) if i == (lama_kegiatan-1) : balancing_biaya = biaya - sum_of_balance_biaya task.update({ 'target_biaya':balancing_biaya+part_biaya }) #task_pool.write(cr, uid, task_id,update_biaya) #insert task task_id = task_pool.create(cr, uid, task) # Update Realisasi Yang sudah selesai Dan inprogress exist_task_data = {} for task_exist_obj in task_pool.browse(cr, uid, task_exist_ids, context=context): exist_task_data.update({ 'project_id':target_obj.id, #'user_id':user_id, #'company_id':company_id, 'description':description, 'name': target_obj.name, 'code': target_obj.code, 'target_category': target_category, #'sequence': target_obj.priority, 'target_type_id':target_obj.target_type_id, #'target_period_year': target_obj.target_period_year, #'target_jumlah_kuantitas_output' : target_obj.target_jumlah_kuantitas_output, # 'target_satuan_kuantitas_output' : target_obj.target_satuan_kuantitas_output.id or None, # 'target_angka_kredit' : target_obj.target_angka_kredit, # 'target_kualitas' : target_obj.target_kualitas, # 'target_waktu' : target_obj.target_waktu, # 'target_satuan_waktu' : 'hari', # 'target_biaya' : target_obj.target_biaya, # 'target_lainlain' : target_obj.target_lainlain, 'user_id_atasan': user_id_atasan or False, 'user_id_banding':user_id_banding or False, 'user_id_bkd':user_id_bkd or False, 'priority':'2', #'notes':'-', #'currency_id':currency_id, 'task_category':'skp', }) task_pool.write(cr,uid,task_exist_obj.id,exist_task_data) #Update Status Target Bulanan update_target = { 'status_target_bulanan':'sudah', 'color':color, 'user_id_atasan': user_id_atasan or False, 'user_id_banding':user_id_banding or False, 'user_id_bkd':user_id_bkd or False, 'date_start':first_date or False } target_pool.write(cr,uid,target_obj.id,update_target) return { 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'notification.generate.task', 'target': 'new', 'context': context,#['notif_booking'], }
from todolist_sub import TASKSub as TASK #attempt to match todolist.exe new file behavior #New TODOLIST newTodolist = TODOLIST() #newTodolist.set_CATEGORY #newTodolist.set_STATUS #newTodolist.set_PERSON #newTodolist.set_ALLOCATEDBY #newTodolist.set_VERSION newTodolist.set_FILEVERSION(1) newTodolist.set_PROJECTNAME('') #newTodolist.set_FILENAME #newTodolist.set_CUSTOMCOMMENTSTYPE td = DateTime.today() newTodolist.set_LASTMODIFIED(td.strftime('%m/%d/%Y')) newTodolist.set_EARLIESTDUEDATE('0.0000000') newTodolist.set_NEXTUNIQUEID(1) newTodolist.set_FILEFORMAT(9) #New TASK newTask = TASK() newTask.set_TITLE('Sample Task') newTodolist.add_TASK(newTask) fileOut = open('new.tdl', 'w') newTodolist.export(fileOut, 1, '') fileOut.close()