def set_configurations(cls): cfgs = dict() if not os.path.exists(ConfigManager.CONFIG_PATH): ConfigManager.LOGGER.error("Configuration file not found...") ConfigManager.LOGGER.info( "Generating default configuration file...") ConfigManager.generate_default_configuration() with open(ConfigManager.CONFIG_PATH, 'r') as json_cfg: cfg = json.load(json_cfg) # LOADING CONFIGURATIONS # TRY to find custom settings try: ConfigManager.LOGGER.info( "Loading custom configuration settings...") cfgs["screen"] = [ cfg["CUSTOM"]["SIZE"]["WIDTH"], cfg["CUSTOM"]["SIZE"]["HEIGHT"] ] cfgs["lang"] = cfg["CUSTOM"]["LANGUAGE"] cfgs["theme"] = cfg["CUSTOM"]["THEME"] except KeyError as ex: ConfigManager.LOGGER.error("Custom configurations not found") ConfigManager.LOGGER.info("Loading default configurations...") cfgs["screen"] = [ cfg["DEFAULT"]["SIZE"]["WIDTH"], cfg["DEFAULT"]["SIZE"]["HEIGHT"] ] cfgs["lang"] = cfg["DEFAULT"]["LANGUAGE"] cfgs["theme"] = cfg["DEFAULT"]["THEME"] DisplaySettings.set_size_by_key( DisplaySettings.get_size_name(cfgs.get("screen"))) StringUtils.set_language(cfgs.get("lang")) # LANGUAGE Themes.set_theme(cfgs.get("theme")) # THEME
def find(self, str_val, max_results): """ Tries to find all occurrences of the template in the provided string. Stops after the maximum number of results is reached. """ str_val = str_val.strip() results = list() for matcher in self._pattern.finditer(str_val): if not StringUtils.is_delimited(str_val, matcher.start(), matcher.end()): continue match_result = MatchResult(matcher.start(), matcher.end()) for slot_key in self._slots.keys(): filled_value = matcher.group(self._slots[slot_key]).strip() # quick-fix to handle some rare cases where the occurrence found # by the regex leads to unbalanced parentheses or brackets. # TODO: check whether this is a bug or not. if not StringUtils.check_form(filled_value) and self.permutate_pattern(): return self.find(str_val, max_results) match_result.add_pair(slot_key, filled_value) results.append(match_result) if len(results) >= max_results: break return results
def check_form_events(self, event): super().check_form_events(event) if event.type == MOUSEBUTTONUP: if event.button != 4 and event.button != 5: pos = pg.mouse.get_pos() self.check_menu_pressed(pos) if self.btn_drop_down.collidepoint(pos) == 1: self.__logger.debug("DROP DOWN PRESSED") if self.__is_drop_down_pressed: self.__is_drop_down_pressed = False else: self.__is_drop_down_pressed = True self.__lang_counter = 0 elif self.btn_apply.get_rect().collidepoint(pos) == 1: for i in range(0, len(StringUtils.LANGUAGES), 1): if self.__lang == StringUtils.LANGUAGES[i][1]: StringUtils.set_language( StringUtils.LANGUAGES[i][0]) else: self.__is_drop_down_pressed = False elif event.type == MOUSEBUTTONDOWN: if self.__is_drop_down_pressed: if event.button == 4: self.__lang_counter -= 1 elif event.button == 5 and len(StringUtils.LANGUAGES) > 3: self.__lang_counter += 1 if self.__lang_counter < 0: self.__lang_counter = 0 elif (len(StringUtils.LANGUAGES) > 3) and ( self.__lang_counter > len(StringUtils.LANGUAGES) - 3): self.__lang_counter = (len(StringUtils.LANGUAGES) - 3)
def get_data(self): data = super().get_data() data[1] = StringUtils.get_string("ID_ATTRIBUTE") data[2] = StringUtils.get_string( AttributeBlueprint.DATA_TYPE.get( self.get_blueprint().get_data_type())) data[3] = self.get_blueprint().get_value() return data
def to_string(cls, style): s = "" if style == Themes.DARK_KNIGHT: s = StringUtils.get_string("ID_DARK_KNIGHT") elif style == Themes.DAY_LIGHT: s = StringUtils.get_string("ID_DAY_LIGHT") elif style == Themes.PRINCESS: s = StringUtils.get_string("ID_PRINCESS") return s
def draw_attribute_data(self, data, pos, font, banner, margin): self.blit(font, "{}:".format(StringUtils.get_string("ID_DATA_TYPE")), data.get(2), (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1 + pos * margin))) pos += 1 self.blit(font, "{}:".format(StringUtils.get_string("ID_VALUE")), str(data.get(3)), (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1 + pos * margin)))
def insert(self, sku): query = '''INSERT INTO sku_management (sku, name, link, min_price, max_price, compete_price, special_price, state, repeat_time, created_at, updated_at) VALUES ('{}', '{}', '{}', {}, {}, {}, {}, {}, {}, {}, 0)'''.format( StringUtils.toString(sku['sku']), StringUtils.toString(sku['name']), StringUtils.toString(sku['link']), sku['min_price'], sku['max_price'], sku['compete_price'], sku['special_price'], sku['state'], sku['repeat_time'], sku['created_at']) DatabaseHelper.execute(query)
def display_data(self, banner): if self.__bp is not None and self.__bp.focused: dt = self.__bp.get_data() pos = 2 font = pg.font.Font(Themes.DEFAULT_THEME.get("text_font_style"), int(self.get_rect().width * .05)) margin = int(font.size("SOME_TEXT")[1] * .35) + font.size( dt.get(1))[1] # DRAW GENERIC BLUEPRINT DATA self.blit(font, "{}:".format(StringUtils.get_string("ID_NAME")), dt.get(0), (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1))) self.blit(font, "{}:".format(StringUtils.get_string("ID_TYPE")), dt.get(1), (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1 + margin))) if self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "ATTRIBUTE"): # ATTRIBUTE RELATED INFORMATION self.draw_attribute_data(dt, pos, font, banner, margin) elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "FUNCTION"): # FUNCTION RELATED INFORMATION self.draw_function_data(dt, pos, font, banner, margin) elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "CHARACTER"): # CHARACTER RELATED INFORMATION self.draw_character_data(dt, pos, font, banner, margin) elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "SPRITE"): # SPRITE RELATED INFORMATION self.draw_sprite_data(dt, pos, font, banner, margin) self.ta_populated = True if self.boarder_rect is not None: pg.draw.rect(self.display, Themes.DEFAULT_THEME.get("selection_boarder"), self.boarder_rect, 2) # DRAW ACTION RELATED WIDGETS if self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "ATTRIBUTE"): # DATA TYPE DROP DOWN if self.__bp.data_type_pressed[0]: self.draw_attribute_data_type_selection() elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "FUNCTION"): pass elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "SPRITE"): pass elif self.__bp.get_blueprint().get_type() == Blueprint.TYPES.get( "CHARACTER"): if self.__bp.state_pressed[0]: self.draw_character_state_selection()
def insert(self, user): query = '''INSERT INTO t_user (user_name, password, token, lazada_user_name, lazada_user_id, lazada_api_key, created_at, updated_at, role, certain_size) VALUES ('{}', '{}', 'temptoken', '{}', '{}', '{}', '{}', 0, '{}', '{}')'''.format( StringUtils.toString(user['username']), StringUtils.toString(user['password']), StringUtils.toString(user['lazada_user_name']), StringUtils.toString(user['lazada_user_id']), StringUtils.toString(user['lazada_api_key']), user['created_at'], user['role'], user['certain_size']) DatabaseHelper.execute(query)
def test_to_bytes(self): """Test to_str Args: self: TestStringUtils Returns: None Raises: None """ self.assertEqual(b'test', StringUtils.to_bytes(b'test')) self.assertEqual(b'test', StringUtils.to_bytes('test'))
def create_entity(table_name, column_info_list): cls_name = StringUtils.to_camel(table_name) + "Entity" env = Environment(loader=FileSystemLoader('./template/', encoding='utf8')) tpl = env.get_template('entity.template') with open("./output/entity/" + cls_name + '.cs', 'wt', encoding='utf-8') as fout: columns = [] for column_info in column_info_list: columns.append({ 'field': StringUtils.to_camel(column_info[0]), 'type': convert_from_sqlite_to_c(column_info[1]) }) out_text = tpl.render({'entity_cls': cls_name, 'columns': columns}) fout.write(out_text)
def insert(self, sku, user): query = '''INSERT INTO price_by_time(sku, name, link, price_by_time, special_price, user_id) VALUES ('{}', '{}', '{}', '{}', '{}', '{}')'''.format( StringUtils.toString(sku['sku']), StringUtils.toString(sku['name']), StringUtils.toString(sku['link']), sku['price_by_time'], sku['special_price'], user['id']) try: DatabaseHelper.execute(query) return ExceptionUtils.success() except Exception as ex: return ExceptionUtils.error( '''User: {}-{}, Insert price by time exception: {}'''.format( user['username'], user['id'], str(ex)))
def draw_sprite_data(self, data, pos, font, banner, margin): s = pos = pos + 1 if len(self.__bp.get_blueprint().attributes) > 0: self.blit(font, "{}".format(StringUtils.get_string("ID_ATTRIBUTES")), None, (int(self.get_rect().left + self.get_rect().width * .08), int(banner.bottom * 1.1 + pos * margin))) pos += 1 for bp in self.__bp.get_blueprint().attributes: if isinstance(bp, AB): self.blit(font, "{} :: {}".format(bp.get_data_type(), bp.get_value()), None, (int(self.get_rect().left + self.get_rect().width * .12), int(banner.bottom * 1.1 + pos * margin)), header=False) pos += 1 r = pg.Rect( (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1 + s * margin)), (int(self.get_rect().width * .90), int((pos - s) * margin))) pg.draw.rect(self.display, Themes.DEFAULT_THEME.get("selection_boarder"), r, 1) s = pos = pos + 1 if len(self.__bp.get_blueprint().functions) > 0: self.blit(font, "{}".format(StringUtils.get_string("ID_FUNCTIONS")), None, (int(self.get_rect().left + self.get_rect().width * .08), int(banner.bottom * 1.1 + pos * margin))) pos += 1 for bp in self.__bp.get_blueprint().functions: if isinstance(bp, FB): self.blit(font, "{}()".format(bp.name), None, (int(self.get_rect().left + self.get_rect().width * .12), int(banner.bottom * 1.1 + pos * margin)), header=False) pos += 1 r = pg.Rect( (int(self.get_rect().left + self.get_rect().width * .05), int(banner.bottom * 1.1 + s * margin)), (int(self.get_rect().width * .90), int((pos - s) * margin))) pg.draw.rect(self.display, Themes.DEFAULT_THEME.get("selection_boarder"), r, 1)
def checkTokenArgument(self, argument): if (not argument): return False if not 'token' in argument: return False token = argument.get('token') return not StringUtils.isEmpty(token)
def perform_turn(self, system_action): """ Performs the dialogue turn in the simulator. :param system_action: the last system action. """ with self._lock: turn_performed = False self.simulator_state.set_parameters(self.domain.get_parameters()) system_assign = Assignment(self.system.get_settings().system_output, system_action) self.simulator_state.add_to_state(system_assign) while len(self.simulator_state.get_new_variables()) > 0: to_process = self.simulator_state.get_new_variables() self.simulator_state.reduce() for model in self.domain.get_models(): if model.is_triggered(self.simulator_state, to_process): change = model.trigger(self.simulator_state) if change and model.is_blocking(): break if len(self.simulator_state.get_utility_node_ids()) > 0: reward = self.simulator_state.query_util() comment = 'Reward: ' + StringUtils.get_short_form(reward) self.system.display_comment(comment) self.system.get_state().add_evidence(Assignment('R(' + system_assign.add_primes() + ')', reward)) self.simulator_state.remove_nodes(self.simulator_state.get_utility_node_ids()) if self.add_new_observations(): turn_performed = True self.simulator_state.add_evidence(self.simulator_state.get_sample()) return turn_performed
def fill_slots(self, assignment): """ Fills the slots of the template, and returns the result of the function evaluation. If the function is not a simple arithmetic expression, """ filled = super(ArithmeticTemplate, self).fill_slots(assignment) if '{' in filled: return filled if ArithmeticTemplate.is_arithmetic_expression(filled): try: return StringUtils.get_short_form( MathExpression(filled).evaluate()) # TODO: need to check exception handling except Exception as e: self.log.warning("cannot evaluate " + filled) return filled # handling expressions that manipulate sets # (using + and - to respectively add/remove elements) merge = ValueFactory.none() for str_val in filled.split("+"): negations = str_val.split("-") merge = merge.concatenate(ValueFactory.create(negations[0])) for negation in negations[1:]: values = merge.get_sub_values() old_value = ValueFactory.create(negation) if old_value in values: values.remove(ValueFactory.create(negation)) merge = ValueFactory.create(values) return str(merge)
def is_arithmetic_expression(exp): """ Returns true if the string corresponds to an arithmetic expression, and false otherwise :param exp: the string to check :return: true if the string is an arithmetic expression, false otherwise """ is_arithmetic_expression = False cur_str = '' for char_val in exp: if char_val == '+' or char_val == '-' or char_val == '/' or ( char_val == '*' and len(exp) > 2): is_arithmetic_expression = True if char_val == '?' or char_val == '|' or char_val == '[' or char_val == '_' or char_val == "'": return False if char_val.isalpha(): cur_str += char_val continue if StringUtils.is_delimiter(char_val): if cur_str not in MathExpression.fixed_functions: return False is_arithmetic_expression = True cur_str = '' return is_arithmetic_expression
class GameApi(Utils): APIS = [["CAR_SIMULATOR_API", StringUtils.get_string("ID_CAR_SIMULATOR")]] DEFAULT_API = None @staticmethod def get_api(id): return GameApi.APIS[id]
def _replace_complex(str_val): """ Replace the alternative or optional elements by a proper regular expression :param str_val: the initial string :return: the formatted expression """ result = str_val matcher = RegexTemplate._alt_regex.search(result) while matcher: group_val = matcher.captures()[0] if not StringUtils.check_form(group_val): continue if group_val.endswith('?'): core = group_val[2:len(group_val) - 4] if matcher.end() < len(result) and result[matcher.end()] == ' ': result = result[:matcher.start()] + ("(?:" + core.replace("\\|", " \\|") + " )?") + result[matcher.end() + 1:] elif matcher.end() >= len(result) and matcher.start() > 0 and result[matcher.start() - 1] == ' ': result = result[:matcher.start() - 1] + ("(?: " + core.replace("\\|", " \\|") + ")?") + result[matcher.end():] else: result = result[:matcher.start()] + "(?:" + core + ")?" + result[matcher.end():] else: core = group_val[2:len(group_val) - 2] result = result[:matcher.start()] + "(?:" + core + ")" + result[matcher.end():] matcher = RegexTemplate._alt_regex.search(result) return result
def draw_form(self): super().draw_form() if self.visible: font = pg.font.Font(Themes.DEFAULT_THEME.get("banner_font_style"), int(self.size[1] * .07)) txt = font.render(StringUtils.get_string("ID_DISPLAY"), True, Themes.DEFAULT_THEME.get("font")) rect_txt = txt.get_rect() rect_txt.topleft = (int(self.coords[0] * 1.05), int(self.coords[1] * 1.05)) self.display.blit(txt, rect_txt) self.size_select = pg.Rect( (0, int(rect_txt.bottom * 1.2)), (int(self.size[0] * .85), int(self.size[1] * .12))) self.size_select.centerx = self.get_rect().centerx img = Images.get_icon(Images.DROP_DOWN) img[1].midright = (int(self.size_select.right - DisplaySettings.get_size_by_key()[0] * .01), int(self.size_select.center[1])) self.btn_drop_down = img[1] pg.draw.rect(self.display, Themes.DEFAULT_THEME.get("text_area_background"), self.size_select, 0) self.display.blit(img[0], img[1]) font = pg.font.Font(Themes.DEFAULT_THEME.get("text_font_style"), int(self.size_select.height * 0.6)) txt = font.render(self.__size, True, Themes.DEFAULT_THEME.get("text_area_text")) rect_txt = txt.get_rect() rect_txt.center = self.size_select.center self.display.blit(txt, rect_txt) self.draw_drop_down()
def __str__(self): """ Returns a string representation of the double. :return: the string representation """ return StringUtils.get_short_form(self._value)
def _get_text_rendering(self, table): """ Generates the text representation for the categorical table. :param table: the table :return: the text rendering of the table """ text_table = '' base_variable = table.get_variable().replace("'", '') if base_variable == self._system.get_settings().user_input: text_table += '\n[user]\t' elif base_variable == self._system.get_settings().system_output: text_table += '[system]\t' else: text_table += '[' + base_variable + ']\t' for value in table.get_values(): if not isinstance(value, NoneVal): content = str(value) if table.get_prob(value) < 0.98: content += ' (' + StringUtils.get_short_form( table.get_prob(value)) + ')' text_table += content + '\n\t\t' if base_variable == self._system.get_settings().user_input: text_table += '\n' text_table = text_table[0:-3] return text_table
def crear_todas_las_evaluaciones(self, evaluaciones: List[Evaluacion], apodo): for evaluacion in evaluaciones: func = "nueva_evaluacion_" + apodo try: metodo = getattr(self, func) metodo(evaluacion.tipo) except AttributeError: self.nueva_evaluacion() self.find_element(self.__locators.MODAL_EVALUACION) fecha_descompuesta = StringUtils.descomponer_fecha_en_atomos( evaluacion.fecha) dtp = DatePicker(self.driver) self.find_element(self.__locators.FECHA_EV_INP).click() dtp.seleccionar_fecha( DateUtils.set_date(*fecha_descompuesta).fecha) self.find_element(self.__locators.NOMBRE_EV_INP).send_keys( evaluacion.nombre) if evaluacion.ponderacion == Ponderacion.MANUAL: self.find_element(self.__locators.PONDERACION_AUTO_BTN).click() self.find_element( self.__locators.VALORACION_PONDERACION_TXT).clear() self.find_element( self.__locators.VALORACION_PONDERACION_TXT).send_keys( evaluacion.porcentaje) self.find_element(self.__locators.GUARDAR_EV_BTN).click() self.wait_for_element_invisibility( self.__locators.MODAL_EVALUACION, 60) self.wait_for_element_invisibility( self.__locators.CARGANDO_LISTADO_EVALUACIONES)
def __lt__(self, other): """ Compares the node to other nodes, in order to derive the topological order of the network. If the node given as argument is one ancestor of this node, return -100. If the opposite is true, returns +100. Else, returns the difference between the size of the respective ancestors lists. Finally, if both lists are empty, returns +1 or -1 depending on the lexicographic order of the node identifiers. :param other: the node to compare :return: the comparison result """ if len(self.get_input_node_ids()) == 0 and len( other.get_input_node_ids()) > 0: return False if len(self.get_input_node_ids()) > 0 and len( other.get_input_node_ids()) == 0: return True if len(self.get_input_node_ids()) == 0 and len( other.get_input_node_ids()) == 0: from bn.nodes.action_node import ActionNode if isinstance(self, ActionNode) and not isinstance(other, ActionNode): return False if not isinstance(self, ActionNode) and isinstance( other, ActionNode): return True return StringUtils.compare(self._node_id, other.get_id()) < 0 ancestors = self.get_ancestors() if other in ancestors: return True other_ancestors = other.get_ancestors() if self in other_ancestors: return False size_diff = len(other_ancestors) - len(ancestors) if size_diff != 0: return True if size_diff < 0 else False return StringUtils.compare(self._node_id, other.get_id()) < 0
def __str__(self): """ Returns a string representation of the array. :return: the string representation of the array """ return '[' + ','.join( [StringUtils.get_short_form(d) for d in self._value]) + ']'
def __init__(self, type, name): self.__type = type if name is None: self.name = "{}_{}".format(StringUtils.get_string("ID_UNKNOWN"), Blueprint.NAME_COUNT) Blueprint.NAME_COUNT += 1 else: self.name = name
def validate_project_info(self): valid = True if (StringUtils.get_string("ID_SELECT") in self.__api) and (len(self.__project_name) < 5): valid = False self.__popup = Popup(Popup.POP_STATES.get("ERROR"), "Incorrect project details") elif StringUtils.get_string("ID_SELECT") in self.__api: valid = False self.__popup = Popup(Popup.POP_STATES.get("ERROR"), "API must be selected") elif len(self.__project_name) < 5: valid = False self.__popup = Popup( Popup.POP_STATES.get("ERROR"), "Project name should be greater than 5 chars") return valid
def load_from_store(cls): if AppStore.is_file_exists(cls.USER_GROUPS_FILE_NAME): user_groups_data = AppStore.get_file_contents(UserGroupsStore.USER_GROUPS_FILE_NAME) if StringUtils.is_empty(user_groups_data): return UserGroups() user_groups_json = json.loads(user_groups_data) user_groups = UserGroups.from_json(user_groups_json) return user_groups else: return UserGroups()
def generate_xml(self): element_list = [] for point, prob in self._points.items(): value_node = Element('value') value_node.set('prob', StringUtils.get_short_form(prob)) value_node.text(str(ValueFactory.create(prob))) element_list.append(value_node) return element_list
def __init__(self, display, coords=None, size=None): Form.__init__(self, display, coords, size) self.lang_select = None self.btn_drop_down = None self.__logger = logger_utils.get_logger(__name__) self.__lang = StringUtils.get_string(StringUtils.DEFAULT_LANGUAGE) self.__lang_content = list() self.__lang_counter = 0 self.__is_drop_down_pressed = False self.__selected = False