def compare(self, category, other): try: c1 = Category.Category(category, self.data) c2 = Category.Category(category, other.data) c1.compare(c2) except Category.InvalidCategoryName: print("Invalid category %s" % category)
def __init__(self, category_a, category_b): ''' initialiser''' self.category_a = Category( list(i[0] for i in category_a[list(category_a.keys())[0]]), list(j[1] for j in category_a[list(category_a.keys())[0]]), list(category_a.keys())[0]) self.category_b = Category( list(i[0] for i in category_b[list(category_b.keys())[0]]), list(j[1] for j in category_b[list(category_b.keys())[0]]), list(category_b.keys())[0]) self.category_a_formula = self.category_a.category_formula() self.category_b_formula = self.category_b.category_formula()
def __init__(self, files): ''' Constructor @param files: list of files to parse ''' self.files = files self.cats = Category.Categories() self.models = Model.Models() # Add the standard categories from OCCI Core self._built_in_model = Model.Model("core", "OCCI Core categories", "1.0,0") self.models.add(self._built_in_model) # Entity entity = Category.Category("entity", "http://schemas.ogf.org/occi/core#", "/entity/", None, "kind", self._built_in_model) entity.addattr( Attribute.Attribute("id", "string", "true", "true", None, "true")) entity.addattr( Attribute.Attribute("title", "string", "false", "false", None, "false")) self.cats.add(entity) # Resource resource = Category.Category( "resource", "http://schemas.ogf.org/occi/core#", "/resource/", "http://schemas.ogf.org/occi/core#entity", "kind", self._built_in_model) resource.addattr( Attribute.Attribute("summary", "string", "false", "false", None, "false")) self.cats.add(resource) # Link link = Category.Category("link", "http://schemas.ogf.org/occi/core#", "/link/", "http://schemas.ogf.org/occi/core#entity", "link", self._built_in_model) link.addattr( Attribute.Attribute("source", "string", "true", "false", None, "false")) link.addattr( Attribute.Attribute("target", "string", "true", "false", None, "false")) self.cats.add(link) self.parsers = ParserCollection()
def get_category(bot, user, text, catdb): # check if category name is valid # must be alphanumeric if commands[text].name == commands["/cancel"].name: cancel(bot, user) valid = catdb.checkName(text) user.tmp_display_id = "" user.tmp_upload_content = None user.tmp_upload_category = None user.tmp_create_category = None if valid == True: category = Category.Category(text, user.hash_id) if catdb.addCategory(category) and user.pella_coins >= cat_price: s = "Success: new category created\n/main_menu" BotWrappers.sendMessage(bot, user, s) user.pella_coins -= cat_price else: s = "Fail: category already present" BotWrappers.sendMessage(bot, user, s) else: user.tmp_create_category = False s = "Create category error: " + valid BotWrappers.sendMessage(bot, user, s)
class DataShicimingju: def __init__(self): self.URL = "http://www.shicimingju.com" self.timeout = 7 # 获取年代. http://www.shicimingju.com/左侧的年代诗人. # 返回值形式 {"先秦":"/category/xianqinshiren"} def get_categories(self): try: # 构建请求的request request = urllib2.Request(self.URL) # 利用urlopen获取页面代码 response = urllib2.urlopen(request, timeout=self.timeout) # 将页面转化为UTF-8编码 agepage = response.read().decode('utf-8') if not agepage: print u"获取年代信息页面出错." except urllib2.URLError, e: if hasattr(e, "reason"): print u"连接诗词名句网失败,错误原因", e.reason return None categories = [] soup = BeautifulSoup(agepage) allcates = soup.select("#left > div:nth-of-type(1) > ul > li") for cate in allcates: atag = cate.select("a") catename = atag[0].string cateurl = atag[0]["href"] category = Category() category.name = catename.encode('utf-8') category.url = cateurl categories.append(category) return categories
def run(self): self.cat = Category.Category() self.cat_name = self.cat.get_category() if self.cat_name == None: return self.run_game() def go_back(): return Menu.MenuStatus.DONE def new_category(): try: self.cat_name = self.cat.get_category() if self.cat_name == None: return Menu.MenuStatus.OK self.run_game() self.cat_menu_item.set_title( self.catMenuTitle.format(self.cat_name)) except Exception as e: print_error(e) return Menu.MenuStatus.OK def same_category(): self.run_game() return Menu.MenuStatus.OK men = Menu.MenuX("Hangman:Menu") self.cat_menu_item = Menu.MenuItem( self.catMenuTitle.format(self.cat.get_name()), same_category) men.add(self.cat_menu_item) men.add(Menu.MenuItem("Change category", new_category)) men.add(Menu.MenuItem("Go Back", go_back)) while men.run() == Menu.MenuStatus.OK: pass
def __init__(self): self.categories = [] self.input_channel_states = [] self.columns = [] # Randomly generate all categories and columns for i in range(Parameters.NUMBER_OF_CATEGORIES): self.categories.append(Category.Category()) for i in range(Parameters.NUMBER_OF_COLUMNS): self.columns.append(Column.Column(i))
def createCategory(self, name, parent=0): categoryData = {} if parent != 0 and self.getCategory(parent) == None: raise CategoryNotFoundError("parent category ID %s not found" % (parent, )) categoryData[ "parent"] = parent #FIXME: Acording to the API, parent is optional but if not set the category has parent=null instead of parent=0 !! FIXME categoryData["name"] = name category = Category(self.auth, self.cache, categoryData) category.onCommit = "create" category.commit() return category
def gen_cats_tree(): cats_list = select_all() cats_list = [Category(cat[0],cat[1],cat[2],cat[3] )for cat in cats_list] main_cats = [cat for cat in cats_list if cat.parent_id == None] de = deque(main_cats) while de: parent_cat = de.popleft() sub_cats = [cat for cat in cats_list if cat.parent_id == parent_cat.cat_id] parent_cat.add_child_cats(sub_cats) de.extend(sub_cats) print(main_cats) return main_cats
def get_categories(): conn = sqlite3.connect('text.db') cursor = conn.cursor() cursor.execute('SELECT * FROM categories') sql_categories = cursor.fetchall() conn.close() categories = [] for sql_category in sql_categories: category = Category(id=sql_category[0], name=sql_category[2], url=sql_category[1]) categories.append(category) return categories
def get_main_categories(save_db = False,debug_run=False): soup = get_soup(TIKI_URL) result = [] for a in soup.find_all("a",{'class' : 'MenuItem__MenuLink-tii3xq-1 efuIbv'}): cat_id = None name = a.find('span', {'class':'text'}).text url = a['href'] parent_id = None cat = Category(cat_id, name, url, parent_id) if save_db: cat.save_into_db() result.append(cat) if debug_run: return result[0:10] return result
def seeds_articles(): """ seeds 2 categories => c1, c2 seeds 2 tags => t1 belongs to c1, t2 belongs to c2 seeds 2 articles => a1 has t1, a2 has t2 """ c1 = Category('c1').save() c2 = Category('c2') .save() t1 = Tag('t1', c1) .save() t2 = Tag('t2', c2) .save() a1 = Article(title="a1", description="a1 description", body="a1 body") a1.tags.append(t1) a1.save() a2 = Article(title="a2", description="a2 description", body="a2 body") a2.tags.append(t2) a2.save()
def tmp(): # need for "Optimize imports" time() urllib() bs4() Category() Deepl() FindDigits() Html() LoadDictFromFile() Parsing() Product() SaveDictToFile() Sw() WorkWithJSON() print() datetime() quote() urljoin()
def _parse_models(self, root): # TODO checking for single model # TODO warn about unknown XML nodes try: xmlmodel = root.find("model") if xmlmodel is None: return model = Model.Model(xmlmodel.get("name"), xmlmodel.get("description"), xmlmodel.get("version"), xmlmodel.get("namespace")) logging.info("Model is " + model.name + " (v. " + model.version + ")") except: logging.error("Problem processing model") raise # Find all categories for category in xmlmodel.findall("category"): term = category.get("term") if term == None: logging.warn("No category provided") continue logging.info("Category " + term) # Add a category try: scheme, klass, location, rel, struct_name, headerFilename = category.get( "scheme"), category.get("class"), category.get( "location"), category.get("rel"), category.get( "structname"), category.get("headerfilename") cat = Category.Category(term, scheme, location, rel, klass, model, struct_name, headerFilename) self._addattrs(category, cat) self._addactions(category, cat) self._addlinks(category, cat) self._addmixins(category, cat) model.add(cat) self.cats.add(cat) except: logging.error("Problem processing category " + term) logging.error(sys.exc_info()) # Add this model to the models collection self.models.add(model)
def readCategories(file_name): categories = {} with open (file_name, 'rb') as fCategories: reader = csv.reader(fCategories) row_num = 0 for row in reader: if row_num == 0: #First row is just the headers row_num += 1 continue category_data = [] for col in row: category_data.append(col.strip()) row_num += 1 category = Category.Category(category_data) categories[category.name] = category return categories
def get_sub_categories(category, save_db = False,debug_run=False): name = category.name url = category.url result = [] try: soup = get_soup(url) div_containers = soup.find_all('div',{"class":"list-group-item is-child"}) print(div_containers) for div in div_containers: sub_id = None sub_name = div.a.text sub_url = 'http://tiki.vn' + div.a['href'] sub_parent_id = category.cat_id sub = Category(sub_id, sub_name, sub_url, sub_parent_id) if save_db: sub.save_into_db() result.append(sub) except Exception as err: print('ERROR BY GET SUB CATEGORIES:', err) if debug_run: return result else: return result
def __init__(self, title): self.title = title self.products = Category() self.features = Category() self.values = ValueMatrix()
#Sprawdzanie wyboru użytkownika if choice == 0: break elif choice == 1: Instruction.Instruction() elif choice == 3: Champions.schowTop10() elif choice == 2: playerName = input("Podaj imię:") #Wybór kategorii Category.Category() try: choiceCategory = int(input("Wybierz kategorię hasła:")) except ValueError: choiceCategory = 5 #Zaciągnięcie haseł do gry passwords = Passwords.GetPasswords(passwords, choiceCategory) #Losowanie hasła do gry wordGame = RandomPasswordGame(passwords, wordGame) #Zakrywanie hasła gry secretPassword = SecredPassword.SecredPassword(wordGame) while True:
def read(self, category): try: Category.Category(category, self.data).read() except Category.InvalidCategoryName: print("Invalid category %s" % category)
def category(): yield Category("animal")
#!/usr/bin/python # -*- coding: UTF-8 -*- import MySql import Category if __name__ == "__main__": sql = MySql.MySql() Category.Category(sql).get_categorys() db = sql.db1 db.commit() db.close()
import sqlite3 import os import os.path path = os.path.abspath(__file__) dirname, useless = os.path.split(path) ROOT_DIR = dirname + '/' DB_FILE_NAME = ROOT_DIR + 'ka.db' BACKUP_FILE_NAME = ROOT_DIR + 'commit.backup' logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) logger = logging.getLogger('ReloadAllData') service_list = {} service_list['account'] = Account.Account(logger) service_list['category'] = Category.Category(logger) service_list['record'] = Record.Record(logger) service_list['statistic'] = Statistic.Statistic(logger) service_list['budget'] = Budget.Budget(logger) service_list['currency'] = Currency.Currency(logger) # 删除数据库文件 if os.path.exists(DB_FILE_NAME): os.remove(DB_FILE_NAME) # 读取创建数据库SQL文件内容 f = open(ROOT_DIR + 'sql/create.sql', encoding='utf-8') create_sql_content = f.read() f.close() f = open(ROOT_DIR + 'sql/add_basic_data.sql', encoding='utf-8') add_basic_data_sql_content = f.read()