def _get(self, _id=None, entity=None): if _id: command = '%s.find_one({"_id":ObjectId("%s")})' % (self._mongocollection, str(_id)) if DBDEBUG: Logger.log_to_file(command) entity = eval(command) if entity: self._hydrate(entity)
def save(self): if self._id: command = '%s.save(%s)' % (self._mongocollection, str(self._get_hash())) if DBDEBUG: Logger.log_to_file(command) eval(command) else: command = '%s.insert(%s)' % (self._mongocollection, str(self._get_hash())) if DBDEBUG: Logger.log_to_file(command) self._id = eval(command)
def test_log(mock_now): """Testa se uma nova mensagem foi adicionada à lista de mensagens do objeto da classe Logger""" test_now = 123 test_message = 'A test message' mock_now.now.return_value = test_now log = Logger() log.log(test_message) assert log.messages == [(test_now, test_message)]
def index(): Logger.log_to_file(bottle.request.session.userId) collections = EntityManager(_DBCON).get_all(Collection , filter_criteria={'userId':bottle.request.session.userId} ,sort_by=[('lowercasename', 1)] ) output = [] for c in collections: output.append( c.get_json_safe() ) return json.dumps(output)
def send(self, subject, body): msg = MIMEText(body, 'html') msg['Subject'] = subject msg['From'] = self.sender msg['To'] = self.recipient try: s = smtplib.SMTP(self.host) if settings.EMAILUSERNAME and settings.EMAILPASSWORD: s.login(settings.EMAILUSERNAME, settings.EMAILPASSWORD) s.sendmail(self.sender, self.recipient, msg.as_string()) except: Logger.log_to_file(msg.as_string())
def send(self, subject, body): msg = MIMEText(body, "html") msg["Subject"] = subject msg["From"] = self.sender msg["To"] = self.recipient try: s = smtplib.SMTP(self.host) if settings.EMAILUSERNAME and settings.EMAILPASSWORD: s.login(settings.EMAILUSERNAME, settings.EMAILPASSWORD) s.sendmail(self.sender, self.recipient, msg.as_string()) except: Logger.log_to_file(msg.as_string())
def delete_one(self, entity, _id): """ Deletes a single entity from the datastore based on the id given entity should be a string _id should be the string entity id e.g. todoId = '5047b7bb37d5e64e9a4b1c74' EntityManager(_DBCON).delete_one('Todo', todoId) """ command = 'self.db.%s.remove({"_id":ObjectId("%s")})' % (entity, str(_id)) if DBDEBUG: Logger.log_to_file(command) eval(command)
def _get(self, _id): command = '%s.find_one({"_id":ObjectId("%s")})' % ( self._mongocollection, str(_id)) if DBDEBUG: Logger.log_to_file(command) entity = eval(command) if entity: setattr(self, '_id', entity.get('_id')) for f, val in self._fields: fieldtype = type(getattr(self, f)) fieldvalue = entity.get(f) if fieldtype == list: fieldlist = [] for el in fieldvalue: if type(el) == dict and el.has_key('__instanceOf__'): command = '%s(self.db, ObjectId("%s"))' % ( self._unicode_to_class( el['__instanceOf__']), el['_id']) if DBDEBUG: Logger.log_to_file(command) el = eval(command) fieldlist.append(el) fieldvalue = fieldlist elif type(fieldvalue) == dict and fieldvalue.has_key( '__instanceOf__'): command = '%s(self.db, ObjectId("%s"))' % ( self._unicode_to_class( fieldvalue['__instanceOf__']), fieldvalue['_id']) if DBDEBUG: Logger.log_to_file(command) fieldvalue = eval(command) setattr(self, f, fieldvalue)
def unit_head_workloads(weather_factors, unit_factors, iterations, workload_steps=20): all_logged_info = [{'WORKLOAD': i / workload_steps} for i in range(workload_steps)] for i in range(iterations): for workload_iteration in range(workload_steps): env = simpy.Environment() weather = Weather(env=env, **weather_factors) Logger._reset() #Logger.LOG = False units = [] for factors in unit_factors: factors['head_workload'] = workload_iteration / float(workload_steps) units.append(factories.build_unit(env, weather, factors)) _ = Madden(env, weather, 2, [unit[0] for unit in units]) env.run(until=24) this = all_logged_info[workload_iteration] gruntled = Review.get_disgruntled_employees() for head_id, num in gruntled.items(): this["LATE MESSAGES"] = this.get("LATE MESSAGES", 0) + num print i return all_logged_info
def weather_differences(weather_factors, unit_factors, iterations, start, finish): assert start >= 3 assert finish <= 25 all_logged_info = [{'TIME': i} for i in range(finish - start)] for iteration in range(iterations): for i in range(start, finish): env = simpy.Environment() weather_factors['time'] = i weather = Weather(env=env, **weather_factors) Logger._reset() Logger.LOG = False units = [] for factors in unit_factors: units.append(factories.build_unit(env, weather, factors)) _ = Madden(env, weather, 2, [unit[0] for unit in units]) env.run(until=24) this = all_logged_info[i - start] for status, num in Review.get_statuses()['home'].items(): this[status] = this.get(status, 0) + num return all_logged_info
def _hydrate(self, entity): setattr(self, '_id', entity.get('_id')) for f, val in self._fields: fieldtype = type(getattr(self, f)) fieldvalue = entity.get(f) if fieldtype == list: fieldlist = [] for el in fieldvalue: if type(el)==dict and el.has_key('__instanceOf__'): command = '%s(self.db, ObjectId("%s"))' % (self._unicode_to_class(el['__instanceOf__']) , el['_id']) if DBDEBUG: Logger.log_to_file(command) el = eval(command) fieldlist.append(el) fieldvalue = fieldlist elif type(fieldvalue)==dict and fieldvalue.has_key('__instanceOf__'): command = '%s(self.db, ObjectId("%s"))' % (self._unicode_to_class(fieldvalue['__instanceOf__']) , fieldvalue['_id']) if DBDEBUG: Logger.log_to_file(command) fieldvalue = eval(command) setattr(self, f, fieldvalue)
def _get(self, _id): command = '%s.find_one({"_id":ObjectId("%s")})' % (self._mongocollection, str(_id)) if DBDEBUG: Logger.log_to_file(command) entity = eval(command) if entity: setattr(self, "_id", entity.get("_id")) for f, val in self._fields: fieldtype = type(getattr(self, f)) fieldvalue = entity.get(f) if fieldtype == list: fieldlist = [] for el in fieldvalue: if type(el) == dict and el.has_key("__instanceOf__"): command = '%s(self.db, ObjectId("%s"))' % ( self._unicode_to_class(el["__instanceOf__"]), el["_id"], ) if DBDEBUG: Logger.log_to_file(command) el = eval(command) fieldlist.append(el) fieldvalue = fieldlist elif type(fieldvalue) == dict and fieldvalue.has_key("__instanceOf__"): command = '%s(self.db, ObjectId("%s"))' % ( self._unicode_to_class(fieldvalue["__instanceOf__"]), fieldvalue["_id"], ) if DBDEBUG: Logger.log_to_file(command) fieldvalue = eval(command) setattr(self, f, fieldvalue)
ind_permute = np.arange(0, 28) np.random.seed(0) np.random.shuffle(ind_permute) np.save("permuteB.npy", ind_permute) # Load the previous FIM fishers_cpu = torch.load("fisherA.pth") fishers = [] for fisher in fishers_cpu: fishers.append(fisher.to(model.device)) # Create callbacks checkpoint = CheckPoint(model, "modelB.ckpt") earlystop = EarlyStopping(**earlystop_params) list_metrics = ["loss_trainB", "loss_testB", "acc_testA", "acc_testB"] logger = Logger(list_metrics=list_metrics, logger_file="log-metrics.npy") # Train and evaluate flg_stop = False for epoch in range(1, params["n_epochs"] + 1): print("\n[EPOCH %d]" % (epoch)) loss_trainB = train_ewc(model, trainB_loader, optimizer, base_loss_fn, params["lamda"], fishers, prev_opt_thetas, epoch, description="Train on task B") print()
def get_all(self, entity, filter_criteria='', sort_by=[], skip=None, limit=None, count=False): """ Get all or a selection of entities from the datastore. This returns a list of entities. Entity should be class object filter_criteria can be used to filter the results and should be a dictionary that adheres to the pymongo documentation http://api.mongodb.org/python/current/genindex.html {'name':'jim'} sort_by should be a list of tuples (attribute, direction) [ ('name',1), ('age',1), ] skip and limit are both ints and are used for pagination count should be True if only a count of the results is required e.g. todos = EntityManager(_DBCON).get_all(Todo ,filter_criteria={'userId':bottle.request.session.userid} ,sort_by=[('added', 1)] ,skip=20 ,limit=10 ) """ extraCriteria = '' if len(sort_by)>0: extraCriteria += '.sort(%s)' % str(sort_by) if skip: extraCriteria += '.skip(%s)' % str(skip) if limit: extraCriteria += '.limit(%s)' % str(limit) if count: extraCriteria += '.count()' command = 'self.db.%s.find(%s)%s' % (entity.__name__ ,str(filter_criteria) , extraCriteria ) if DBDEBUG: Logger.log_to_file(command) if count: return eval(command) else: entities = [] for result in eval(command): e = entity(self.db) setattr(e, '_id', result.get('_id')) for f, val in e.fields: setattr(e, f, result.get(f)) entities.append(e) return entities
def test_init(): """Testa se a classe Logger é instanciado corretamente.""" log = Logger() assert log.messages == []