コード例 #1
0
	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)
コード例 #2
0
def getData(filename):
    """input: filename of the json object with tweets
    output: a list of list of tokenized tweets
    """
    tweets = loadParsedTweets(filename);

    # Try to figure out which scraped results to use
    fn = "categories_nominees_winners";
    global gYear
    if ("15" in filename):
        gYear = 2015
        (categories, nominees, catList) = Category.createCategories(fn + ".json")
    elif ("13" in filename):
        gYear = 2013
        (categories, nominees, catList) = Category.createCategories(fn + "_2013.json")
    else:
        yr = re.search('\d\d\d\d', filename).group(0);
        gYear= yr
        if yr:
            scrapedResults = scrapeResultsforYear(yr, toFile=False)
            (categories, nominees, catList) = Category.createCategories(dict=scrapedResults)
        else: # Just do with 2015 results
            (categories, nominees, catList) = Category.createCategories(fn + ".json")
            
    return (tweets, categories, nominees, catList)
コード例 #3
0
ファイル: Players.py プロジェクト: KimYiuLui/Project2.2
def ga_category():
    blit_bg()
    sprites2.update()
    sprites2.draw(basic.screen)
    blit_allbutbg()
    pygame.display.flip()
    pygame.time.delay(1500)
    Category.typeQroll()
コード例 #4
0
async def add(
    context,
    game,
    alias=None,
    completion_role=None,
    channel_suffix=None,
    active_category=None,
    finished_category=None,
):
    """Command to add a game"""
    discord_context = context.obj["discord_context"]
    guild_obj = Guild.get(id=discord_context.guild.id)

    async with discord_context.typing():
        if Game.get(name=game):
            await discord_context.send(f"{game} already exists.")
            return

        if not channel_suffix:
            channel_suffix = f"plays-{game.lower().strip()}"

        game_obj = Game.create(name=game, channel_suffix=channel_suffix)
        if alias:
            GameAlias.create(name=alias, game=game_obj)

        if completion_role:
            role = get(discord_context.guild.roles, id=role)
        else:
            role = await discord_context.guild.create_role(name=game)
        CompletionRole.create(
            id=role.id, guild=guild_obj, name=role.name, game=game_obj
        )

        if active_category:
            category = get(discord_context.guild.categories, id=active_category)
        else:
            category = await discord_context.guild.create_category(
                name=f"{game} Playthroughs"
            )
        Category.create(
            id=category.id, guild=guild_obj, name=category.name, game_id=game_obj.id,
        )

        if finished_category:
            category = get(discord_context.guild.categories, id=finished_category)
        else:
            category = await discord_context.guild.create_category(
                name=f"{game} Archived"
            )
        Category.create(
            id=category.id,
            guild=guild_obj,
            name=category.name,
            game_id=game_obj.id,
            archival=True,
        )

        await discord_context.send(f"Successfully added {game}!")
コード例 #5
0
ファイル: Clearcheckbook.py プロジェクト: ocurero/python-ccb
 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
コード例 #6
0
ファイル: FieldClf.py プロジェクト: Coder-X15/FieldClf
 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()
コード例 #7
0
 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
コード例 #8
0
ファイル: FieldClf.py プロジェクト: Coder-X15/FieldClf
class Category_Field_Machine:
    ''' Categorical Field Machine'''
    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 predict(self, point):
        '''predicts the class to which the point belongs'''
        val_a = self.category_a_formula(point)
        val_b = self.category_b_formula(point)
        if val_a > val_b:
            return str(self.category_a)
        elif val_b > val_a:
            return str(self.category_b)
        else:
            return 'Confused....'

    def train(self, point, actual_class):
        ''' trains the model'''
        if str(self.category_a).lower() == actual_class.lower():
            self.category_a.update(point)
            self.category_a_formula = self.category_a.category_formula()
        elif str(self.category_b).lower() == actual_class.lower():
            self.category_b.update(point)
            self.category_b_formula = self.category_b.category_formula()
コード例 #9
0
ファイル: app.py プロジェクト: vuquocan1987/TikiScraping2
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
コード例 #10
0
ファイル: Parser.py プロジェクト: visavis2k/accords-platform
    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()
コード例 #11
0
def mainmenu():
    program_run = True

    #Display Menu
    while program_run == True:
        print("\nOffice Solutions Data Analytics" +
              "\nPlease make a selection from the menu below:")
        print("\n\tMain Menu:" +
              "\n\t1 - Most Profitable Products" +
              "\n\t2 - Least Profitable Products" +
              "\n\t3 - Region Insights" +
              "\n\t4 - Sub-Category Insights" +
              "\n\t5 - State Insights" +              
              "\n\t6 - Top Customers" +
              "\n\t7 - Add New Employee" +
              "\n\t8 - Exit")
        selected = input("Choose a menu #: ").lower().strip()

        #Menu Item selected
        if selected == "1":
            # Opens Most Profitable PRoducts
            Profits_Top.top_ten()
        elif selected == "2":
            # Opens Second Insight Code
            Profits_Bottom.bottom_ten()
        elif selected == "3":
            # Opens Region Insights
            Regions.menu()
        elif selected == "4":
            # Opens Sub-Category Insights
            Category.menu()
        elif selected == "5":
            # Opens State Insights
            States.menu()
        elif selected == "6":
            # Opens Top Customer Insights
            Top_Customers.top_customers()            
        elif selected == "7":
            #Opens Add New Employee Code
            New_Employee.add_employee()
            pause()
        elif selected == "8" or selected == "exit":
            # Exits Loop (and Program)
            program_run = False
        else:
            print("'" + selected + "' is not a valid menu selection. " +
                  "Please enter a numerical value from 1-8.\n")
            pause()
コード例 #12
0
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)
コード例 #13
0
    async def end(self, context):
        """Command to archive a channel that has been finished."""
        user = context.author
        channel_id = context.channel.id
        guild_id = context.guild.id
        channel = Channel.get(user_id=user.id, id=channel_id, guild_id=guild_id)

        if not channel:
            await context.send(
                "This command must be sent from a proper playthrough room that you own."
            )
            return

        # TODO Check if already archived or not
        archival_category_obj = Category.get(
            guild_id=guild_id, game=channel.game, archival=True, full=False
        )
        if not archival_category_obj:
            await context.send(
                "No archival category is available for this game. Please contact an admin."
            )
            return

        archival_category = get(context.guild.categories, id=archival_category_obj.id)
        await context.channel.edit(category=archival_category, sync_permissions=True)

        completion_role_obj = CompletionRole.get(game=channel.game, guild_id=guild_id)
        if completion_role_obj:
            completion_role = get(context.guild.roles, id=completion_role_obj.id)
            await context.author.add_roles(completion_role)
            await context.send("You have been grantend the completion role.")

        await context.send("The channel has been moved to the archival category.")
コード例 #14
0
    def load_categories(cls):
        """ reads the categories.txt file and re-compose the Python objects
            from the json representation of categories. The content of the
            categories.txt file should look something like:

            "{\"name\": \"Necklaces\"}"
            "{\"name\": \"Bracelets\"}"

            Basically, we read the file line by line and from those lines we
            recreate the Pyhton objects.

            Also we take care to not multiply the elements in the categories
            list. We have avoided this by overloading the __eq__() operator in
            Category class. More on this during the lectures.
        """
        decoder = Category.Decoder()

        try:
            with open("categories.txt") as f:
                for line in f:
                    data = loads(line)
                    decoded_category = decoder.decode(data)
                    if decoded_category not in cls.categories:
                        cls.categories.append(decoded_category)
        except (JSONDecodeError, FileNotFoundError) as e:
            cls.categories = []
        return cls.categories
コード例 #15
0
ファイル: DataRetrieve.py プロジェクト: github4n/Python
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
コード例 #16
0
ファイル: Game.py プロジェクト: prabhavivek/Hangman
    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
コード例 #17
0
def fetch():    
    request = service.service().guideCategories().list(part='snippet', regionCode=regionCode)
    response = request.execute()
    
    categories = []
        
    for item in response['items']:
        category = Category.fromCategoryList(item)
        categories.append(category)
        
    return categories
コード例 #18
0
    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))
コード例 #19
0
ファイル: app.py プロジェクト: vuquocan1987/TikiScraping2
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
コード例 #20
0
def fetch():
    request = service.service().guideCategories().list(part='snippet',
                                                       regionCode=regionCode)
    response = request.execute()

    categories = []

    for item in response['items']:
        category = Category.fromCategoryList(item)
        categories.append(category)

    return categories
コード例 #21
0
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
コード例 #22
0
ファイル: app.py プロジェクト: vuquocan1987/TikiScraping2
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
コード例 #23
0
def user_answer():
    while True:
        played = ["math", "geography", "french", "rap",
                  "trivia"]  #a list with the possible categories
        player_input = input(
            "Choose a category. Make sure it is all lowercase!!\n"
        )  # asks player to choose a category
        print("")
        if player_input == "geography":  # checks if it matches geography
            Category.geography()
        elif player_input == 'math':  # checks if it matches math
            Category.math()
        elif player_input == "french":  # checks if it matches french
            Category.french()
        elif player_input == "rap":  # checks if it matches rap
            Category.rap()
        elif player_input == 'trivia':  # checks if it matches trivia
            Category.trivia()
        else:  # otherwise you can't play that category
            print("That was not an option! Choose between the 5 categories!"
                  )  # and you will be reminded this
            user_answer(
            )  # and given an option to type in the category name correctly
        print(
            "Would you like to continue playing the Game?"
        )  # after playing the category, ask player if they want to continue
        player_input = input("Type yes or no!\n")  # by typing yes or no
        if player_input == 'yes':  # if yes
            user_answer()  # recall the function
        elif player_input == 'no':  # if no
            print("BYE!! Thank you for playing!")  # print this
            break  # end the while loop
        elif player_input != "no":  #user type anything other than yes or no
            print("Make sure you type yes or no")  # print this to remind them
        elif player_input != "yes":  #user type anything other than yes or no
            print("Make sure you type yes or no")  # print this to remind them
コード例 #24
0
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()
コード例 #25
0
def tmp():  # need for "Optimize imports"
    time()
    urllib()
    bs4()
    Category()
    Deepl()
    FindDigits()
    Html()
    LoadDictFromFile()
    Parsing()
    Product()
    SaveDictToFile()
    Sw()
    WorkWithJSON()
    print()
    datetime()
    quote()
    urljoin()
コード例 #26
0
ファイル: Parser.py プロジェクト: visavis2k/accords-platform
 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)
コード例 #27
0
ファイル: FeatureMatrix.py プロジェクト: xfq/aquamacs-emacs
class FeatureMatrix:
    def __init__(self, title):
        self.title = title
        self.products = Category()
        self.features = Category()
        self.values = ValueMatrix()

    def get_products(self):
        return self.products

    def get_features(self):
        return self.features

    def add(self, product, feature, value):
        if product.get_subcategories():
            print >> sys.stderr, sys.argv[
                0] + ": Product '%s' is not a leaf." % product.get_name()
            raise NonLeafFeature
        if feature.get_subcategories():
            print >> sys.stderr, sys.argv[
                0] + ": Feature '%s' is not a leaf." % feature.get_name()
            raise NonLeafProduct
        self.values.add(product, feature, value)

    def html_print(self, style=''):
        print '<html>'
        print style
        print '<body><p>%s</p><table>\n' % cgi.escape(self.title)
        # Sub one in the following because we ignore the (useless to us) first level in the product/feature matrix.
        feature_depth = self.features.max_depth() - 1
        product_depth = self.products.max_depth() - 1
        product_list = self.products.leaves()

        # Print the product hierarchy
        print self.products.as_cols(self.products.get_subcategories(), True,
                                    feature_depth, product_depth, 1)

        # Print the feature hierarchy and feature values
        for feature in self.features.get_subcategories():
            print feature.as_rows(False, product_list, self.values,
                                  feature_depth, 1)

        print "</table></body></html>"
コード例 #28
0
ファイル: InputReaders.py プロジェクト: Oxitocina/HODOR
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
コード例 #29
0
class FeatureMatrix:
    def __init__(self, title):
	self.title = title
	self.products = Category()
	self.features = Category()
	self.values = ValueMatrix()

    def get_products(self):
	return self.products;
    
    def get_features(self):
	return self.features
    
    def add(self, product, feature, value):
	if product.get_subcategories():
	    print >> sys.stderr, sys.argv[0] + ": Product '%s' is not a leaf." % product.get_name()
	    raise NonLeafFeature
	if feature.get_subcategories():
	    print >> sys.stderr, sys.argv[0] + ": Feature '%s' is not a leaf." % feature.get_name()
	    raise NonLeafProduct
	self.values.add(product, feature, value)

    def html_print(self, style=''):
	print '<html>'
	print style
	print '<body><p>%s</p><table>\n' % cgi.escape(self.title)
	# Sub one in the following because we ignore the (useless to us) first level in the product/feature matrix.
	feature_depth = self.features.max_depth() - 1
	product_depth = self.products.max_depth() - 1
	product_list = self.products.leaves()

	# Print the product hierarchy
	print self.products.as_cols(self.products.get_subcategories(), True, feature_depth, product_depth, 1)
	
	# Print the feature hierarchy and feature values
	for feature in self.features.get_subcategories():
	    print feature.as_rows(False, product_list, self.values, feature_depth, 1)
	
	print "</table></body></html>"
コード例 #30
0
    def __init__(self, title):
	self.title = title
	self.products = Category()
	self.features = Category()
	self.values = ValueMatrix()
コード例 #31
0
    async def start(self, context, *, game: str):
        """Command to start a playthrough channel in a particular game.

        Arguments:
            game -- The game to start a playthrough channel for.
        """
        guild = context.guild
        guild_obj = Guild.get(id=context.guild.id)
        user = context.author
        game_obj = Game.get_by_alias(game)

        if not game_obj:  # Game not found
            # TODO Implement start list or maybe have another command
            await context.send(
                "Game does not exist, try again or use `$start list` for game list!"
            )
            return

        if Channel.get(user_id=user.id, game=game_obj, guild=guild_obj):
            await context.send(f"You already have a {game_obj.name} room!")
            return

        # Get first available category for the game
        category_obj = Category.get(
            game=game_obj, guild=guild_obj, full=False, archival=False
        )
        if not category_obj:
            await context.send(
                f"Sorry, all our categories are full right now. Please contact an admin."
            )
            return

        category = get(context.guild.categories, name=category_obj.name)
        channel_name = f"{context.author.display_name}-{game_obj.channel_suffix}"
        channel = await context.guild.create_text_channel(
            name=channel_name, category=category
        )
        Channel.create(
            id=channel.id,
            user_id=user.id,
            game=game_obj,
            guild=guild_obj,
            category=category_obj,
            name=channel.name,
        )

        # Handle persmissions
        permissions_owner = discord.PermissionOverwrite(
            read_messages=True,
            read_message_history=True,
            send_messages=True,
            manage_messages=True,
        )
        await channel.set_permissions(context.author, overwrite=permissions_owner)

        instructions = (
            f"This room has been created for your playthrough of {game_obj.name}.\n"
            "When you have finished the game, type `$finished` and the room will be moved.\n\n"
            "Please note that commands will only function in your playthrough room, "
            "and that you can only have one playthrough room at any given time."
        )

        instructions_msg = await channel.send(instructions)
        await instructions_msg.pin()

        await context.send(f"Game room created: {channel.mention}", delete_after=30)
コード例 #32
0
postags = cmu.runtagger_parse(parsedSociallists) #gets a list of postags each for each hashtag

i = 0

for ParsedTag,postag,type in zip(parsedSociallists,postags,list_type):
	checkTweetsret = checkTweets.checkTweets(ParsedTag.replace(" ",""),"test/"+str(i/100)+"tweets.txt")
	#checks for the hashtag in the files provided.

	i+=1

	tofile = open(argv[3],"a")
	tofile.write(str(testFile1.test1(ParsedTag))+","+ #number of charcters in hashtag
	str(testFile2.test2(ParsedTag))+","+ #number of words in hashtag
	str(testFile4.test4(ParsedTag))+","+ #presence of days
	str(testFile5.numbercount(postag))+","+ # presence of numbers
	str(testFile5.prepositioncount(postag))+","+ #presence of prepositions
	str(testFile5.conjuctioncount(postag))+","+ #presence of conjuctions
	str(testFile5.interjectioncount(postag))+","+ #presence of interjections
	str(testFile6.test6(postag))+","+ #presence of nouns
	str(testFile7.test7(postag))+","+ #presence of Adjectives
	str(testFile8.test8(postag))+","+ #presence of verbs
	str(testFile9.test9(postag))+","+ #presence of Adverbs
	str(testFile10.test10(postag))+","+ #presence of pronouns
	str(testFile11.pos_tag_entropy(ParsedTag.replace(" ",""),postag))+","+ #pos_tag entropy
	str(testFile12.test12(ParsedTag.replace(" ","")))+","+ #ratio of non-english to english words
	str(checkTweetsret[0])+","+str(checkTweetsret[1])+","+ #check for number and urls in tweets
	str(Category.checkCategories(ParsedTag.replace(" ","")))+","+ #check for category match
	str(plurals.containspluralNouns(ParsedTag,postag))+","+ #check if hashtag contains plural common noun
	str(type.replace("\n",""))+"\n") #class of hashtag
	tofile.close()
コード例 #33
0
    tofile = open(argv[3], "a")
    tofile.write(
        str(testFile1.test1(ParsedTag)) +
        "," +  #number of charcters in hashtag
        str(testFile2.test2(ParsedTag)) + "," +  #number of words in hashtag
        str(testFile4.test4(ParsedTag)) + "," +  #presence of days
        str(testFile5.numbercount(postag)) + "," +  # presence of numbers
        str(testFile5.prepositioncount(postag)) +
        "," +  #presence of prepositions
        str(testFile5.conjuctioncount(postag)) +
        "," +  #presence of conjuctions
        str(testFile5.interjectioncount(postag)) +
        "," +  #presence of interjections
        str(testFile6.test6(postag)) + "," +  #presence of nouns
        str(testFile7.test7(postag)) + "," +  #presence of Adjectives
        str(testFile8.test8(postag)) + "," +  #presence of verbs
        str(testFile9.test9(postag)) + "," +  #presence of Adverbs
        str(testFile10.test10(postag)) + "," +  #presence of pronouns
        str(testFile11.pos_tag_entropy(ParsedTag.replace(" ", ""), postag)) +
        "," +  #pos_tag entropy
        str(testFile12.test12(ParsedTag.replace(" ", ""))) +
        "," +  #ratio of non-english to english words
        str(checkTweetsret[0]) + "," + str(checkTweetsret[1]) +
        "," +  #check for number and urls in tweets
        str(Category.checkCategories(ParsedTag.replace(" ", ""))) +
        "," +  #check for category match
        str(plurals.containspluralNouns(ParsedTag, postag)) +
        "," +  #check if hashtag contains plural common noun
        str(type.replace("\n", "")) + "\n")  #class of hashtag
    tofile.close()
コード例 #34
0
ファイル: socialList.py プロジェクト: mkdadi/SocialList
i = 0

for ParsedTag,postag,type in zip(parsedSociallists,postags,list_type):
	checkTweetsret = checkTweets.checkTweets(ParsedTag,"test/"+str(i/100)+"tweets.txt")
	#checks for the hashtag in the files provided.

	i+=1

	tofile = open(argv[3],"a")
	tofile.write(str(testFile1.test1(ParsedTag))+","+ #number of charcters in hashtag
	str(testFile2.test2(ParsedTag))+","+ #number of words in hashtag
	str(testFile4.test4(ParsedTag))+","+ #presence of days
	str(testFile5.numbercount(postag))+","+ # presence of numbers
	str(testFile5.prepositioncount(postag))+","+ #presence of prepositions
	str(testFile5.conjuctioncount(postag))+","+ #presence of conjuctions
	str(testFile5.interjectioncount(postag))+","+ #presence of interjections
	str(testFile6.test6(postag))+","+ #presence of nouns
	str(testFile7.test7(postag))+","+ #presence of Adjectives
	str(testFile8.test8(postag))+","+ #presence of verbs
	str(testFile9.test9(postag))+","+ #presence of Adverbs
	str(testFile10.test10(postag))+","+ #presence of pronouns
	str(testFile11.pos_tag_entropy(ParsedTag.replace(" ",""),postag))+","+ #pos_tag entropy
	str(testFile12.test12(ParsedTag.replace(" ","")))+","+ #ratio of non-english to english words
	str(checkTweetsret[0])+","+str(checkTweetsret[1])+","+ #check for number and urls in tweets
	str(Category.checkCategories(ParsedTag.replace(" ","")))+","+ #check for category match
	str(plurals.containspluralNouns(ParsedTag,postag))+","+ #check if hashtag contains plural common noun
	str(type.replace("\n",""))+"\n") #class of hashtag
	tofile.close()
	print i
コード例 #35
0
ファイル: Hangman.py プロジェクト: MaciejBedkowski/Hangman
#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: