def settings_button(self, bot, update): query = update.callback_query self.logger.info(query) user_id = query.message.chat_id user_settings = self.user_settings.get(user_id, {}) settings = user_settings.get('route_settings', []) key = query.data if key == 'all': settings = list(self.cds.bus_routes.keys()) elif key == 'none': settings = [] elif key == 'hide': routes = ' '.join(settings) if settings else 'все доступные' bot.edit_message_text( text=f"Текущие маршруты для вывода: {routes}", chat_id=query.message.chat_id, message_id=query.message.message_id) return else: if key in settings: settings.remove(key) else: settings.append(key) user_settings['route_settings'] = settings self.user_settings[user_id] = user_settings keyboard = self.get_buttons_routes(settings) reply_markup = InlineKeyboardMarkup(keyboard) routes = ' '.join(settings) if settings else 'все доступные' bot.edit_message_text(text=f"Текущие маршруты для вывода: {routes}", chat_id=query.message.chat_id, message_id=query.message.message_id, reply_markup=reply_markup)
def listeners(bot, trigger): """ Viser antall lyttere på alle streamene våre. /revolt er nettstreamen /revolt_dab er streamen dedikert til SBS (den skal være 1, dersom den er 0 er vi av DAB) Alle andre er ikke så mye å bry seg om. """ streamer = IcecastServer(s.ICECAST_NAME, s.ICECAST_URL, s.ICECAST_PORT, s.ICECAST_USERNAME, s.ICECAST_PASSWORD) s = list() for mount in streamer.Mounts: s.append(mount.Name + ': ' + str(len(mount.Listeners))) bot.say(' '.join(s))
def sobel(x, y, hm, sobelscale): s = [] for ny in range(1, -2, -1): for nx in range(-1, 2): value = hm.getpixel((x + nx, y + ny)) s.append(value) # if value != -2147483648: # else: # samples.append(hm.getpixel) normal = vmath.Vector3(0, 0, 0) scale = sobelscale normal.x = scale * -(s[2] - s[0] + 2 * (s[5] - s[3]) + s[8] - s[6]) normal.y = scale * -(s[6] - s[0] + 2 * (s[7] - s[1]) + s[8] - s[2]) normal.z = 1 normal.normalize() normal.x = normal.x * 0.5 + 0.5 normal.y = normal.y * 0.5 + 0.5 normal.z = normal.z + 0.5 return normal
def evaluate(j, e, method, scores, data_loader, logdir, reference_point, split, result_dict): assert split in ['train', 'val', 'test'] global volume_max global epoch_max score_values = np.array([]) for batch in data_loader: batch = utils.dict_to_cuda(batch) # more than one solution for some solvers s = [] for l in method.eval_step(batch): batch.update(l) s.append([s(**batch) for s in scores]) if score_values.size == 0: score_values = np.array(s) else: score_values += np.array(s) score_values /= len(data_loader) hv = HyperVolume(reference_point) # Computing hyper-volume for many objectives is expensive volume = hv.compute(score_values) if score_values.shape[1] < 5 else -1 if len(scores) == 2: pareto_front = utils.ParetoFront( [s.__class__.__name__ for s in scores], logdir, "{}_{:03d}".format(split, e)) pareto_front.append(score_values) pareto_front.plot() result = { "scores": score_values.tolist(), "hv": volume, } if split == 'val': if volume > volume_max: volume_max = volume epoch_max = e result.update({ "max_epoch_so_far": epoch_max, "max_volume_so_far": volume_max, "training_time_so_far": elapsed_time, }) elif split == 'test': result.update({ "training_time_so_far": elapsed_time, }) result.update(method.log()) if f"epoch_{e}" in result_dict[f"start_{j}"]: result_dict[f"start_{j}"][f"epoch_{e}"].update(result) else: result_dict[f"start_{j}"][f"epoch_{e}"] = result with open(pathlib.Path(logdir) / f"{split}_results.json", "w") as file: json.dump(result_dict, file) return result_dict
def merge_iter(new, old, allcaps=True, doubleunderscore=False, verbose=2, overwrite=True, depth=100): """ Merge two namespaces or dictionaries, optionally ignoring non-ALL-CAPS names Duplicate keys (variable/atribute names) are recursively merged to deal with nested dictionaries (dict of dict of dict ...) Lists are appended/extended. TODO: mimic the Yii associative array merge function, including specification of prefixes and suffixes to skip """ import types import copy scalar_type = ( str, float, int, bool, types.MethodType ) # TODO: what about types.ClassType or types.ObjectType or types.StringTypes iterable_type = (list, tuple, set) if isinstance(old, types.ModuleType) or isinstance(new, types.ModuleType): print 'aborting merge of 2 modules' return old elif isinstance(old, dict) and isinstance(new, dict): if verbose >= 2: print 'merging two dicts' for k, v in new.items(): if verbose >= 2: print 'merging key %s' % repr(k) # problem with this is that when inside a dict we WANT to merge non-allcaps stuff if (not allcaps or k == k.upper()) and ( doubleunderscore or not (k.startswith('__') and k.endswith('__'))): if k in old: if depth > 0: old[k] = merge_iter(new[k], old[k], allcaps, doubleunderscore, verbose=verbose, overwrite=overwrite, depth=depth) elif overwrite: old[k] = copy.deepcopy(new[k]) else: # FIXME: deepcopy faults on objects with unsafe attributes like __new__! old[k] = copy.deepcopy( new[k] ) # deepcopy in case the element is an object/dict, elif verbose >= 2: print 'key value ignored because it looks like a protected or non-user object' # don't do anythin with double underscore or mixed-case variables if not flagged to merge them # merge lists by unioning -- don't add duplicates elif isinstance(old, list) and isinstance( new, iterable_type): # and not isinstance( new, (str,unicode)): if isinstance(new, tuple): print 'merging a tuple into a list. list =' + repr(old) #TODO: convert to sets, append, then convert back to list? for i, v in enumerate(new): if verbose >= 2: print 'merging list item', i # FIXME: the exact same object instance (e.g. dict) might not exist in the old # but you still want to merge dicts rather than append a new dict if not v in old: if verbose >= 2: print 'appending list item', i old.append(v) if isinstance(new, tuple): print 'merged tuple into a list. list =' + repr(old) elif isinstance(old, tuple) and isinstance( new, iterable_type): # and not isinstance( new, (str,unicode)): #TODO: convert to sets, append, then convert back to list? print 'old tuple' + repr(old) for i, v in enumerate(new): if verbose >= 2: print 'merging tuple item', i # ,' value '+repr(v) # FIXME: the exact same object instance (e.g. dict) might not exist in the old # but you still want to merge dicts rather than append a new dict #print type(new) if not v in old: if verbose >= 2: print 'appending the value' tmp = old + ( v, ) # WARN: tuple(v) would turn a str into a tuple of chars old = tmp print 'new tuple' + repr(old) # TODO: 4 DRY-up oportunities below elif isinstance(old, tuple) and isinstance( new, scalar_type ): # even though strings are a tuple of characters this shouldn't mess up if verbose >= 2: print 'appending a scalar ' + repr(v) + ' to a tuple' #TODO: convert to sets, append, then convert back to list? tmp = old + ( new, ) # WARN: don't use tuple(new) because converts str to a tuple of chars, but parentheses (with comma) do not old = tmp elif isinstance(old, list) and isinstance(new, scalar_type): if verbose >= 2: print 'appending a scalar to a list' #TODO: convert to sets, append, then convert back to list? old.append(new) elif isinstance(old, set) and isinstance(new, scalar_type): if verbose >= 2: print 'adding a scalar to a set' #TODO: convert to sets, append, then convert back to list? old.add(new) elif isinstance(old, scalar_type) and isinstance(new, scalar_type): if verbose >= 2: print 'replacing value ' + repr(old) + ' with value ' + repr(new) old = new # TODO: is it OK to change the old type in addition to its value? # FIXME: mismatched schemas (new and old elements not the same type and structure) may result in no change #print 'returning value '+repr(old) return old
def merge_iter( new, old, allcaps=True, doubleunderscore=False, verbose=2, overwrite=True, depth=100): """ Merge two namespaces or dictionaries, optionally ignoring non-ALL-CAPS names Duplicate keys (variable/atribute names) are recursively merged to deal with nested dictionaries (dict of dict of dict ...) Lists are appended/extended. TODO: mimic the Yii associative array merge function, including specification of prefixes and suffixes to skip """ import types,copy scalar_type = (str, float, int, bool, types.MethodType) # TODO: what about types.ClassType or types.ObjectType or types.StringTypes iterable_type = (list,tuple,set) if isinstance( old, types.ModuleType ) or isinstance( new, types.ModuleType ): print 'aborting merge of 2 modules' return old elif isinstance( old, dict ) and isinstance( new, dict ): if verbose>=2: print 'merging two dicts' for k,v in new.items(): if verbose>=2: print 'merging key ',k # problem with this is that when inside a dict we WANT to merge non-allcaps stuff if (not allcaps or k==k.upper()) and ( doubleunderscore or not ( k.startswith('__') and k.endswith('__') )): if k in old: if depth>0: old[k] = merge_iter( new[k], old[k], allcaps, doubleunderscore, verbose=verbose, overwrite=overwrite, depth=depth) elif overwrite: old[k] = copy.deepcopy(new[k]) else: # FIXME: deepcopy faults on objects with unsafe attributes like __new__! old[k] = copy.deepcopy(new[k]) # deepcopy in case the element is an object/dict, elif verbose>=2: print 'key value ignored because it looks like a protected or non-user object' # don't do anythin with double underscore or mixed-case variables if not flagged to merge them # merge lists by unioning -- don't add duplicates elif isinstance( old, list ) and isinstance( new, iterable_type ): # and not isinstance( new, (str,unicode)): if isinstance(new,tuple): print 'merging a tuple into a list. list ='+repr(old) #TODO: convert to sets, append, then convert back to list? for i,v in enumerate(new): if verbose>=2: print 'merging list item',i # FIXME: the exact same object instance (e.g. dict) might not exist in the old # but you still want to merge dicts rather than append a new dict if not v in old: if verbose>=2: print 'appending list item',i old.append(v) if isinstance(new,tuple): print 'merged tuple into a list. list ='+repr(old) elif isinstance( old, tuple ) and isinstance( new, iterable_type ): # and not isinstance( new, (str,unicode)): #TODO: convert to sets, append, then convert back to list? print 'old tuple'+repr(old) for i,v in enumerate(new): if verbose>=2: print 'merging tuple item',i #,' value '+repr(v) # FIXME: the exact same object instance (e.g. dict) might not exist in the old # but you still want to merge dicts rather than append a new dict #print type(new) if not v in old: if verbose>=2: print 'appending the value' tmp = old + (v,) # WARN: tuple(v) would turn a str into a tuple of chars old = tmp print 'new tuple'+repr(old) # TODO: 4 DRY-up oportunities below elif isinstance( old, tuple) and isinstance( new, scalar_type ): # even though strings are a tuple of characters this shouldn't mess up if verbose>=2: print 'appending a scalar '+repr(v)+' to a tuple' #TODO: convert to sets, append, then convert back to list? tmp = old + (new,) # WARN: don't use tuple(new) because converts str to a tuple of chars, but parentheses (with comma) do not old = tmp elif isinstance( old, list ) and isinstance( new, scalar_type ): if verbose>=2: print 'appending a scalar to a list' #TODO: convert to sets, append, then convert back to list? old.append(new) elif isinstance( old, set ) and isinstance( new, scalar_type ): if verbose>=2: print 'adding a scalar to a set' #TODO: convert to sets, append, then convert back to list? old.add(new) elif isinstance( old, scalar_type ) and isinstance( new, scalar_type ): if verbose>=2: print 'replacing value '+repr(old)+' with value ' +repr(new) old = new # TODO: is it OK to change the old type in addition to its value? # FIXME: mismatched schemas (new and old elements not the same type and structure) may result in no change #print 'returning value '+repr(old) return old