index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
44,660 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/load.py | #!/usr/bin/env python3
from bs4 import BeautifulSoup
import logging
import json
import sys
from os import listdir
import os.path
from match import parse
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def parse_match(filename):
if (filename.startswith("match")):
return parse.open_match(from_file(filename))
return None
def process_matchdata(match, directory):
matchdatafile = os.path.join(directory, "html/match/", "matchdata-{}.html".format(match["matchid"]))
# print(match["matchid"])
with open(matchdatafile, "rb") as fp:
linje = fp.read().decode("latin-1")
matchdata = parse.parse_matchdata(linje)
match["away_coachid"] = matchdata["coach2"]
match["home_coachid"] = matchdata["coach1"]
return match
return match
def process_match(directory, filename):
LOG.debug("Process single match %s %s", directory, filename)
matchid = filename[filename.find("match-") + 6:filename.rfind(".html")]
match = parse.parse_match(matchid, from_file("{}/html/match/{}".format(directory, filename)))
# print(match)
if match:
if "date" in match and match["date"]:
match = process_matchdata(match, directory)
return match
else:
print("No date in file {}".format(filename), file=sys.stderr)
return None
return None
def process_matches(directory, files):
matches = []
for filename in files:
if (filename.startswith("match-")):
match = process_match(directory, filename)
if match:
matches.append(match)
return matches
def from_files(directory):
match_path = os.path.join(directory, "html/match/")
LOG.debug("listing files in %s", directory)
return process_matches(directory, listdir(match_path))
def create_json_cache(basepath = BASEPATH):
LOG.debug("Creating json cache using %s", basepath)
import json
filepath = os.path.join(basepath, "json/match-all.json")
match_html_directory = os.path.join(basepath, "html/match/")
matches = from_files(basepath)
LOG.debug("Dump %s matches into %s", len(matches), filepath)
if len(matches) == 0:
LOG.warning("No matches found in %s", basepath)
with open(filepath, "w") as fp:
json.dump(matches, fp, indent=4)
return matches
def create_cache(directory=BASEPATH, filename="json/match-all.json"):
import os.path
match_all_filename = os.path.join(directory, filename)
match_html_directory = os.path.join(directory, "html/match")
if not os.path.isfile(match_all_filename):
LOG.debug("%s does not exist", match_all_filename)
return True
LOG.debug("Found %s", match_all_filename)
json_mtime = os.path.getmtime(match_all_filename)
for checkfile in listdir(match_html_directory):
LOG.debug("Checking %s", checkfile)
if checkfile.startswith("match") and os.path.getmtime(os.path.join(directory,"html/match", checkfile)) > json_mtime:
LOG.debug("Modified since %s", json_mtime)
return True
return False
def from_json(basepath = BASEPATH):
LOG.debug("From json %s json/match-all.json", basepath)
if create_cache(basepath, "json/match-all.json"):
print("Creating cache")
return create_json_cache(basepath)
with open(basepath + "json/match-all.json") as fp:
return json.load(fp)
def from_file(filename):
LOG.debug("From file %s", filename)
if not os.path.isfile(filename):
LOG.warning("File %s does not exist", filename)
matchid = filename[filename.find("match-") + 6:filename.rfind(".html")]
LOG.debug("match id: %s", matchid)
html = open(filename, "rb").read()
soup = BeautifulSoup(html, "lxml")
return soup
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.info("Parsing teamlist for coaches")
# import parse
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(process_match(sys.argv[1] if len(sys.argv) > 1 else BASEPATH, "match-{}.html".format(sys.argv[2])))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,661 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/parse_profile.py | #!/usr/bin/env python
""" Parse player from HTML file """
import sys
import re
import dateutil.parser as parser
import logging
from bs4 import BeautifulSoup
from bs4.element import NavigableString
LOG = logging.getLogger(__package__)
def row_with_heading(table, heading):
LOG.debug("Searching for heading {}".format(heading))
for row in table.select("tr"):
if isinstance(row, NavigableString):
continue
LOG.debug("raden: {}".format(row))
columns = list(row.select("td"))
LOG.debug("{} children {}".format(len(columns), columns))
if columns[0] and heading in columns[0].text:
LOG.debug("Found {} with content '{}'".format(heading, columns[1].text))
if columns[1].select_one("a"):
return columns[1].select_one("a")["href"] if columns[1].select_one("a").has_attr("href") else columns[1].text
return columns[1].text
LOG.debug("{} not found".format(heading))
return None
def parse_touchdown(achievements):
LOG.debug("-==< parse TOUCHDOWN >==-")
LOG.debug("achievement el %s", achievements[2])
return achievements[2].text
def parse_casualties(achievements):
LOG.debug("-==< parse CASUALTIES >==-")
LOG.debug("achievement el %s", achievements[3])
return achievements[3].text
def parse_completions(achievements):
LOG.debug("-==< parse COMPLETIONS >==-")
LOG.debug("achievement el %s", achievements[1])
return achievements[1].text
def parse_interception(achievements):
LOG.debug("-==< parse INTERCEPTION >==-")
LOG.debug("achievement el %s", achievements[0])
return achievements[0].text
def parse_total(spp_table):
LOG.debug("-==< parse TOTAL >==-")
LOG.debug("achievement el %s", spp_table)
return row_with_heading(spp_table, 'Star Player Points')
def parse_mvp(achievements):
LOG.debug("MVP >=========-")
LOG.debug("achievement el %s", achievements[4])
return achievements[4].text
def parse_value(soup):
spans = soup.find_all("span", style="font-size:10px")
for span in spans:
if " gp" in span.text:
return int(span.text.strip()[:-3].replace(",",""))
return ""
def find_achievements(soup):
el = soup.select_one("table[style='background-color:#F0F0F0;border:1px solid #808080'] table")
if el:
return el
return soup.select_one('tr.trborder td table td[align=center] table')
def parse_games(player, soup):
LOG.debug("-==< parse player with id %s >==-", player["playerid"])
spp_table = find_achievements(soup)
achievements = spp_table.select('td[align=center]')
#spp_table = soup.select_one("table[style='background-color:#F0F0F0;border:1px solid #808080'] table")
LOG.debug("achievements len %s", len(achievements))
player["spp"] = {"interception": parse_interception(achievements),
"td":parse_touchdown(achievements),
"casualty": parse_casualties(achievements),
"completion": parse_completions(achievements),
"mvp": parse_mvp(achievements),
"total": parse_total(spp_table)}
return player
def parse_playername(soup):
return soup.select_one("h1").text
def parse_position(soup):
for el in soup.select("td a"):
if el.has_attr("href") and "default.asp?p=pt&typID=" in el["href"]:
return el.text
return "unknown"
def parse_spp(soup):
return ["spp"]
def parse_profile(player, soup):
profile = soup.select_one('div[style="vertical-align:top;background-color:#F0F0F0;font-size:10px;border:1px solid #808080;width:300px;min-height:80px;text-align:justify;padding:3px"]')
LOG.debug("profile len %s", len(profile.text) if profile else "NOT FOUND!!")
player["profile"] = profile.text.replace('\xa0', ' ') if profile and "----empty----" not in profile.text else ""
return player
def column_with_heading(table, heading):
LOG.debug("Looking for column with heading %s", heading)
found = False
rows = table.find_all("tr")
LOG.debug("Table has %s rows", len(rows))
headings = rows[0]
LOG.debug(headings)
values = rows[1]
LOG.debug(values)
for idx, h in enumerate(headings.find_all("td")):
LOG.debug(h)
if h.text == heading:
return values.find_all("td")[idx]
return False
def parse_abilities(soup, ability, playerid):
table = soup.select_one("table[width='300']")
if not table:
LOG.debug("Ability table not found for player %s", playerid)
return "0"
column = column_with_heading(table, ability)
return [s.strip() for s in column.find_all(text=True) if s.strip()!=","] if column else []
def parse_ability(soup, ability, playerid):
table = soup.select_one("table[width='300']")
if not table:
LOG.debug("Ability table not found for player %s", playerid)
return "0"
column = column_with_heading(table, ability)
return column.text if column else "-1"
def parse_team(player, soup):
LOG.debug("parse player with id %s", player["playerid"])
LOG.debug("TEAM >========-")
team = soup.select_one("a[style='font-size:11px']")
LOG.debug("team el %s", "{}".format(team))
player["playername"] = parse_playername(soup)
player["position"] = parse_position(soup)
player["value"] = parse_value(soup)
team_id = team["href"].split("=")[-1] if team and team.has_attr("href") else None
team_name = team.text if team else ""
player["ma"] = int(parse_ability(soup, "MA", player["playerid"]))
player["st"] = int(parse_ability(soup, "ST", player["playerid"]))
player["ag"] = int(parse_ability(soup, "AG", player["playerid"]))
player["av"] = int(parse_ability(soup, "AV", player["playerid"]))
player["skills"] = parse_abilities(soup, "Skills", player["playerid"])
number = soup.select_one('td[style="max-height:20px;font-size:10px"]')
LOG.debug("number el %s", "{}".format(number))
player["team"] = team_id
player["teamname"] = team_name
player["number"] = number.text.split('\xa0')[-1] if number else ""
return parse_profile(player, soup)
def parse_fromfile(path, playerid):
LOG.debug("%s %s", path, playerid)
import player.load
parsed_player = parse_games({"playerid": playerid}, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))
parsed_player = parse_team(parsed_player, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))
return parsed_player
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
#logging.basicConfig(level=logging.DEBUG, format=log_format)
logging.basicConfig(level=logging.DEBUG)
import pprint
if len(sys.argv) < 2:
sys.exit("path and playerid required")
path = sys.argv[1] if not sys.argv[1].isdigit() else "input/html/player"
players = sys.argv[1:] if sys.argv[1].isdigit() else sys.argv[2:]
for player_id in players:
if player_id.isdigit():
parsed_player = parse_fromfile(path, player_id)
pprint.PrettyPrinter(indent=4).pprint(parsed_player)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,662 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate.py | #!/usr/bin/env python3
import os
import sys
import json
from match import match
from coach import coach
from team import team
from player import player
from . import collate_coach
from . import collate_match
from . import collate_team
from . import collate_player
from importer.bbleague.defaults import BASEPATH
def load_from_json(basepath = BASEPATH):
path = os.path.join(basepath, "json/data.json")
data = open(path, "rb").read()
return json.loads(data.decode())
def save_to_json(collated_data, basepath = BASEPATH):
path = os.path.join(basepath, "json/data.json")
data = json.dumps(collated_data)
json_file = open(path, "wb")
json_file.write(data.encode())
json_file.close()
def collate(reload=False, basepath = BASEPATH):
path = os.path.join(basepath, "json/data.json")
coaches8 = os.path.join(basepath, "html/coach/coaches-8.html")
if reload or not os.path.isfile(path) or os.stat(path).st_mtime < os.stat(coaches8).st_mtime:
collated_data = collate_data(coach.dict_coaches(), team.dict_teams(), match.dict_games(), player.dict_players())
save_to_json(collated_data)
return collated_data
return load_from_json()
def collate_from_disk():
return collate(True)
def collate_data(coaches, teams, games, players):
data = {"coach": coaches,
"team": teams,
"game": games,
"player": players}
return {"game": collate_match.collate_match(data),
"coach": collate_coach.collate_coach(data),
"team": collate_team.collate_team(data),
"player": collate_player.collate_players(data),
"_coachid": coach.dict_coaches_by_uid()
}
def main():
import pprint
import sys
def pretty(value):
pprint.pprint(value, indent=2)
def search(data, display):
for t in data["team"].values():
if t["id"] in display:
yield t
for c in data["coach"].values():
if c["nick"] in display:
yield c
for g in data["game"].values():
if g["matchid"] in display:
yield g
for p in data["player"].values():
if "p"+p["playerid"] in display:
yield p
force_reload = True if "--force" in sys.argv else False
search_terms = list(filter(lambda x: not x.startswith("--"), sys.argv[1:]))
data = collate(force_reload)
for found in search(data, search_terms if len(search_terms) > 0 else ["Kyrre", "tea2", "1061", "p2804"]):
pretty(found)
print("Data count: {}".format([[key, type(data[key]), len(data[key])] for key in data.keys()]))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,663 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/elo.py |
import logging
LOG = logging.getLogger(__package__)
START_RATING = 0
def expected(A, B):
"""
Calculate expected score of A in a match against B
:param A: Elo rating for player A
:param B: Elo rating for player B
"""
return 1 / (1 + 10 ** ((B - A) / 150))
def elo(old, exp, score, k=10):
"""
Calculate the new Elo rating for a player
:param old: The previous Elo rating
:param exp: The expected score for this match
:param score: The actual score for this match
:param k: The k-factor for Elo (default: 32)
"""
return old + k * (score - exp)
def rate_all(data, key=lambda v, y: v[y+"_coachid"]):
def verify_coach(result, cid):
if cid not in result:
result[cid] = {"cid": cid, "rating": START_RATING, "games": []}
return result
def add_game(result, cid, game_id, old_rating, new_rating, score):
result[cid]["rating"] = new_rating
result[cid]["games"].append( {"game_id": game_id, "score": score, "old_rating": old_rating, "rating": new_rating} )
return result
result = {}
games = sorted(data["game"].values(), key=lambda x: "{0}-{1:04d}".format(x["date"], int(x["matchid"])))
for g in games:
c1_id = key(g, "home")
verify_coach(result, c1_id)
c1_gamecount = len(result[c1_id]["games"])
c2_id = key(g, "away")
verify_coach(result, c2_id)
c2_gamecount = len(result[c2_id]["games"])
c1_rating = result[c1_id]["rating"] if c1_id in result else START_RATING
c2_rating = result[c2_id]["rating"] if c2_id in result else START_RATING
c1_kfactor = 2 if c1_gamecount > 6 else 10
c1_expected = expected(c1_rating, c2_rating)
c2_kfactor = 2 if c2_gamecount > 6 else 10
c2_expected = expected(c2_rating, c1_rating)
c1_score = 1 if g["home_result"] == "W" else 0.5 if g["home_result"] == "T" else 0
c2_score = 1 - c1_score
c1_newrating = elo(c1_rating, c1_expected, c1_score, c1_kfactor) #if len(result) < 10 or c2_gamecount > 4 or (c1_gamecount < 5 and c2_gamecount < 5) else c1_rating
c2_newrating = elo(c2_rating, c2_expected, c2_score, c2_kfactor) #if len(result) < 10 or c1_gamecount > 4 or (c1_gamecount < 5 and c2_gamecount < 5) else c2_rating
add_game(result, c1_id, g["matchid"], c1_rating, c1_newrating, c1_score)
add_game(result, c2_id, g["matchid"], c2_rating, c2_newrating, c2_score)
return result
def main():
from sys import argv
import pprint
from stats import collate
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
from coach.coach import dict_coaches_by_uid
pp = pprint.PrettyPrinter(indent=2)
data = collate.collate()
rates = rate_all(data, lambda v, y: v[y+"_team"])
print(pp.pprint(rates) )
#pp.pprint(data["coachid"])
for r in sorted(rates.values(), key=lambda x: x["rating"]):
print("{:>25} {:.3g}".format(r["cid"], 150+r["games"][-1]["rating"]))
if len(argv) > 1:
pp.pprint(rates[int(argv[1])])
#pp.pprint(coaches_by_uid)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,664 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/export.py | #!/usr/bin/env python3
import jinja2
from match import match
from team import team
from coach import coach
from stats.team_list import list_all_teams_by_points, list_all_games_by_race
from stats.match_list import list_all_matches, list_all_games_by_year
from stats.team_list import format_for_total, format_for_average
from . import coach_data
from . import index
from . import filter
import datetime
def get_template(template_name):
template_dir = 'template/'
loader = jinja2.FileSystemLoader(template_dir)
environment = jinja2.Environment(loader=loader)
environment.globals["basehref"] = "/"
environment.globals["baseurl"] = "http://www.anarchy.bloodbowlleague.com/"
environment.globals["league_name_short"] = "AnBBL"
filter.load_filter(environment)
return environment.get_template(template_name)
def write_html(data, filename):
with open("output/{}.html".format(filename), "w") as fp:
fp.write(data)
#def write_data(data, filename):
#write_html(data, filename)
def main():
import stats.collate
collated_data = stats.collate.collate()
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,665 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/race_data.py | #!/usr/bin/env python3
import logging
from team import team
from stats.team_list import list_all_teams_by_points, list_all_games_by_race
from stats.match_list import list_all_matches, list_all_games_by_year
from stats.team_list import format_for_total, format_for_average
from stats import match_list
import stats.elo
import export.filter
from . import export
LOG = logging.getLogger(__package__)
def add_title(races):
LOG.debug("add_title")
for race in races:
group={}
group["data"] = race
group["data"]["total"] = race
group["title"] = race["race"]
group["link"] = export.filter.race_link(race["teamid"])
yield group
def all_games_by_race(data=None):
LOG.debug("all_games_by_race")
elo_rating = stats.elo.rate_all(data, lambda v, y: v[y+"_race"])
rated_race = list(add_title(list_all_games_by_race(data, no_mirror=True)))
for r in rated_race:
race_name = r["title"][0:r["title"].find("(")].strip()
r["data"]["elo"] = "{:.2f}".format(150+elo_rating[race_name]["games"][-1]["rating"])
return export.get_template("race/races.html").render(
show_elo = True,
teams = rated_race,
teams_in_need = rated_race,
title="All races",
subtitle="sorted by performance")
def all_teams_for_race(race, race_teams, performance_by_race):
LOG.debug("All %s teams %s", race, len(race_teams))
return export.get_template("race/teams-for-race.html").render(
teams_average = format_for_average(race_teams),
teams_total = format_for_total(race_teams),
teams = race_teams,
games_by_race = performance_by_race,
title="All {} teams".format(race),
subtitle="sorted by points")
def teams_by_race(data):
LOG.debug("teams_by_race")
race = team.list_race(data)
teams = list_all_teams_by_points(data)
for r in race:
team_race = filter(lambda x: x["race"] == r, teams)
race_games = match_list.we_are_race(data["game"].values(), r)
race_games = list(filter(lambda m: m["away_race"] != r, race_games))
LOG.debug("race_games length is %s", len(race_games))
performance_by_race = match_list.sum_game_by_group(race_games, match_list.group_games_by_race)
with open("output/race/{}.html".format(r.replace(" ","-")), "w") as fp:
fp.write(all_teams_for_race(r, list(team_race), performance_by_race))
def export_race_by_performance(data = None):
with open("output/races.html", "w") as matches:
matches.write(all_games_by_race(data))
def main():
import stats.collate
collated_data = stats.collate.collate()
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.info("Exporting races by performance")
with open("output/races.html", "w") as matches:
matches.write(all_games_by_race(collated_data))
print("Exporting teams by race")
teams_by_race(collated_data)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,666 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/bblparser/tests/test_models.py | from bblparser.models import Link
def test_link_get_link_return_str():
assert Link(href=None, onclick=None, text='Heading').get_link() is None
onclick_link = "self.location.href='?p=rs&s=34';"
assert 'the_base+?p=rs&s=34' == Link(href=None, onclick=onclick_link, text='Heading').get_link(base='the_base+')
assert 'the_base+default.asp?p=tm&t=roy2' == Link(href='default.asp?p=tm&t=roy2', onclick=None, text='Heading').get_link(base='the_base+')
assert 'the_base+this_link' == Link(href='this_link', onclick='not_this_link', text='not_this_text').get_link(base='the_base+')
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,667 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/parse.py | #!/usr/bin/env python
""" Parse match from HTML """
import re
import sys
import logging
import dateutil.parser as parser
import bs4
LOG = logging.getLogger(__package__)
def id_from_a(a):
if a.has_attr("href"):
return a["href"][a["href"].rfind("=") + 1:]
if a.parent and a.parent.has_attr("href"):
return a.parent["href"][a.parent["href"].rfind("=") + 1:]
return "teamid not found {}".format(a.name)
def parse_team(prefix, team):
team = {prefix+"team": team.text,
prefix+"teamid": id_from_a(team)}
return team
def convert_to_isodate(text):
return parser.parse(text).isoformat()
def parse_date(soup):
LOG.debug("Parsing date")
found = soup.find_all("div")
LOG.debug("Found {} potential divs".format(len(found)))
for div in found:
if "Result added" in div.text:
LOG.debug("Found Result added")
found_date = convert_to_isodate(div.text.strip()[13:])
LOG.debug("Match date is %s", found_date)
return found_date
LOG.debug("Did not find date location.")
return None
def parse_score(scoreboard):
touchdowns = scoreboard.select("br")
return len(touchdowns)
def parse_scoreboardelement(el):
if el == "mercenary / star":
return "*"
elif el.has_attr("href") and el["href"].startswith("default.asp?p=pl&pid="):
return int(el["href"][el["href"].rfind("=") + 1:])
return el.has_attr("href")
def parse_scoreboard(scoreboard):
LOG.debug("Parsing scoreboard")
td = []
for c in list(scoreboard.children):
LOG.debug("Found {}".format(c))
if type(c) == bs4.NavigableString:
LOG.debug("NavigatableString")
continue
el = parse_scoreboardelement(c)
LOG.debug("scoreboard el {}".format(el))
if el:
td.append(el)
return td
def parse_td(soup):
scoreboard = soup.select('tr[style="background-color:#f4fff4"] td')
return {"home": parse_scoreboard(scoreboard[0]),
"away": parse_scoreboard(scoreboard[2])}
def parse_casualtyspp(soup):
return {"home": [],
"away": [],
}
def parse_injury_column(column):
LOG.debug("injury el {}".format(column))
return parse_scoreboard(column)
def parse_injury_row(soup, search):
LOG.debug("Searching for {}".format(search))
found = soup.select(search)
LOG.debug("found len %s", len(found))
injuries = []
for row in found:
LOG.debug("row el %s", row)
injuries.extend(parse_injury_column(row.select("td")[0]))
LOG.debug("injury type: %s", row.select("td")[1].text)
injuries.extend(parse_injury_column(row.select("td")[2]))
return [injured for injured in injuries if injured]
def parse_injuries(soup):
LOG.debug("INJURIES")
dead = parse_injury_row(soup, "tr[style='background-color:#f4d2d2']")
mng = parse_injury_row(soup, "tr[style='background-color:#f2e2da']")
niggle = parse_injury_row(soup, "tr[style='background-color:#f0d8d4']")
return {"dead": dead,
"seriousinjuries": mng + niggle}
def parse_spp(soup):
td = parse_td(soup)
cas = parse_casualtyspp(soup)
return {"td": td,
"cas": cas, }
def find_score(soup):
scoreboard = soup.select('tr[style="background-color:#f4fff4"]')[0]
return {"home": parse_score(scoreboard.select(".td10")[0]), "away": parse_score(scoreboard.select(".td10")[1])}
def parse_casualties(soup):
LOG.debug(str(soup.select(".td10")[0]))
home = len(soup.select(".td10")[0].select("br"))
away = len(soup.select(".td10")[1].select("br"))
return {"home": home, "away": away}
def find_casualties(soup):
bh = parse_casualties(soup.select('tr[style="background-color:#fcfcf0"]')[0])
si = parse_casualties(soup.select('tr[style="background-color:#fff9f0"]')[0])
de = parse_casualties(soup.select('tr[style="background-color:#fff4f4"]')[0])
home = bh["home"] + si["home"] + de["home"]
away = bh["away"] + si["away"] + de["away"]
return {"home_cas": home, "home_bh": bh["home"], "home_si": si["home"], "home_dead": de["home"],
"away_cas": away, "away_bh": bh["away"], "away_si": si["away"], "away_dead": de["away"]}
def find_hometeam(soup):
# print("[[[{}]]]".format(soup.find_all("b")[2].parent))
return parse_team("home_", soup.find_all("b")[2])
def find_awayteam(soup):
el = soup.findAll("td", {"width": "180"})
return parse_team("away_", el[1].select_one("a"))
def parse_season(soup):
season = soup.select_one("td[valign=top] div[align=center] b")
season_name, round_name = season.text.split(",", 1)
season_id = season.select_one("a")["href"].split("=")[-1] if season.select_one("a") else None
return {"tournament_id": season_id, "tournament_name": season_name.strip(), "round": round_name.strip()}
def parse_notes(soup):
LOG.debug("parsing notes")
notes = soup.select_one("td[style='width:460px;text-align:justify;']")
LOG.debug("notes len %s", len(notes.text) if notes else "Not found!")
return notes.text.replace('\xa0', ' ')
def parse_match(matchid, soup):
def calculate_result(us, them):
if us > them:
return "W"
elif us < them:
return "L"
return "T"
LOG.debug("Parse match {}".format(matchid))
if not soup.findAll("h1", text="Match result"):
return False
game_date = parse_date(soup)
if not game_date:
LOG.warning("No game_date in file with match id: %s", matchid)
match = {"approved": False}
match.update(find_hometeam(soup))
match.update(find_awayteam(soup))
return match
td_home = find_score(soup)["home"]
td_away = find_score(soup)["away"]
match = {"matchid": matchid,
"date": game_date,
"approved": True,
"home_td": find_score(soup)["home"],
"home_result": calculate_result(td_home, td_away),
"away_td": td_away,
"away_result": calculate_result(td_away, td_home),
"spp": parse_spp(soup),
"injuries": parse_injuries(soup),
"notes": parse_notes(soup)
}
match.update(find_hometeam(soup))
match.update(find_awayteam(soup))
match.update(find_casualties(soup))
match.update(parse_season(soup))
return match
def parse_matchdata(data):
coach = re.findall('coach[12]: \d*', data)
matchdata = {
"coach1": coach[0][7:].strip(),
"coach2": coach[1][7:].strip()}
return matchdata
def load_from_file(filename):
import match.load as loader
LOG.info("Parsing {}".format(filename))
match_id = filename[filename.find("match-") + 6:filename.rfind(".html")]
LOG.debug("match_id: {}".format(match_id))
match = parse_match(match_id, loader.from_file(filename))
return match
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
import pprint
pp = pprint.PrettyPrinter(indent=2)
if len(sys.argv) != 2:
sys.exit("filename required")
filename = sys.argv[1]
match = load_from_file(filename)
pp.pprint(match)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,668 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/bblparser/page.py | import io
import logging
import pathlib
import typing
import sys
import bs4
from bblparser.models import Page, Link
import bblparser.load
LOG = logging.getLogger(__name__)
def _parse_link(el: bs4.element.Tag) -> Link:
onclick = el.get('onclick') if el.has_attr('onclick') else None
return Link(text=el.text, href=None, onclick=onclick)
def parse_menu(soup: bs4.BeautifulSoup) -> typing.List[bblparser.models.Link]:
return [_parse_link(link) for link in soup.select('td.menu')]
def parse(html: str) -> bblparser.models.Page:
soup = bs4.BeautifulSoup(html, 'lxml')
if soup:
return Page(menu=parse_menu(soup=soup),
latest_matches=None,
latest_bulletins=None)
return None
def main():
import argparse
encoding = 'utf_8' if '--utf-8' in sys.argv else 'latin-1'
print(encoding)
arg_p = argparse.ArgumentParser()
arg_p.add_argument('documents', nargs='*', type=str, default=[sys.stdin], help="HTML code to parse")
arg_p.add_argument('--pprint', type=int, default=40, help="Pretty print parser result")
arg_p.add_argument('--utf-8', action='store_true', help="Use UTF-8 encoding. default is latin-1")
arg_p.add_argument('--json', action='store_true', help="JSON print parser result")
arguments = arg_p.parse_args()
result = [parse(d) for d in bblparser.load.load_documents(arguments.documents)]
if arguments.pprint > 0 or arguments.pprint == -1:
import pprint
if arguments.pprint > 0:
for p in result:
for l in p.menu:
pprint.pprint(l, indent=4)
else:
pprint.pprint(result)
return result, arguments
r = None
if __name__ == '__main__':
r = main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,669 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/match_list.py | #!/usr/bin/env python3
import dateutil
from operator import itemgetter
from copy import copy
import logging
import pprint
import sys
from match import match
LOG = logging.getLogger(__package__)
def game_streaks(games):
streaks = {}
streaks["gamestreak"] = playstreak(games)
streaks["winstreak"] = eventstreak(games,
event = lambda x: x["home_result"] == "W", minimum=2)
streaks["losstreak"] = eventstreak(games,
event = lambda x: x["home_result"] == "L", minimum=2)
streaks["tiestreak"] = eventstreak(games,
event = lambda x: x["home_result"] == "T", minimum=2)
streaks["nolosstreak"] = eventstreak(games,
event = lambda x: x["home_result"] == "T" or x["home_result"] == "W",
minimum=streaks["winstreak"]+1)
streaks["killstreak"] = eventstreak(games,
event = lambda x: x["home_dead"] > 0, minimum=1)
streaks["wonby2"] = eventstreak(games,
event = lambda x: x["home_td"] - x["away_td"] > 1, minimum=3)
streaks["lostby2"] = eventstreak(games,
event = lambda x: x["home_td"] - x["away_td"] < -1, minimum=3)
streaks["didnotscore"] = eventstreak(games,
event = lambda x: x["home_td"] == 0, minimum=2)
streaks["shutoutstreak"] = eventstreak(games,
event = lambda x: x["away_td"] == 0, minimum=2)
return streaks
def eventstreak(games, event, minimum=0):
longest_streak = 0
current_streak = 0
for g in games:
if event(g):
current_streak = current_streak + 1
if current_streak > longest_streak:
longest_streak = current_streak
else:
current_streak = 0
if longest_streak < minimum:
return 0
return longest_streak
def favorite_day(games):
days = [0,0,0,0,0,0,0]
for g in games:
date = dateutil.parser.parse(g['date'])
days[date.weekday()] = days[date.weekday()] + 1
best_day = days.index(max(days))
days_of_week = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
return "{}".format(days_of_week[best_day])
def playstreak(games):
if len(games) < 1:
return None
best_score = {"count": 0, "days": 0 }
current_score = {"count": 1, "days": 1}
current_date = dateutil.parser.parse(games[0]["date"])
for g in games[1:]:
game_date = dateutil.parser.parse(g["date"])
days_between_games = (current_date - game_date).days
if days_between_games <= 1:
current_score["count"] = current_score["count"] + 1
if days_between_games == 1:
current_score["days"] = current_score["days"] + 1
if current_score["count"] > best_score["count"]:
best_score = current_score
if best_score["days"] == 0:
best_score["days"] = 1
else:
current_score = {"count": 1, "days": 1}
current_date=game_date
if best_score["count"] == 0 and best_score["days"] == 0:
return None
return best_score
def format_for_matchlist(match):
try:
return {"matchid": match["matchid"],
"date": match["date"].split("T")[0],
"repeated_date": False,
"home": match["home_team"],
"homeid": match["home_teamid"],
"awayid": match["away_teamid"],
"away": match["away_team"],
"td_home": match["home_td"],
"td_away": match["away_td"],
"cas_home": match["home_cas"],
"cas_away": match["away_cas"],
"season": match["tournament_name"],
"home_coach": match["home_coach"] if 'home_coach' in match else None,
"away_coach": match["away_coach"] if 'away_coach' in match else None
}
except KeyError as kerr:
print("Crashed on format_for_matchlist:", file=sys.stderr)
pprint.pprint(match, indent=2)
raise kerr
def games_for_year(games, year=None):
if not year:
return games
result = []
start = "{}-00-00".format(year)
end = "{}-99-99".format(year)
result = list(
filter(
lambda x: x["date"] > start and end > x["date"],
games))
#print("{} games".format(len(games)))
return result
def games_for_teams(data, games):
teams = {}
for g in games:
teamid = g["home_teamid"]
if teamid not in teams:
teams[teamid] = data["team"][teamid]
teams[teamid]["games"] = list(filter(lambda x: x["home_teamid"] == teamid, games))
total = sum_game(teams[teamid]["games"])
teams[teamid]["total"] = total["total"]
teams[teamid]["average"] = total["average"]
return teams
def sort_group_by_points(groups):
games_for_team = sorted(groups, key=lambda g: g["title"])
games_for_team = sorted(games_for_team, key=lambda g: g["data"]["total"]["cas_for"]+g["data"]["total"]["cas_against"], reverse=True)
games_for_team = sorted(games_for_team, key=lambda g: g["data"]["total"]["td_for"]+g["data"]["total"]["td_against"], reverse=True)
games_for_team = sorted(games_for_team, key=lambda g: g["data"]["total"]["win"], reverse=True)
games_for_team = sorted(games_for_team, key=lambda g: g["data"]["total"]["gamesplayed"])
games_for_team = sorted(games_for_team, key=lambda g: g["data"]["total"]["points"], reverse=True)
return games_for_team
def games_by_weekday(games):
games_by_weekday = sum_game_by_group(games, group_games_by_weekday)
for w in games_by_weekday:
w["order"] = w["title"]
w["title"] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"][w["title"]-1]
w["link"] = None
return sorted(games_by_weekday, key=lambda x: x["order"])
def group_games_by_weekday(games):
return group_games(lambda x: dateutil.parser.parse(x["date"]).isoweekday(), games)
def group_games_by_coach(games, who="away"):
return group_games(lambda x: x[who+"_coachid"], games)
def group_games_by_our_coach(games):
return group_games_by_coach(games, who="home")
def group_games_with_race(games, who="home"):
return group_games_by_race(games, who=who)
def group_games_by_race(games, who="away"):
by_race = group_games(lambda x: x[who+"_race"], games)
return by_race
def group_games(group, games):
result = {}
for g in games:
grp = group(g)
if grp not in result:
result[grp] = []
result[grp].append(g)
return result
def sum_game_by_group(games, grouping):
result = []
for rac, g in grouping(games).items():
result.append({"title": rac, "data": sum_game(g)})
return sort_group_by_points(result)
def sum_game(games):
total = {"gamesplayed": 0, "win":0, "tie":0, "loss": 0,
"td": 0,"td_for": 0, "td_against": 0,
"cas": 0, "cas_for": 0, "cas_against": 0, "dead_for": 0, "dead_against": 0,
"points": 0, "performance": 0 }
average = copy(total)
for g in games:
total["gamesplayed"] = total["gamesplayed"] + 1
total["td_for"] = total["td_for"] + g["home_td"]
total["td_against"] = total["td_against"] + g["away_td"]
total["cas_for"] = total["cas_for"] + g["home_cas"]
total["cas_against"] = total["cas_against"] + g["away_cas"]
total["dead_for"] = total["dead_for"] + g["home_dead"]
total["dead_against"] = total["dead_against"] + g["away_dead"]
if g["home_result"] == "W": total["win"] = total["win"] + 1
if g["home_result"] == "T": total["tie"] = total["tie"] + 1
if g["home_result"] == "L": total["loss"] = total["loss"] + 1
total["points"] = total["win"]*5 + total["tie"]*3 + total["loss"]
total["performance"] = 100 * ((total["win"]*2)+total["tie"])/(total["gamesplayed"]*2) if total["gamesplayed"] > 0 else 0
total["td"] = total["td_for"] - total["td_against"]
total["cas"] = total["cas_for"] - total["cas_against"]
if total["gamesplayed"] > 0:
average = {"gamesplayed": len(games)/total["gamesplayed"],
"win":total["win"] / total["gamesplayed"],
"tie":total["tie"] / total["gamesplayed"],
"loss": total["loss"] / total["gamesplayed"],
"td_for": total["td_for"] / total["gamesplayed"], "td_against": total["td_against"] / total["gamesplayed"],
"cas_for": total["cas_for"] / total["gamesplayed"], "cas_against": total["cas_against"] / total["gamesplayed"],
"dead_for": total["dead_for"] / total["gamesplayed"], "dead_against": total["dead_against"] / total["gamesplayed"],
"points": total["points"]/total["gamesplayed"], "performance": total["performance"] }
return {"total": total, "average": average}
def switch_homeaway(g):
result = {}
for k, v in g.items():
if k.startswith("home_"):
result["away"+k[4:]] = v
elif k.startswith("away_"):
result["home"+k[4:]] = v
else:
result[k] = v
return result
#TODO Fix we_are_team for flat
def we_are_team(games, team):
result = []
for g in games:
if g["home_teamid"] == team["id"]:
result.append(g)
elif g["away_teamid"] == team["id"]:
result.append(switch_homeaway(g))
return result
def we_are(games, what, what_away):
result = []
for g in games:
if what(g):
result.append(g)
elif what_away(g):
result.append(switch_homeaway(g))
return result
def we_are_race(games, race):
return we_are(games, lambda x: x["home_race"] == race, lambda x: x["away_race"] == race)
def we_are_coach(games, coach):
result = []
for g in games:
if g["home_coachid"] == coach["uid"]:
result.append(g)
elif g["away_coachid"] == coach["uid"]:
result.append(switch_homeaway(g))
return result
def list_all_matches(data=None):
matches = data["game"].values() if data else match.match_list()
formatted_matches = list(map(format_for_matchlist, matches))
return sorted(formatted_matches, key=itemgetter("date"), reverse=True)
def list_all_games_by_year(data, year):
start_date = "{}-99-99".format(year-1)
end_date = "{}-00-00".format(int(year)+1)
return list(filter(lambda x: x["date"] > start_date and x["date"] < end_date, data["game"].values()))
def print_list_all_matches():
for t in list_all_matches():
print(t)
def test_we_are_race():
from . import collate
all_matches = collate.collate()["game"].values()
matches = we_are_team(all_matches, {"id":"mot"})
LOG.debug("all_matches: %s, matches: %s", len(all_matches), len(matches))
for m in matches:
LOG.debug("print match %s", m["matchid"])
print("{} {}({}) {}({}) {}".format( m["home_td"], m["home_team"], m["home_race"], m["away_team"], m["away_race"], m["away_td"]))
def test_we_are_coach():
from . import collate
all_matches = collate.collate()["game"].values()
matches = we_are_coach(all_matches, {"uid": "71", "nick": "Kyrre"})
LOG.debug("all_matches: %s, matches: %s", len(all_matches), len(matches))
for m in matches:
LOG.debug("print match %s", m["matchid"])
print("{} {} {} {}".format( m["home_td"], m["home_team"], m["away_team"], m["away_td"]))
def main():
import sys
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
if "--we-are-coach" in sys.argv:
test_we_are_coach()
elif "--we-are-race" in sys.argv:
test_we_are_race()
else:
print_list_all_matches()
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,670 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/team/parse.py | #!/usr/bin/env python
from bs4 import BeautifulSoup
from unicodedata import normalize
import re
import logging
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def find_rows(soup):
LOG.debug("Find rows")
teams = []
rows = soup.find_all("tr")
LOG.debug("Found {} rows".format(len(rows)))
for row in rows:
if row.has_attr("height") and row['height'] == "30":
teams.append(row)
LOG.debug("Returning {} teams".format(len(teams)))
return teams
def id_from_onclick(el):
if el.has_attr("onclick") and el["onclick"].startswith("self.location.href='default.asp?p=tm&t="):
oncl = el["onclick"]
return re.sub(r'\W+', '', oncl[el["onclick"].rfind("=") + 1:])
return None
def parse_id(row):
id_from_row = id_from_onclick(row)
if id_from_row:
return id_from_row
columns = row.find_all("td")
for column in columns:
teamid = id_from_onclick(column)
if teamid != None:
return teamid
def parse_name(row):
return row.find("b").text
def parse_race(row):
return row.find_all(lambda tag: tag.name == "td" and tag.get('class') == ['td10'])[0].text
def parse_teamvalue(row):
teamvalue = row.find_all(lambda tag: tag.name == "td" and tag.get('class') == ['td10'])[2].text.replace('\xa0',
'').replace(
"k", "000")
try:
return int(teamvalue) # if teamvalue !="" else None
except ValueError:
return None
def parse_cocoach(row):
LOG.debug("Parsing co-coach")
column = row.find_all(lambda tag: tag.name == "td" and tag.get('class') == ['td10'])[1].text
LOG.debug(column)
co_coach_name = column.split("&")[1] if len(column.split("&")) == 2 else None
return co_coach_name
def parse_coach(row):
LOG.debug("Parsing coach")
column = row.find_all(lambda tag: tag.name == "td" and tag.get('class') == ['td10'])[1].text
LOG.debug(column)
coach_name = column.split("&")[0] if column != "?" else None
return coach_name
def parse_team_row(row):
LOG.debug("Parse team row {}".format(row))
team_id = parse_id(row)
name = parse_name(row)
coach_name = parse_coach(row)
co_coach_name = parse_cocoach(row)
race = parse_race(row)
team_value = parse_teamvalue(row)
return {"id": team_id,
"name": name,
"coach": coach_name,
"co-coach": co_coach_name,
"race": race,
"teamvalue": team_value}
def parse_rows(rows_of_teams):
teams = []
for row in rows_of_teams:
teams.append(parse_team_row(row))
return teams
def dict_teams():
teams = list_teams()
result = {}
for team in teams:
result[team["id"]] = team
return result
def list_teams(basepath = BASEPATH):
filepath = basepath + "html/team/teams-8.html"
LOG.info("list teams from %s ", filepath)
html = open(filepath, "r").read()
soup = BeautifulSoup(normalize("NFC", html), "html.parser")
teams = parse_rows(find_rows(soup))
return teams
def main():
import sys
import pprint
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.info("Parsing teamlist")
teams = list_teams(sys.argv[1] if len(sys.argv) > 1 else BASEPATH)
if "--no-print" not in sys.argv:
pprint.PrettyPrinter().pprint(teams)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,671 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/tournament/pairing.py | #!/usr/bin/env python
""" Match teams for round """
import sys
import logging
LOG = logging.getLogger(__package__)
def pairing(standings, matches, type="swiss"):
if not standings:
raise ValueError("standings are None or empty")
return swiss_pairing(standings, matches)
def match_played(home_team, away_team, matches):
for match in matches:
print("match played {}-{} {}".format(home_team["teamid"], away_team["teamid"], match))
if match["home_team"]["teamid"] == home_team["teamid"] and match["away_team"]["teamid"] == away_team["teamid"]:
print("TRUE")
return True
if match["away_team"]["teamid"] == home_team["teamid"] and match["home_team"]["teamid"] == away_team["teamid"]:
print("TRUE")
return True
print("FALSE")
return False
def find_opponent(home_team, teams, matches):
if not matches:
return teams.pop(0)
for index, team in enumerate(teams):
if not match_played(home_team, teams[index], matches):
return teams.pop(index)
return None
def swiss_pairing(standings, played_matches):
matches = []
teams = standings[:]
while len(teams):
home_team = teams.pop(0)
away_team = find_opponent(home_team, teams, played_matches)
matches.append({"home_team": home_team,
"away_team": away_team})
import pprint
pprint.pprint(matches)
return matches
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
if __name__ == "__main__":
main() | {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,672 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/team/create.py | #!/usr/bin/env python
""" Create new team """
import sys
import logging
import scrape.session
LOG = logging.getLogger(__package__)
def create_team(team_name, race, coach, co_coach, session):
LOG.debug("Creating team '%s' '%s' '%s' '%s'", team_name, race, coach, co_coach)
team_form = {"coach": coach,
"coach2": co_coach,
"race": race,
"navn": team_name,
"rr": 0,
"ff": 0}
response = session.post("http://test.bloodbowlleague.com/default.asp?p=nt", data=team_form)
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
if len(sys.argv) < 3:
sys.exit("username password team_name")
s = scrape.session.login("http://test.bloodbowlleague.com/login.asp", username=sys.argv[1], password=sys.argv[2])
team_name=" ".join(sys.argv[3:])
team_race="5"
coach="Ketil"
co_coach=""
if s:
LOG.debug("Session seems OK")
else:
sys.exit("session not ok?")
create_team(team_name, team_race, coach, co_coach, s)
if __name__ == "__main__":
main() | {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,673 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/scrape/fetchplayer.py | #!/bin/env python3
import sys
import requests
import os.path
from time import sleep
import scrape.session
from importer.bbleague.defaults import BASEPATH
base_url = "https://www.anarchy.bloodbowlleague.net/default.asp?p=pl&pid={}"
admin_url = "https://www.anarchy.bloodbowlleague.net/default.asp?p=pladm&pid={}"
def download_all_players(fetch_list):
s = scrape.session.login("https://www.anarchy.bloodbowlleague.net/login.asp", sys.argv[1], sys.argv[2])
for playerid in fetch_list:
if scrape.session.download_to(s, admin_url.format(playerid), os.path.join(BASEPATH, "html/player/","admin-player-{}.html".format(playerid))):
sleep(2)
scrape.session.download_to(s, base_url.format(playerid), os.path.join(BASEPATH, "html/player/", "player-{}.html".format(playerid)))
sleep(5)
def main():
fetch_list = sys.argv[3:] if len(sys.argv) > 3 else range(5, 3535)
download_all_players(fetch_list)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,674 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/team_data.py | #!/usr/bin/env python3
from match import match
from stats import team_list
from stats import match_list
from stats import coach_list
from export import export, coach_data, race_data
from team import team
from export import index
import datetime
#coach = coach_list.coach_data(coach, coach_games),
def team_stats(data, teams, games, the_team):
#team_data = coach_list.coach_data(the_team, data)
games_for_team = match_list.we_are_team(list(data["game"].values()), the_team)
games_for_team = sorted(games_for_team, key=lambda g: int(g["matchid"]), reverse=True)
games_for_team = sorted(games_for_team, key=lambda g: g["date"], reverse=True)
game_total = match_list.sum_game(games_for_team)
streaks = match_list.game_streaks(games_for_team)
games_by_race = match_list.sum_game_by_group(games_for_team, match_list.group_games_by_race)
games_by_our_coach = match_list.sum_game_by_group(games_for_team, match_list.group_games_by_our_coach)
#FIXME, improve nick lookup
for c in games_by_our_coach:
if c["title"] in data["_coachid"]:
c["title"] = data["_coachid"][c["title"]]["nick"]
c["link"] = "/coach/{}.html".format(c["title"].replace(" ","-"))
else:
c["title"] = "Unknown {}".format(c["title"])
c["link"] = "/coaches.html"
export.write_html(export.get_template("team/team.html").render(
team_data = team_list.team_data(the_team, games_for_team),
stats_average = game_total["average"],
stats_total = game_total["total"],
matches=games_for_team,
games_by_race = games_by_race,
games_by_our_coach = games_by_our_coach,
show_coaches = len(games_by_our_coach) > 1,
coaches=data["coach"],
streaks = streaks,
teamname = the_team["name"],
teamid = the_team["id"],
title="{}".format(the_team["name"],
subtitle="sorted by date")),
"team/{}".format(the_team["id"]))
def all_games_by_team(data):
teams = data["team"].values()
games = data["game"].values()
for t in teams:
team_stats(data, teams, games, t)
def all_teams_by_year(data, year):
teams = team_list.list_all_teams_by_year(year)
return export.get_template("team/all_team.html").render(
teams_average = team_list.format_for_average(teams),
teams_total = team_list.format_for_total(teams),
teams =teams,
title="All teams in {}".format(year),
subtitle="sorted by points")
def all_teams(data):
teams = team_list.list_all_teams_by_points(data=data)
return export.get_template("team/all_team.html").render(
teams_average = team_list.format_for_average(teams),
teams_total = team_list.format_for_total(teams),
teams = team_list.list_all_teams_by_points(),
title="All teams",
subtitle="sorted by points")
def teams_by_year(data, start, end):
for year in range(start, end):
with open("output/team-{}.html".format(year), "w") as teams:
teams.write(all_teams_by_year(data, year))
def export_all_teams(data):
with open("output/team.html", "w") as teams:
teams.write(all_teams(data))
def main():
import stats.collate
collated_data = stats.collate.collate()
print("Exporting all teams")
all_games_by_team(collated_data)
print("Exporting teams by points")
with open("output/team.html", "w") as teams:
teams.write(all_teams(collated_data))
print("Exporting teams by year")
teams_by_year(collated_data, 2007, datetime.datetime.now().year+1)
#index.index()
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,675 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate_test.py | #!/usr/bin/python3
import pprint
import stats.collate
import sys
def pretty(value):
pprint.pprint(value, indent=2)
def match_sans_coach(data):
no_coachid = [match["matchid"] for match in data["game"].values() if match["away_coachid"] in ["-1", 0, -1, "0", None] or match["home_coachid"] in ["0","-1", 0, -1, None]]
print("{}\ncount: {}".format(sorted(no_coachid, key=lambda x: int(x)), len(no_coachid)))
def main():
data = stats.collate.collate()
print([[key, len(data[key])] for key in data.keys()])
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,676 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/team/fetch-team.py | #!/bin/env python3
import urllib.request
from urllib.error import HTTPError
from time import sleep
base_url = "http://www.anarchy.bloodbowlleague.com/default.asp?p=pl&pid={}"
for playerid in range(5, 3341):
print(base_url.format(playerid))
try:
with urllib.request.urlopen(base_url.format(playerid)) as respons:
html = respons.readlines()
open("output/player-{}.html".format(playerid), "wb").writelines(html)
print("wrote file")
except HTTPError as e:
html = e.readlines()
open("output/player-{}.html".format(playerid), "wb").writelines(html)
print("wrote 500 file")
sleep(10)
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,677 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/coach/parse.py | #!/usr/bin/env python
import sys
import os.path
import logging
from bs4 import BeautifulSoup
from unicodedata import normalize
import datetime
from importer.bbleague.defaults import BASEPATH
#import dateutil.parser as parser
NEVER_LOGGED_IN = "2000-01-01T00:00:01"
LOG = logging.getLogger(__package__)
def find_rows(soup):
coaches = []
rows = soup.find_all("tr")
LOG.debug("Found %s rows", len(rows))
for row in rows:
if row.has_attr("height") and row['height'] == "27":
coaches.append(row)
return coaches
def parse_email(row):
found = row.find_all("a")
for a in found:
if a.has_attr("href") and a["href"].startswith("mailto"):
return a.text
return "Found no email"
def parse_nick(row):
found = row.find_all("td")
for td in found:
if td.has_attr("style") and td["style"]=="border-top:1px solid #808080;color:#203040":
return td.find("b").text
return "Found no nick"
def parse_uid(row):
found = row.select("div.divbutton")
for div in found:
if div.has_attr("onclick"):
onclick = div["onclick"]
return onclick.split("&")[1][4:]
def parse_naf(row):
found = row.find_all("div")
for div in found:
if div.text.startswith("NAF#:"):
return div.text[6:]
def parse_role(row):
return row.select('td[align="center"]')[1].text
def parse_phone(row):
return row.select('td[align="center"]')[2].contents[0]
def parse_location(row):
column = row.select('td[align="center"]')[2].contents
return column[2] if len(column) > 2 else "Old World"
def parse_date(row):
style_search="border-top:1px solid #808080;color:#404040;padding-top:3px;padding-bottom:1px"
found = row.find_all("td")
for td in found:
if td.has_attr("style") and td["style"]==style_search:
text = td.text.split("\xa0")[0]
if text == "never logged in":
return NEVER_LOGGED_IN
clock = "00:00:00"
year = "{}".format(datetime.datetime.now().year)
if text.find("-")>0:
clock = text.split("-")[1].strip()
text = text.split("-")[0]
if len(text.split("/")) == 3:
year = text.split("/")[2]
return "{}-{}-{}T{}".format(year, text.split("/")[1].strip().zfill(2), text.split("/")[0].strip().zfill(2), clock)
return "Found no date"
def parse_coach_row(row):
coach = {'nick': parse_nick(row),
'email': parse_email(row),
'naf': parse_naf(row),
'role': parse_role(row),
'phone': parse_phone(row),
'location': parse_location(row),
'login': parse_date(row),
'loggedin': False,
'uid': parse_uid(row)}
if(coach["login"] != NEVER_LOGGED_IN):
coach["loggedin"] = True
parse_uid(row)
return coach
def parse_rows(rows_of_coaches):
coaches = []
for row in rows_of_coaches:
coaches.append(parse_coach_row(row))
return coaches
def data_exists(basepath = BASEPATH):
file_path = basepath + "html/coach/coaches-8.html"
exists = os.path.isfile(file_path)
LOG.debug("%s that %s isfile", exists, file_path)
return exists
def load(basepath = BASEPATH):
filepath = basepath + "html/coach/coaches-8.html"
LOG.debug("Opening file %s", filepath)
LOG.debug("exists: %s", os.path.isfile(filepath))
html = open(filepath, "r").read()
soup = BeautifulSoup(normalize("NFC", html), "lxml")
#print(soup)
coaches = parse_rows(find_rows(soup))
return coaches
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
basepath = sys.argv[1] if len(sys.argv) > 1 else BASEPATH
coaches = load(basepath)
for coach in coaches:
print(coach)
print("Total: {}".format(len(coaches)))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,678 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/team/team.py | #!/usr/bin/env python
from bs4 import BeautifulSoup
from unicodedata import normalize
import datetime
import re
from . import parse
import collections
from importer.bbleague.defaults import BASEPATH
def dict_teams():
teams = list_teams()
result = {}
for team in teams:
result[team["id"]] = team
return result
def list_teams(basepath = BASEPATH):
html = open(BASEPATH + "html/team/teams-8.html", "r").read()
soup = BeautifulSoup(normalize("NFC", html), "html.parser")
teams = parse.parse_rows( parse.find_rows(soup))
return teams
def list_race(collated_data=None):
race = collections.defaultdict(set)
teams = list_teams() if collated_data==None else collated_data["team"].values()
for t in teams:
race[t["race"]].add(t["id"])
return race
#Fix me. merge list_race, filter_race
def filter_race(collated_data):
race = collections.defaultdict(set)
for teamid, team in collated_data["team"].items():
print(team)
race[team["race"]].add(team["id"])
return race
def main():
import sys
import pprint
for t in list_teams():
if len(sys.argv) < 2 or t["id"] in sys.argv[1:]:
pprint.pprint(t, indent=4, width=200)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,679 | ketilkn/bloodbowl-utility | refs/heads/master | /skills/skills-html.py | #!/bin/env python3
linjer = open("skills.txt", "r").readlines()
skill = {}
skills = []
for linje in linjer:
if not linje.strip():
skills.append(skill)
skill = None
continue
elif not skill:
title = linje[0: linje.find("(")].strip()
id = title.strip().replace(" ", "-").lower()
category = linje[linje.find("(")+1: -2].lower()
skill = {'id': id, 'title': title, 'category': category, 'text': ""}
else:
skill['text'] = skill['text'] + linje.replace("\n"," ")
for skill in skills:
print("<article class='{}' id='{}'><h2>{}</h2>{}<p>{}</p></article>".format(skill['category'], skill['id'], skill['title'], skill['category'], skill['text']))
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,680 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/importer/bbleague/__main__.py | #!/usr/bin/env python
""" default functionality for bbleague importer """
import sys
import logging
import argparse
import importer.bbleague.update
LOG = logging.getLogger(__package__)
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG if "--debug" in sys.argv else logging.INFO, format=log_format)
argparser = argparse.ArgumentParser()
argparser.add_argument("function", choices=["update", "initialize", "collate"], help="update")
argparser.add_argument("site", help="[Site] from bbl-scrape.ini")
argparser.add_argument("--debug", action="store_true", help="")
args = argparser.parse_args()
section = "test" if len(sys.argv) < 2 else sys.argv[1]
config = importer.bbleague.update.load_config(args.site)
if args.function == "update":
importer.bbleague.update.import_bbleague(config)
else:
print("Nothing to do with {}".format(args.function))
if __name__ == "__main__":
main() | {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,681 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/tournament/parse.py | #!/usr/bin/env python
import sys
from bs4 import BeautifulSoup
import logging
def id_from_onclick(el):
if el and el.has_attr("onclick"):
return el["onclick"][el["onclick"].find("'")+1:el["onclick"].rfind("'")]
return "teamid not found {}".format(el.name)
def parse_team(team):
team_name = team
team = { "name": team_name.text.replace(u"\xa0", ' '),
"teamid": id_from_onclick(team_name) }
return team
def parse_standings(soup):
standings = []
for position, found in enumerate(soup.select('tr td[style="color:#203040"]')):
team = parse_team(found)
team["position"]=position+1
standings.append(team)
return standings
def open_standings(filename):
html = open(filename, "rb").read()
soup = BeautifulSoup(html, "html.parser")
league = parse_standings(soup)
return league
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
tournament = open_standings(sys.argv[1])
for t in tournament:
print(t)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,682 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/bblparser/load.py | import logging
import pathlib
import sys
import typing
LOG = logging.getLogger(__name__)
def load_raw(file_no) -> str:
with open(file_no, mode='rb', closefd=False) as f:
raw_input = f.read()
try:
return raw_input.decode('utf-8')
except UnicodeDecodeError:
return raw_input.decode('latin1')
def load_file(filename) -> str:
the_path = pathlib.Path(filename)
if the_path.is_file():
with open(the_path, 'r') as f:
return load_raw(f.fileno())
def load_document(document) -> str:
if document == sys.stdin:
return load_raw(sys.stdin.fileno())
else:
return load_file(document)
def load_documents(documents) -> typing.Generator[str, None, None]:
for document in documents:
yield load_document(document)
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,683 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/importer/bbleague/defaults.py | #!/usr/bin/env python
""" Default values for bloodbowlleague importerer """
import logging
LOG = logging.getLogger(__package__)
BASEPATH = "input/anarchy.bloodbowlleague.com/"
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
if __name__ == "__main__":
main() | {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,684 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/player_data.py | #!/usr/bin/env python3
import datetime
import os
import logging
import export.filter
import stats.player_list
from . import export
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def make_top_list(players, name, key, heading="Most experienced", order=stats.player_list.order_by_spp, limit=5):
return {"name": name,
"key": key,
"heading": heading,
"players": list(stats.player_list.flatten_players(order(players)))[:limit]}
def players_by_position(data, position):
LOG.debug("%s players in data", len(data["player"]) if "player" in data else "No")
players = [p for p in stats.player_list.all_players(data) if p["position"] == position]
players = stats.player_list.flatten_players(players)
return export.get_template("player/player_position.html").render(
players = list(players),
hide_position = False,
hide_team = False,
title=position,
subtitle="")
def top_players(data=None):
LOG.debug("%s players in data", len(data["player"]) if "player" in data else "No")
players = stats.player_list.all_players(data)
top_by_touchdown = make_top_list(players, "TDs", "td", "Top scorers", stats.player_list.order_by_touchdowns)
top_by_completion = make_top_list(players, "passes", "cmp", "Top throwers", stats.player_list.order_by_completion)
top_by_casualties = make_top_list(players, "cas", "cas", "Top hitters", stats.player_list.order_by_casualties)
top_by_mvp = make_top_list(players, "mvp", "mvp", "Top MVPs", stats.player_list.order_by_mvp)
top_by_interception = make_top_list(players, "int", "int", "Top interceptors", stats.player_list.order_by_interception)
top_by_spp = make_top_list(players, "spp", "spp", "Top stars", stats.player_list.order_by_spp, limit=14)
top_by_value = make_top_list(players, "gp", "value", "Most expensive", stats.player_list.order_by_value)
toplists = [top_by_spp, top_by_value,
top_by_touchdown,
top_by_mvp,
top_by_completion,
top_by_interception,
top_by_casualties]
return export.get_template("player/players.html").render(
toplists = toplists,
title="All time top players",
subtitle="")
def get_players_modification_date():
try:
return datetime.datetime.fromtimestamp(os.path.getmtime('input/anarchy.bloodbowlleague.com/json/players.json')).strftime("%Y-%m-%d")
except:
return "?"
def all_player(data=None):
LOG.debug("%s players in data", len(data["player"]) if "player" in data else "No")
players = stats.player_list.flatten_players(stats.player_list.all_players(data))
players_updated = get_players_modification_date()
return export.get_template("player/all_player.html").render(
players = list(players),
players_updated = players_updated,
hide_position = False,
hide_team = False,
title="All players",
subtitle="sorted by star player points")
def export_race_by_performance(data = None):
with open("output/races.html", "w") as matches:
matches.write(stats.player_list.all_games_by_race(data))
def all_players(collated_data):
LOG.info("Exporting top players index")
with open("output/players.html", "w") as all_players_file:
all_players_file.write(top_players(collated_data))
LOG.info("Exporting all players")
with open("output/all_players.html", "w") as all_players_file:
all_players_file.write(all_player(collated_data))
all_position(collated_data)
def all_position(collated_data):
LOG.info("Exporting all players by position")
for position in stats.player_list.all_positions(collated_data):
filename = position.replace(" ", "-")
with open("output/player/{}.html".format(filename), "w") as all_players_file:
all_players_file.write(players_by_position(collated_data, position))
def main():
import stats.collate
collated_data = stats.collate.collate()
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
all_players(collated_data)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,685 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/fetch.py | #!/bin/env python3
"""fetch all games from anarchy blood bowl league"""
import os.path
import sys
import urllib.request
from urllib.error import HTTPError
from time import sleep
from bs4 import BeautifulSoup
import logging
from importer.bbleague.defaults import BASEPATH
BASE_URL = "{}/default.asp?p=m&m={}"
DATA_URL = "{}/matchdata.asp?m={}"
LOG = logging.getLogger(__package__)
def parse_index(basepath=BASEPATH):
result = set()
with open(os.path.join(basepath, "html", "index.html"), "rb") as index_file:
soup = BeautifulSoup(index_file.read(), 'html.parser')
for anchor in soup.find_all('a'):
if anchor.has_attr("href") and anchor["href"].startswith("default.asp?p=m&m="):
href = anchor["href"]
result.add(href[href.rfind("=")+1:])
return result
def new_games(base_path=BASEPATH, base_url="http://www.anarchy.bloodbowlleague.com/"):
download_to(base_url, os.path.join(base_path, "html", "index.html"))
return parse_index(base_path)
def download_to(url, target):
"""Download match with url to target path"""
try:
with urllib.request.urlopen(url) as response:
if response.geturl() == url:
html = response.readlines()
try:
open(target, "wb").writelines(html)
LOG.debug(" Wrote {} to {}".format(url, target))
except OSError:
LOG.error(" Failed writing {} to {}".format(url, target))
else:
LOG.error(" Server redirect {} to {}".format(url, response.geturl()))
except HTTPError as error:
html = error.readlines()
open(target, "wb").writelines(html)
LOG.warning(" Server error {} to {}".format(url, target))
def download_match(matchid, directory=BASEPATH, base_url="http://www.anarchy.bloodbowlleague.net"):
download_to(DATA_URL.format(base_url, matchid), os.path.join(directory, "html/match/", "matchdata-{}.html".format(matchid)))
sleep(1)
download_to(BASE_URL.format(base_url, matchid), os.path.join(directory, "html/match/", "match-{}.html".format(matchid)))
sleep(3)
def is_match_downloaded(matchid, directory=BASEPATH+"html/match/"):
return os.path.isfile(os.path.join(directory, "matchdata-{}.html".format(matchid))) \
and os.path.isfile(os.path.join(directory, "match-{}.html".format(matchid)))
def download_matches(basepath, from_match, to_match, force=True):
download_matches2(base_path=basepath, games=list(range(from_match, to_match)), force=force)
def force_download():
return "--force" in sys.argv
def download_matches2(base_url="http://www.anarchy.bloodbowlleague.com/", base_path=BASEPATH, force=force_download(), games=[]):
target_path = os.path.join(base_path, "match")
if not os.path.isdir(target_path):
LOG.warning("Target path %s does not exist. Attempting to create", target_path)
os.makedirs(target_path)
for g in games:
if not is_match_downloaded(g, base_path) or force:
LOG.info("Downloading match {}".format(g))
download_match(g, directory=base_path, base_url=base_url)
else:
LOG.debug("Match {} already downloaded use --force to reload".format(g))
def recent_matches(base_url="http://www.anarchy.bloodbowlleague.net/", base_path = BASEPATH, force=force_download()):
"""Download recent matches from host. If force is True existing matches will be downloaded again"""
LOG.debug("Fetch recent matches")
games = new_games(base_path, base_url)
LOG.info("{} recent match{} {}".format(len(games), "es" if len(games) != 1 else "", games))
download_matches2(base_url, base_path=base_path, force=force, games=games)
def main():
import importer.bbleague.update
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.debug("Command line arguments %s", sys.argv)
LOG.info("Fetch match")
site = sys.argv[1] if len(sys.argv) > 1 else "anbbl"
config = importer.bbleague.update.load_config(site)
if len(sys.argv) == 3 and sys.argv[2].isnumeric():
download_match(sys.argv[2], config.get("base_path"))
elif len(sys.argv) == 4:
from_match = int(sys.argv[2])
to_match = int(sys.argv[3]) + 1
download_matches(config.get("base_path"), from_match, to_match)
else:
recent_matches(base_path=config.get("base_path"))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,686 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/scrape/fetch_coachlist.py | #!/bin/env python3
import sys
import os.path
import scrape.session
import logging
LOG = logging.getLogger(__name__)
coaches_url = "/default.asp?p=co"
def download_coach_list(base_url, username, password, base_path):
login_url = "{}/login.asp".format(base_url)
s = scrape.session.login(login_url, username=username, password=password)
source_url = "{}/{}".format(base_url, coaches_url)
target_path = os.path.join(base_path, "html/coach")
if not os.path.isdir(target_path):
LOG.warning("Target path %s does not exist. Attempting to create", target_path)
os.makedirs(target_path)
scrape.session.download_to(s, source_url, os.path.join(target_path, "coaches-8.html"))
def main():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("username")
parser.add_argument("password")
parser.add_argument("base_url")
parser.add_argument("base_path")
arguments = parser.parse_args()
download_coach_list(arguments.base_url, arguments.username, arguments.password, arguments.base_path)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,687 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/coach/parse_from_team.py | #!/usr/bin/env python
""" Create list of coaches from team list for use when actual coach list is missing. """
import sys
import os.path
import logging
from .coach import parse
import team.parse
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def create_coach(nick, uid):
coach = {'nick': nick,
'email': nick,
'naf': "",
'role': "coach",
'phone': "",
'location': "Old World",
'login': parse.NEVER_LOGGED_IN,
'loggedin': True,
'uid': str(uid)}
if coach["login"] != parse.NEVER_LOGGED_IN:
coach["loggedin"] = True
return coach
def parse_teams(teams):
coaches = set()
for t in teams:
LOG.debug("Team '%s', '%s' '%s'",
t["name"] if t["name"] else "No name",
t["coach"] if t["coach"] else "No coach",
t["co-coach"] if t["co-coach"] else "No co-coach")
if t["coach"]:
coaches.add(t["coach"])
if t["co-coach"]:
coaches.add(t["co-coach"])
return [create_coach(coach, index+10000) for index, coach in enumerate(coaches)]
def data_exists(basepath = BASEPATH):
file_path = basepath + "html/team/teams-8.html"
exists = os.path.isfile(file_path)
LOG.debug("%s that %s isfile", exists, file_path)
return exists
def list_coaches(basepath = BASEPATH):
LOG.debug("Retrieving coaches from team list")
teams = team.parse.list_teams(basepath)
LOG.debug("Found {} teams".format(len(teams)))
coaches = parse_teams(teams)
return coaches
def main():
import sys
from pprint import pprint
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.info("Parsing teamlist for coaches")
path = sys.argv[1] if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]) else BASEPATH
coaches = list_coaches(path)
if "--no-print" not in sys.argv:
pprint(coaches, indent=2)
if __name__ == "__main__":
main() | {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,688 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate_match.py | #!/usr/bin/env python3
import logging
from coach import coach
LOG = logging.getLogger(__package__)
def add_team_race(data):
for g in data["game"].values():
g["home_race"] = data["team"][g["home_teamid"]]["race"]
g["away_race"] = data["team"][g["away_teamid"]]["race"]
return data["game"]
def add_coach_nick(data):
print("add_coach_nick, {} {}".format( type(data), len(data)))
lookup = {c["uid"]:c["nick"] for c in data["coach"].values()}
try:
for match in data["game"].values():
match["away_coach"] = lookup[match["away_coachid"]]
match["home_coach"] = lookup[match["home_coachid"]]
except KeyError as kerr:
print(match)
raise kerr
return data["game"]
def fix_missing_coaches(data):
def fix_coach(gam, coaches, teams):
if gam["home_coachid"] in ["0", None]:
team_coachnick = teams[gam["home_teamid"]]['coach']
uid = coach.find_uid_for_nick(data["coach"], team_coachnick)
gam["home_coachid"] = uid if uid else -1
if gam["away_coachid"] in ["0", None]:
team_coachnick = teams[gam["away_teamid"]]['coach']
uid = coach.find_uid_for_nick(data["coach"], team_coachnick)
gam["away_coachid"] = uid if uid else -1
for matchid, g in data["game"].items():
fix_coach(g, data["coach"], data["team"])
return data["game"]
def collate_match(data):
games2 = fix_missing_coaches(data)
games2 = add_coach_nick(data)
games2 = add_team_race(data)
return games2
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,689 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/tournament/parse_matches.py | #!/usr/bin/env python
import sys
from bs4 import BeautifulSoup
import logging
LOG = logging.getLogger(__name__)
def id_from_onclick(el):
if el and el.has_attr("onclick"):
return el["onclick"][el["onclick"].rfind("=")+1:el["onclick"].rfind("'")]
return "teamid not found {}".format(el.name)
def parse_match(match):
return {"matchid": id_from_onclick(match),
"match_played": match.has_attr("title")}
def parse_matches(soup):
standings = []
matches = soup.findAll(lambda t: t.name=="tr" and t.has_attr("onclick") and t["onclick"].startswith("self.location.href='default.asp?p=m&m="))
#matches = soup.findAll(lambda t: t.name=="tr" and t.has_attr("title") and t["title"].startswith("result added"))
LOG.debug("Found %s matches", len(matches))
for found in matches:
team = parse_match(found)
standings.append(team)
return standings
def open_matches(filename):
html = open(filename, "rb").read()
soup = BeautifulSoup(html, "html.parser")
matches = parse_matches(soup)
return matches
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
matches = open_matches(sys.argv[1])
for m in matches:
print(m["matchid"])
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,690 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/bblparser/models.py | from dataclasses import dataclass
import typing
@dataclass
class Link:
href: str
onclick: str
text: str
def get_link(self, base='http://anarchy.bloodbowlleague.com/'):
if self.href:
return "{base}{href}".format(base=base, href=self.href)
if self.onclick:
onclick = self.onclick[self.onclick.find("'?")+1:self.onclick.rfind("';")]
return "{base}{onclick}".format(base=base,
onclick=onclick)
return None
def is_link(self):
return self.href or self.onclick
@dataclass
class Page:
menu: typing.List[Link]
latest_matches: typing.List[typing.Dict]
latest_bulletins: typing.List[typing.Dict]
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,691 | ketilkn/bloodbowl-utility | refs/heads/master | /skills/skills.py | #!/bin/env python3
import simplejson
linjer = open("skills.txt", "r").readlines()
skill = {}
skills = {}
for linje in linjer:
if not linje.strip():
skills[skill['id']] = skill
skill = None
continue
elif not skill:
title = linje[0: linje.find("(")].strip()
id = title.strip().replace(" ", "-").lower()
category = linje[linje.find("(")+1: -2].lower()
skill = {'id': id, 'title': title, 'category': category, 'text': ""}
else:
skill['text'] = skill['text'] + linje.replace("\n"," ")
print(simplejson.dumps(skills))
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,692 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate_player.py | #!/usr/bin/env python3
import os
import json
import logging
from match import match
from coach import coach
from team import team
from player import player
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def hide_invalid_players(players):
for p in players.values():
p["invalid"] = p["position"].strip() in ["-", "Skaven Bookie", "Undead High Liche Priest", "Human Referee"]
return players
def collate_players(data):
players = data["player"]
players = hide_invalid_players(players)
return players
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,693 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate_coach.py | #!/usr/bin/env python3
import os
import sys
import json
import logging
from match import match
from coach import coach
from team import team
from player import player
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def collate_coach(data):
for coach in data["coach"].values():
coach["games"]=[]
for match in data["game"].values():
if match["matchid"] in data["coach"][match["home_coach"]]["games"]:
print("Warning {} already exists in {}".format(match["matchid"], match["home_coach"]))
data["coach"][match["home_coach"]]["games"].append(match["matchid"])
if match["matchid"] in data["coach"][match["away_coach"]]["games"]:
print("Warning {} already exists in {}".format(match["matchid"], match["away_coach"]))
data["coach"][match["away_coach"]]["games"].append(match["matchid"])
return data["coach"]
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,694 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/player_list.py | #!/usr/bin/env python
""" Functions to list and filter league players """
import sys
import logging
import stats.collate
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def order_by_pid(players):
"""order list of players by player.player_id"""
return sorted(players,
key=lambda p: int(p["playerid"]))
def order_by_team(players):
"""order list of players by player.team"""
return sorted(players,
key=lambda p: p["teamname"])
def order_by_playername(players):
"""order list of players by player.name"""
return sorted(players,
key=lambda p: p["playername"])
def order_by_position(players):
"""order list of players by player.position"""
return sorted(players,
key=lambda p: p["position"],
reverse=False)
def order_by_spp(players):
"""order list of players by player.spp.total"""
return sorted(players,
key=lambda p: int(p["spp"]["total"]) if p["spp"]["total"] else 0,
reverse=True)
def order_by_interception(players):
"""order list of players by player.spp.cmp"""
return sorted(players,
key=lambda p: int(p["spp"]["interception"]) if p["spp"]["interception"] else 0,
reverse=True)
def order_by_completion(players):
"""order list of players by player.spp.cmp"""
return sorted(players,
key=lambda p: int(p["spp"]["completion"]) if p["spp"]["completion"] else 0,
reverse=True)
def order_by_mvp(players):
"""order list of players by player.spp.mvp"""
return sorted(players,
key=lambda p: int(p["spp"]["mvp"]) if p["spp"]["mvp"] else 0,
reverse=True)
def order_by_casualties(players):
"""order list of players by player.spp.cas"""
return sorted(players,
key=lambda p: int(p["spp"]["casualty"]) if p["spp"]["casualty"] else 0,
reverse=True)
def order_by_value(players):
"""order list of players by value"""
return sorted(players,
key=lambda p: int(p["value"]) + int(p["spp"]["total"]) if "value" in p and p["value"] and p["value"] and p["spp"]["total"] else 0,
reverse=True)
def order_by_touchdowns(players):
"""order list of players by player.spp.td"""
return sorted(players,
key=lambda p: int(p["spp"]["td"]) if p["spp"]["td"] else 0,
reverse=True)
def order_by(players, order):
ordering = order
if type(order) is not list:
ordering=list(order)
ordered = players
if type(players) is not list:
ordered=list(players)
LOG.debug("Ordering %s players by %s", len(ordered), order)
for o in ordering:
LOG.debug("Order by %s", o)
if o == "spp":
ordered = order_by_spp(ordered)
elif o == "position":
ordered = order_by_position(ordered)
elif o == "name" or o == "playername":
ordered = order_by_playername(ordered)
elif o == "team":
ordered = order_by_team(ordered)
elif o in ["playerid", 'pid']:
ordered = order_by_pid(ordered)
else:
LOG.warning("No such ordering %s", o)
return ordered
def filter_invalid(players):
"""Filter players used to record team stats"""
return filter(lambda p: p["team"] and
("invalid" not in p or not p["invalid"]), players)
def filter_position(players, position):
"""Filter players by position"""
return filter(lambda p: p["position"] == position, players)
def filter_nospp(players):
"""Filter players with no star player points"""
return filter(lambda p: p["spp"]["total"].strip() != "" and int(p["spp"]["total"]) > 0, players)
def filter_team(players, team):
"""Filter players by teams"""
teams = team
if type(team) is not list:
teams = list(team)
return filter(lambda p: p["team"] in teams, players)
def flatten_players(players):
"""Flatten list of players"""
for p in players:
yield flatten_player(p)
def flatten_player(p):
return {"playerid": p["playerid"],
"playername": p["playername"],
"position": p["position"],
"team": p["team"],
"teamname": p["teamname"],
"ma": p["ma"],
"st": p["st"],
"ag": p["ag"],
"av": p["av"],
"skills": ",".join(p["skills"]),
"injuries": p["status"]["injury"],
"int": p["spp"]["interception"],
"cmp": p["spp"]["completion"],
"td": p["spp"]["td"],
"cas": p["spp"]["casualty"],
"mvp": p["spp"]["mvp"],
"spp": p["spp"]["total"],
"value": p["value"]}
def all_positions(data):
"""Return all player positions in data"""
LOG.debug("Print all positions in data.player")
positions = set()
for p in data["player"].values():
positions.add(p["position"])
return positions
def all_players(data, include_journeymen=False):
"""Convert players in collated data to list"""
LOG.debug("Player count is %s", len(data["player"]) if "player" in data else "No 'player' in data")
if "player" not in data:
LOG.warning("No 'player' in data")
if "player" in data and len(data["player"]) == 0:
LOG.warning("Zero players in data")
players = data["player"].values()
players = filter_invalid(players)
players = order_by_spp(players)
if not include_journeymen:
LOG.debug("Filter journeymen")
return list(filter(lambda p: not p["journeyman"], players))
return players
def main():
import argparse
import player.display
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.WARNING, format=log_format)
argparser=argparse.ArgumentParser()
argparser.add_argument("--player", help="Filter players by player id", nargs="*")
argparser.add_argument("--team", help="Filter players by team", nargs="*")
argparser.add_argument("--pid", help="Show pid only", action="store_true")
argparser.add_argument("--journeymen", help="Include journeymen", action="store_true")
argparser.add_argument("--inactive", help="Include inactive players", action="store_true")
argparser.add_argument("--position", help="Filter by position", nargs="*")
argparser.add_argument("--sort", help="Sort players", nargs="*")
arguments=argparser.parse_args()
data = stats.collate.collate(False, BASEPATH)
players = all_players(data, include_journeymen=arguments.journeymen)
LOG.debug("Player count is %s", len(players))
if arguments.team:
players = filter_team(players, arguments.team)
if arguments.position:
players = filter_position(players, " ".join(arguments.position))
if arguments.sort:
players = order_by(players, arguments.sort)
for idx, p in enumerate(players):
if arguments.pid:
print(p["playerid"])
else:
print("{:>4}".format(idx + 1), player.display.plformat(p))
flatten_player(p)
#print(all_positions(data))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,695 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/__main__.py | #!/usr/bin/env python3
from export import all_data
if __name__ == '__main__':
all_data.export_all_data()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,696 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/coach_data.py | #!/usr/bin/env python3
from copy import deepcopy
from match import match
from team import team
from coach import coach
from stats import coach_list
from stats import team_list
from stats import match_list
import stats.elo
from export import export
import dateutil.parser
from datetime import date
from stats.collate import collate
import datetime
from importer.bbleague.defaults import BASEPATH
import logging
LOG = logging.getLogger(__package__)
def all_teams_for_coach(data, coach, coach_teams, coach_games):
game_total = match_list.sum_game(coach_games)
streaks = match_list.game_streaks(coach_games)
streaks.update(coach_list.coach_streaks(coach_games))
games_with_race = match_list.sum_game_by_group(coach_games, match_list.group_games_with_race)
games_by_race = match_list.sum_game_by_group(coach_games, match_list.group_games_by_race)
games_by_weekday = match_list.games_by_weekday(coach_games)
games_by_coach = match_list.sum_game_by_group(coach_games, match_list.group_games_by_coach)
#FIXME. group_games_by_coach should return proper coach
for c in games_by_coach:
if c["title"] in data["_coachid"]:
c["title"] = data["_coachid"][c["title"]]["nick"]
c["link"] = "/coach/{}.html".format(c["title"].replace(" ","-"))
else:
c["title"] = "Unknown {}".format(c["title"])
c["link"] = "/coaches.html"
return export.get_template("coach/coach.html").render(
coach_name = coach["nick"],
coach = coach_list.coach_data(coach, coach_games),
streaks = streaks,
games_with_race = games_with_race,
games_by_race = games_by_race,
games_by_coach = games_by_coach,
games_by_weekday = games_by_weekday,
more_games = len(coach_games) - 10,
teams = coach_teams,
stats_average = game_total["average"],
stats_total = game_total["total"],
games = coach_games[:10],
title="{}".format(coach["nick"])
)
def teams_by_coach(data):
coaches = coach.list_coaches()
teams = sorted(team_list.list_all_teams_by_points(data), key=lambda x: x["gamesplayed"], reverse=True)
add_elo(data)
#games = list_all_games_by_coach()
for c in coaches:
name = c["nick"]
if name in data["coach"] and "elo" in data["coach"][name]:
c["elo"] = data["coach"][name]["elo"]
cgames = list( sorted( coach_list.list_all_games_by_coach2(data, name), key=lambda x: int(x["matchid"]), reverse=True))
cgames = list( sorted( cgames, key=lambda x: x["date"], reverse=True))
cgames = deepcopy(match_list.we_are_coach(cgames, c))
team_coach = list(sorted(match_list.games_for_teams(data, cgames).values(), key=lambda x: x["name"]))
team_coach = sorted(team_coach, key=lambda x: x["total"]["performance"], reverse = True)
team_coach = sorted(team_coach, key=lambda x: x["total"]["gamesplayed"], reverse = True)
with open("output/coach/{}.html".format(name.replace(" ","-")), "w") as fp:
fp.write(all_teams_for_coach(data, c, team_coach, cgames))
with open("output/coach/{}-games.html".format(name.replace(" ","-")), "w") as fp:
fp.write(export.get_template("coach/coach-games.html").render(
coach = c,
games = cgames,
title = "All games by {}".format(name)))
def all_coaches_by_year(data, start = 2007, end = datetime.datetime.now().year+1):
import stats.collate
#data = stats.collate.collate()
for year in range(2007, end):
coaches = coach_list.list_all_coaches2(data = data, year=year)
#print( "{} coaches {} ".format(year, len(coaches)))
coaches = [c for c in coaches if c["games"]["total"]["gamesplayed"] > 0]
coaches = sorted(coaches, key=lambda x: x["nick"])
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["cas"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["td"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["gamesplayed"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["performance"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["points"], reverse=True)
#print( "{} coaches {} ".format(year, len(coaches)))
with open("output/coaches-{}.html".format(year), "w") as fp:
fp.write(export.get_template("coach/all_coaches2.html").render(
coaches=coaches, title="All coaches in {}".format(year)))
def add_elo(data):
rating = stats.elo.rate_all(data)
coaches_by_uid = data["_coachid"]
for rate in rating.values():
if rate["cid"] in coaches_by_uid:
nick = coaches_by_uid[rate["cid"]]["nick"]
if nick in data["coach"]:
data["coach"][nick]["elo"] = rate
return data
def all_coaches(data):
coaches = coach_list.list_all_coaches2(data)
add_elo(data)
coaches = [c for c in coaches if c["games"]["total"]["gamesplayed"] > 0]
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["td"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["performance"], reverse=True)
coaches = sorted(coaches, key=lambda x: x["games"]["total"]["points"], reverse=True)
#coaches = sorted(coaches, key=lambda x: x["elo"]["rating"], reverse=True)
with open("output/coaches.html", "w") as fp:
fp.write(export.get_template("coach/all_coaches2.html").render(
display_rating=True, coaches=coaches, title="All coaches through all time"))
def doExport():
import stats.collate
collated_data = stats.collate.collate()
print("Exporting all coaches")
all_coaches(collated_data)
print("Exporting teams by coach")
teams_by_coach(collated_data)
print("Export year by coach")
all_coaches_by_year(collated_data)
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
doExport()
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,697 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/parse.py | #!/usr/bin/env python
""" Parse player from HTML file """
import sys
import re
import dateutil.parser as parser
import logging
from bs4 import BeautifulSoup
from bs4.element import NavigableString
from player import parse_admin
from . import parse_profile
LOG = logging.getLogger(__package__)
def parse_fromfile(path, playerid):
LOG.debug("%s %s", path, playerid)
import player.load
try:
parsed_player = parse_admin.parse_player(playerid, soup=player.load.from_file("{}/admin-player-{}.html".format(path, playerid)))
parsed_player = parse_profile.parse_games(parsed_player, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))
parsed_player = parse_profile.parse_team(parsed_player, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))
if not parsed_player["journeyman"] and parsed_player["status"]["active"]["reason"] == "no status":
LOG.warning("%s %s %s %s has no status", parsed_player["team"], playerid, parsed_player["playername"],
parsed_player["position"])
return parsed_player
except:
LOG.exception("Exception while parsing %s in %s", playerid, path)
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
#logging.basicConfig(level=logging.DEBUG, format=log_format)
logging.basicConfig(level=logging.DEBUG)
import pprint
if len(sys.argv) < 2:
sys.exit("path and playerid required")
path = sys.argv[1] if not sys.argv[1].isdigit() else "input/html/player"
players = sys.argv[1:] if sys.argv[1].isdigit() else sys.argv[2:]
for player_id in players:
if player_id.isdigit():
parsed_player = parse_fromfile(path, player_id)
pprint.PrettyPrinter(indent=4).pprint(parsed_player)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,698 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/parse_admin.py | #!/usr/bin/env python
""" Parse player from HTML file """
import sys
import re
import dateutil.parser as parser
import logging
from bs4 import BeautifulSoup
from bs4.element import NavigableString
LOG = logging.getLogger(__package__)
def parse_date(soup):
LOG.debug("CREATION DATE >==-")
indates = soup.select("input[name=indate]")
LOG.debug("Search len %s", len(indates))
indate = indates[0]
LOG.debug("indate el %s", "{}".format(indate))
return parser.parse(indate["value"]).isoformat()
def parse_bounties(soup):
LOG.debug("-==< Parsing BOUNTY >==-")
bounties = soup.select("input[name=bounty]")
LOG.debug("Search len %s", len(bounties))
bounty = bounties[0]
Log.debug("bounty el: %s", bounty)
return {"total": int(bounty["value"]) * 1000}
def parse_journeyman(soup):
LOG.debug("JOURNEYMAN >=========-")
return parse_playername(soup).strip() == "journeyman"
def parse_playername(soup):
LOG.debug("PLAYER NAME >=========-")
search = soup.select("input[name=name]")
LOG.debug("Search len %s", len(search))
playername = search[0]
LOG.debug("playername el %s", playername)
return playername["value"]
def parse_position(soup):
LOG.debug("POSITION >=========-")
search = soup.select("select option[selected]")
LOG.debug("Search len %s", len(search))
position = search[0]
LOG.debug("position el %s", position)
return position["value"]
def parse_normal(soup):
LOG.debug("NORMAL >=========-")
normal = soup.find_all("input", {"name": lambda x: x and x.startswith("upgr") and x != "upgr7"})
LOG.debug("search len %s", len(normal))
for el in normal:
LOG.debug("normal el %s", el)
return [x["value"] for x in normal if x["value"]]
def parse_extra(soup):
LOG.debug("EXTRA >=========-")
extra = soup.select_one("input[name=upgr7]")
LOG.debug("extra el %s", extra)
return [x for x in extra["value"].split(',') if len(extra["value"]) > 0]
def parse_modifier(soup):
LOG.debug("MODIFIER >=========-")
return {"ma": parse_characteristic(soup, "ma"),
"st": parse_characteristic(soup, "st"),
"ag": parse_characteristic(soup, "ag"),
"av": parse_characteristic(soup, "av")}
def parse_upgrade(soup):
LOG.debug("EXTRA UPGRADE >=========-")
search = soup.select("input[name=upgr7]")
LOG.debug("Search len %s", len(search))
extra = search[0]
LOG.debug("extra el %s", extra)
return {"normal": parse_normal(soup),
"extra": parse_extra(soup),
"modifier": parse_modifier(soup)}
def parse_characteristic(soup, characteristic):
LOG.debug("CHARACTERISTIC %s >=========-", characteristic)
element = soup.select_one("select[name={}] option[selected]".format(characteristic))
LOG.debug("characteristic el %s", element)
return int(element["value"])
def parse_halloffame(soup):
LOG.debug("HALL_OF_FAME >=========-")
hall_of_famer = soup.select_one("select[name=hof] option[selected]")
LOG.debug("h-o-f el %s", hall_of_famer)
# print(hall_of_famer)
hall_of_famer_reason = soup.select_one("textarea[name=hofreason]")
return {"hall_of_famer": True if hall_of_famer and hall_of_famer["value"] != 0 else False,
"season": hall_of_famer["value"] if hall_of_famer else 0,
"reason": hall_of_famer_reason.string if hall_of_famer_reason else ""}
def parse_note(soup):
LOG.debug("NOTE >========>")
note = soup.select_one("textarea[name=remarks]")
LOG.debug("Note len %s", len(note.text))
return note.text.replace('\xa0', ' ')
def parse_permanent(soup):
LOG.debug("PERMANENT injuries >=========-")
permanent = soup.select_one("input[name=inj]")
LOG.debug("permanent el %s", permanent)
return list(filter(lambda x: len(x) > 0, permanent["value"].split(",")))
def parse_active(soup, pid=None):
LOG.debug("ACTIVE >=========-")
status = soup.select_one("select[name=status]")
LOG.debug("status len %s", len(status))
for el in status:
LOG.debug("option el {}".format(el).strip())
selected_option = status.select_one("option[selected]")
LOG.debug("option->selected {}".format(selected_option))
active = True if selected_option and selected_option["value"] == "a" else False
reason = selected_option.text if not active and selected_option else ""
if not selected_option:
LOG.debug("No selected_option for %s", pid)
LOG.debug("active: %s %s", active, reason)
return {"active": active,
"reason": reason if selected_option else ""}
def parse_status(soup, pid="Unknown"):
LOG.debug("PARSE STATUS")
return {"entered_league": parse_date(soup),
"niggle": parse_niggle(soup),
"injury": parse_permanent(soup),
"active": parse_active(soup, pid=pid)}
def parse_niggle(soup):
LOG.debug("NIGGLE >=========-")
niggle =soup.select_one("select[name=n] option[selected]")
LOG.debug("niggle el %s", niggle)
return int(niggle["value"])
def parse_player(playerid, soup):
LOG.debug("parse player-admin with id %s", playerid)
player_date = parse_date(soup)
if not player_date:
return None
player = {"playerid": playerid,
"playername": parse_playername(soup),
"position": parse_position(soup),
"upgrade": parse_upgrade(soup),
"status": parse_status(soup, pid=playerid),
"hall_of_fame": parse_halloffame(soup),
"journeyman": parse_journeyman(soup),
"note": parse_note(soup)
}
return player
def parse_fromfile(path, playerid):
LOG.info("%s %s", path, playerid)
import player.load
parsed_player = parse_player(playerid, soup=player.load.from_file("{}/admin-player-{}.html".format(path, playerid)))
return parsed_player
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
#logging.basicConfig(level=logging.DEBUG, format=log_format)
logging.basicConfig(level=logging.DEBUG)
import pprint
if len(sys.argv) < 2:
sys.exit("path and playerid required")
path = sys.argv[1] if not sys.argv[1].isdigit() else "input/html/player"
players = sys.argv[1:] if sys.argv[1].isdigit() else sys.argv[2:]
for player_id in players:
if player_id.isdigit():
parsed_player = parse_fromfile(path, player_id)
pprint.PrettyPrinter(indent=4).pprint(parsed_player)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,699 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/tournament/test_pairing.py | #!/usr/bin/env python
""" Test tournament pairing """
import sys
import pytest
import logging
from tournament.pairing import swiss_pairing, pairing, match_played, find_opponent
LOG = logging.getLogger(__package__)
STANDINGS = [{'name': 'test team 2', 'position': 1, 'teamid': 'tes2'},
{'name': 'Test team K', 'position': 2, 'teamid': 'tes3'},
{'name': 'Dust Bunnies', 'position': 3, 'teamid': 'dus'},
{'name': 'Demolition men', 'position': 4, 'teamid': 'dem'},
{'name': 'The Dwarf Giants', 'position': 5, 'teamid': 'dwa'},
{'name': 'Amazons', 'position': 6, 'teamid': 'les'},
{'name': 'Reikland Reavers', 'position': 7, 'teamid': 'rei'},
{'name': 'Underworld Creepers', 'position': 8, 'teamid': 'und'},
{'name': 'Chaos All-stars', 'position': 9, 'teamid': 'cha'},
{'name': 'Ogreheim Manglers', 'position': 10, 'teamid': 'ogr'}]
def test_swiss_pairing_return_list():
assert type(swiss_pairing([], [])) == list
def test_swiss_pairing_after_one_round():
matches = swiss_pairing(STANDINGS, [])
print(matches)
paired = swiss_pairing(STANDINGS, matches)
print("========")
assert len(paired) == 5, "Expected 6 matches"
assert paired[0]["home_team"]["teamid"] == "tes2"
assert paired[0]["away_team"]["teamid"] == "dus"
assert paired[1]["home_team"]["teamid"] == "tes3"
assert paired[1]["away_team"]["teamid"] == "dem"
assert paired[2]["home_team"]["teamid"] == "dwa"
assert paired[2]["away_team"]["teamid"] == "rei"
#assert matches[4]["away_team"]["teamid"] == "les"
#assert matches[3]["away_team"]["teamid"] == "cha"
#assert matches[3]["home_team"]["teamid"] == "und"
#assert matches[4]["away_team"]["teamid"] == "ogr"
def test_swiss_pairing_return_matches():
matches = swiss_pairing(STANDINGS, [])
assert type(matches) == list
assert len(matches) == 5, "Expected 6 matches"
assert matches[0]["home_team"]["teamid"] == "tes2"
assert matches[0]["away_team"]["teamid"] == "tes3"
assert matches[1]["home_team"]["teamid"] == "dus"
assert matches[1]["away_team"]["teamid"] == "dem"
assert matches[2]["home_team"]["teamid"] == "dwa"
assert matches[2]["away_team"]["teamid"] == "les"
assert matches[3]["home_team"]["teamid"] == "rei"
assert matches[3]["away_team"]["teamid"] == "und"
assert matches[4]["home_team"]["teamid"] == "cha"
assert matches[4]["away_team"]["teamid"] == "ogr"
def test_pairing_require_standings():
with pytest.raises(ValueError):
pairing([], [], "swiss")
def test_match_played():
matches = [{'away_team': {'teamid': 'tes3', 'name': 'Test team K', 'position': 2},
'home_team': {'teamid': 'tes2', 'name': 'test team 2', 'position': 1}}]
assert match_played({'teamid': 'tes2', 'name': 'test team 2', 'position': 1},
{'teamid': 'tes3', 'name': 'Test team K', 'position': 2},
matches)
def test_find_opponent():
matches = swiss_pairing(STANDINGS, [])
assert find_opponent({'teamid': 'tes2', 'name': 'test team 2', 'position': 1},
STANDINGS[1:],
matches) == {'name': 'Dust Bunnies', 'position': 3, 'teamid': 'dus'}
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,700 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/collate_team.py | #!/usr/bin/env python3
import os
import json
import logging
from match import match
from coach import coach
from team import team
from player import player
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def collate_team(data):
for team in data["team"].values():
team["games"]=[]
for match in data["game"].values():
if match["matchid"] in data["team"][match["home_teamid"]]["games"]:
print("Warning {} already exists in {}".format(match["matchid"], match["home_team"]))
data["team"][match["home_teamid"]]["games"].append(match["matchid"])
if match["matchid"] in data["team"][match["away_teamid"]]["games"]:
print("Warning {} already exists in {}".format(match["matchid"], match["away"]["team"]))
data["team"][match["away_teamid"]]["games"].append(match["matchid"])
return data["team"]
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,701 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/scrape/fetch_teamlist.py | #!/bin/env python3
import sys
import os.path
import logging
import scrape.session
LOG = logging.getLogger(__package__)
teams_script = "default.asp?p=te"
def download(session, url, path):
pass
def download_team_list(base_url, username, password, base_path):
LOG.debug("Download teamlist from %s to %s", base_url, base_path)
s = scrape.session.login("{}/login.asp".format(base_url), username=username, password=password)
target_path = os.path.join(base_path, "html", "team")
if not os.path.isdir(target_path):
LOG.warning("Target path %s does not exist. Attempting to create", base_path)
os.makedirs(target_path)
teams_location = "{}/{}".format(base_url, teams_script)
scrape.session.download_to(s, teams_location, os.path.join(base_path, "html/team/teams-8.html"))
def main():
import argparse
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
parser = argparse.ArgumentParser()
parser.add_argument("username")
parser.add_argument("password")
parser.add_argument("base_url")
parser.add_argument("base_path")
arguments = parser.parse_args()
download_team_list(arguments.base_url, arguments.username, arguments.password, arguments.base_path)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,702 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/coach_list.py | #!/usr/bin/env python3
import dateutil
import datetime
from datetime import date
from operator import itemgetter
from copy import deepcopy
from match import match
from team import team
from coach import coach
from stats.match_list import list_all_matches
from stats.match_list import games_for_year, we_are_coach, sum_game, favorite_day
from stats.match_list import playstreak
from stats import match_list
def eventstreak(games, event, minimum=0):
if len(games) < 1:
return 0
longest_streak = 0
current_streak = 0
previous_game = games[0]
for g in games[1:]:
#if g["us"]["coachid"] == 74:
#print("\n====")
#print(g["date"])
#print(g["us"])
#print(g["them"])
#print("\n")
if event(g, previous_game):
if longest_streak == 0 and current_streak == 0:
current_streak = 1
current_streak = current_streak + 1
if current_streak > longest_streak:
longest_streak = current_streak
else:
current_streak = 0
previous_game = g
if longest_streak < minimum:
return 0
return longest_streak
def coach_streaks(games):
streaks = {}
streaks["sameteam"] = eventstreak(games,
event = lambda x, y: y["home_teamid"] == x["home_teamid"],
minimum=2)
streaks["differentteam"] = eventstreak(games,
event = lambda x, y : y["home_teamid"] != x["home_teamid"],
minimum=2)
streaks["sameopponent"] = eventstreak(games,
event = lambda x, y: y["away_teamid"]== x["away_teamid"],
minimum=2)
streaks["differentopponent"] = eventstreak(games,
event = lambda x, y : y["away_teamid"] != x["away_teamid"],
minimum=2)
streaks["sameopponentcoach"] = eventstreak(games,
event = lambda x, y: x["away_coachid"]== y["away_coachid"],
minimum=2)
streaks["differentopponentcoach"] = eventstreak(games,
event = lambda x, y : x["away_coachid"]!= y["away_coachid"],
minimum=2)
return streaks
def list_all_games_by_coach2(data, the_coach):
coach_id = data["coach"][the_coach]["uid"]
return [g for g in data["game"].values() if g["home_coachid"] == coach_id or g["away_coachid"] == coach_id]
def coach_data(coach, coach_games):
coach["last_game"] = coach_games[0]["date"] if len(coach_games) > 0 else "Never"
coach["first_game"] = coach_games[-1]["date"] if len(coach_games) > 0 else None
games_played = len(coach_games)
coach["game_frequency"] ="Never"
coach["gamesplayed_time"] = 0
coach["favorite_day"] = favorite_day(coach_games)
coach["anbbl_rating"] = "N/A"
if "elo" in coach:
coach["anbbl_rating"] = "{:.1f}".format(150 + coach["elo"]["rating"])
#coach["anbbl_rating"] = coach["elo"]["rating"]
if(coach["first_game"]):
first_game = dateutil.parser.parse(coach["first_game"])
last_game = dateutil.parser.parse(coach["last_game"])
days_since_first_game = (datetime.datetime.now() - first_game).days
days_active = (last_game - first_game).days
if (datetime.datetime.now() - last_game).days > 730:
coach["game_frequency"] = "Stopped playing"
elif (datetime.datetime.now() - last_game).days > 365:
coach["game_frequency"] = "Rare"
else:
coach["game_frequency"] = "every {} days".format(round(abs(days_since_first_game)/games_played))
if len(coach_games) > 1 and days_active > len(coach_games):
coach["gamesplayed_time"] = len(coach_games) / days_active
if len(coach_games) >= days_active:
coach["gamesplayed_time"] = 1
coach["gp"] = len(coach_games)
return coach
def list_all_coaches2(data = None, year = None):
all_data = data
if all_data == None:
import stats.collate
all_data = stats.collate.collate()
result = []
for the_coach in all_data["coach"].values():
games = deepcopy(we_are_coach(all_data["game"].values(), the_coach))
games = games_for_year(games, year)
total = sum_game(games)
the_coach["games"] = {"all": games,
"total": total["total"],
"average": total["average"]}
the_coach["coachlink"] = the_coach["nick"].replace(" ","-")
result.append(the_coach)
return result
def main():
import stats.collate
data = stats.collate.collate()
games = list_all_games_by_coach2(data, "Tango")
for g in games:
print("{} - {}".format(g["home_name"], g["away_name"]))
#for coach in list_all_coaches():
#print(coach)
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,703 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/load.py | #!/usr/bin/env python3
""" Parse players from HTML"""
import sys
import os.path
import json
import logging
from bs4 import BeautifulSoup
from player import parse
from importer.bbleague.defaults import BASEPATH
LOG=logging.getLogger(__name__)
def from_file(filename):
html = open(filename, "rb").read()
soup = BeautifulSoup(html.decode("utf-8", 'ignore'), "html.parser")
return soup
def parse_path(path):
files = os.listdir(path)
for player_file in filter(lambda f: f.startswith("player-"), files):
playerid = player_file.replace("player-", "").replace(".html", "")
yield parse.parse_fromfile(path, playerid)
def setup_log(level):
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# create formatter
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
logging.addHandler(ch)
def write_json(player, path="input/json/player"):
filename = "player-{}.json".format(player["playerid"])
with open(os.path.join(path, filename), "w") as outfile:
json.dump(player, outfile)
def load_player(path, filename):
print("Open file {} {}".format(path, filename))
with open(os.path.join(path, filename), "r") as infile:
return json.load(infile)
def load(basepath=BASEPATH):
path = os.path.join(basepath, "json/player/")
files = os.listdir(path)
for playerfile in filter(lambda f: f.startswith("player-") and f.endswith(".json"), files):
yield load_player(path, playerfile)
def load_all():
return load()
def main():
if "--debug" in sys.argv[1:]:
logging.basicConfig(level=logging.DEBUG)
logging.debug("Log level debug")
do_print = True if "--no-print" not in sys.argv[1:] else False
do_json = True if "--json" in sys.argv[1:] else False
if "--load-all" in sys.argv[1:]:
players = load_all()
print("found {} players".format(sum(1 for x in players)))
sys.exit()
logging.basicConfig(level=logging.INFO)
arguments = list(filter(lambda x: not x.startswith("--"), sys.argv[1:]))
interesting = arguments if len(arguments) > 0 else None
logging.info("program started")
logging.debug("debug")
# setup_log(logging.DEBUG)
path = os.path.join(BASEPATH, "html/player/")
logging.info("Loading players from %s", path)
import pprint
if interesting:
logging.info("Looking for %s", interesting)
pp = pprint.PrettyPrinter(indent=4)
invalid_count = 0
for player in parse_path(path):
if not player:
LOG.debug('Ignoring invalid file')
invalid_count = invalid_count + 1
continue
if not interesting or player["playerid"] in interesting:
if do_print:
pp.pprint(player)
if do_json:
write_json(player=player, path=os.path.join(BASEPATH, "json/player/"))
LOG.debug("%s invalid files", invalid_count)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,704 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/scrape/session.py | #!/usr/bin/env python3
import requests
import sys
import logging
LOG = logging.getLogger(__package__)
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
ACCEPT = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
def download_to(session, url, target):
LOG.debug("Downloading %s to %s", url, target)
response = session.get(url, headers={'Accept': ACCEPT, 'User-Agent': USER_AGENT} )
if not response.history or response.status_code==200:
html = response.text
try:
open(target, "w").write(html)
LOG.debug(" Wrote {} to {}".format(url, target))
return True
except OSError:
LOG.error(" Failed writing {} to {}".format(url, target))
else:
LOG.error(" Server error {} to {}".format(url, response.status_code))
return False
def verify_session(session, response = None):
#TODO check if session is logged in
LOG.debug("verifying session on %s", response.url)
return response.status_code == 200 and response.url.endswith("/default.asp?p=adm")
def login(url, username, password, league_id=14):
LOG.debug("Logging in to %s using %s", url, username)
s = requests.session()
r = s.post(url, headers={'Accept': ACCEPT, 'User-Agent': USER_AGENT}, data={"user":username, "pass":password, 'ligaID': league_id})
if verify_session(s, r):
return s
LOG.error("Could not verify session")
print(r.content)
sys.exit("Could not verify session")
def new_session():
return requests.session()
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
session=login("http://www.anarchy.bloodbowlleague.com/login.asp", sys.argv[1], sys.argv[2])
print("{}".format(session.cookies))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,705 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/create.py | #!/usr/bin/env python
""" Create new team """
import sys
import logging
import scrape.session
LOG = logging.getLogger(__package__)
def create_match(session, tournament_id, home_id, away_id, tround, mdate=None, tournament_match=True):
LOG.debug("Creating match '%s' '%s' '%s' '%s' '%s' '%s'", tournament_id, home_id, away_id, tround, mdate, tournament_match)
match_form = {
"m0team1": home_id,
"m0team2": away_id,
"dato": mdate,
"puljekamp": 1 if tournament_match else 0,
"runde": tround,
"retid": 0}
response = session.post("http://test.bloodbowlleague.com/addmatch.asp?s={}&ret=0".format(tournament_id), data=match_form)
return response
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
if len(sys.argv) < 4:
sys.exit("username password home_id away_id")
s = scrape.session.login("http://test.bloodbowlleague.com/login.asp", username=sys.argv[1], password=sys.argv[2])
home_id = sys.argv[3]
away_id = sys.argv[4]
if s:
LOG.debug("Session seems OK")
else:
sys.exit("session not ok?")
response=create_match(s, 2, home_id, away_id, "runde 1", mdate="7/21/2018")
print(response)
print(response.text)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,706 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/test_parse.py | from bs4 import BeautifulSoup
import match.parse
def test_parse_match_works_for_unplayed():
soup = BeautifulSoup(open("match/testdata/unplayed_match.html", "rb").read().decode("iso-8859-1"), "lxml")
played_match = match.parse.parse_match(1161, soup)
assert "approved" in played_match
assert not played_match["approved"]
assert "home_team" in played_match
assert "away_team" in played_match
assert played_match["home_teamid"] == "ank"
assert played_match["home_team"] == "Ankerskogen Blodbaderklubb"
assert played_match["away_teamid"] == "boer"
def test_parse_match_works_for_approved():
soup = BeautifulSoup(open("match/testdata/match-1113.html", "rb").read().decode("iso-8859-1"), "lxml")
played_match = match.parse.parse_match(1161, soup)
assert "approved" in match
assert played_match["home_teamid"] == "wam"
assert played_match["home_team"] == "Wampire Counts von Norway"
assert played_match["away_teamid"] == "und"
assert played_match["away_team"] == "Underworld Overlords"
def test_return_false_on_invalid_match():
soup = BeautifulSoup(open("match/testdata/invalid.html", "rb").read().decode("iso-8859-1"), "lxml")
played_match = match.parse.parse_match(1043, soup)
assert not played_match
def test_parse_return_foul_casualties():
soup = BeautifulSoup(open("match/testdata/match-1190.html", "rb").read().decode("iso-8859-1"), "lxml")
casualties = match.parse.find_casualties(soup)
assert "home_cas_foul" in casualties
assert "away_cas_foul" in casualties
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,707 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/index.py | #!/usr/bin/env python3
"""Create index file for dataset. Require template index.html"""
import datetime
from team import team
from coach import coach
from stats.match_list import list_all_matches
from export import export
def create_index(data):
"""Create and return a template containing site index"""
games = list_all_matches(data)
coaches = coach.list_coaches()
teams = team.list_teams()
time_of_update = '{0:%Y-%m-%d %H:%M}'.format(datetime.datetime.now())
return export.get_template("index.html").render(
time_of_update=time_of_update,
number_of_coaches=len(coaches),
number_of_teams=len(teams),
number_of_games=len(games),
latest_games=games[:10]
)
def index():
"""create_index and write file to disk"""
import stats.collate
collated_data = stats.collate.collate()
"""create_index and write file to disk"""
with open("output/index.html", "w") as filepointer:
filepointer.write(create_index(collated_data))
if __name__ == "__main__":
print("Exporting index")
index()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,708 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/player.py | #!/usr/bin/env python3
""" Python libraries for Dr.Tide"""
import sys
import os
import os.path
import collections
import logging
import json
import player.load
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def load_fromjson(basepath = BASEPATH, filepath="json/players.json"):
path = os.path.join(basepath, filepath)
with open(path, "r") as infile:
return json.load(infile)
def dict_players(basepath = BASEPATH, filepath="json/players.json"):
path = os.path.join(basepath, filepath)
if os.path.isfile(path):
return load_fromjson()
players = {}
for p in list(player.load.load_all()):
players[p["playerid"]] = p
with open(path, "w") as outfile:
json.dump(players, outfile)
return players
def main():
import pprint
interested = sys.argv[1:] if len(sys.argv) > 1 else []
for p in dict_players().values():
if len(interested) == 0 or p["playerid"] in interested:
pprint.pprint(p, indent=4)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,709 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/match/match.py | #!/usr/bin/env python3
import logging
from match import load
from match import parse
LOG = logging.getLogger(__package__)
def open_match(filename):
matchid = filename[filename.find("match-") + 6:filename.rfind(".html")]
return parse.parse_match(matchid, load.from_file(filename))
def collate_gamedata(games, id=None):
LOG.debug("collate %s gamedata looking for %s", len(games), id if id else "last entry")
return [m for m in games if m["matchid"] in id] if id else [games[-1]]
def dict_games():
games = {}
for g in match_list():
games[g["matchid"]] = g
return games
def match_list():
games = load.from_json()
return games
import stats.collate
data = stats.collate.collate()
return data["game"].values() if "game" in data else load.from_json()
def main():
import sys
import pprint
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
LOG.info("Loading matches")
matchid = sys.argv[1:] if len(sys.argv) > 1 else None
matches = list(collate_gamedata(match_list(), matchid))
pprint.pprint(matches, indent=4, width=160)
if len(sys.argv[1:]) > 1: print("Found {} of {}".format(len(matches), len(sys.argv[1:])))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,710 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/importer/bbleague/update.py | #!/usr/bin/env python
""" Import data from bloodbowlleague.com """
import sys
import logging
import scrape.fetch_teamlist
import scrape.fetch_coachlist
import match.fetch
LOG = logging.getLogger(__package__)
def load_config(section):
import configparser
config = configparser.ConfigParser()
LOG.info("Loading config from bbl-scrape.ini using %s", section)
config.read("bbl-scrape.ini")
if section not in config.sections():
LOG.error("No such section %s in bbl-scrape.ini", section)
sys.exit("Giving up")
return config[section]
def import_bbleague(config):
"""Import teamlist, coaches and recent match data from host"""
# LOG.info("Importing data %s to %s", config.get("base_url"), config.get("base_path"))
LOG.info("Importing data")
LOG.info("base_url %s", config.get("base_url"))
LOG.info("base_path %s", config.get("base_path"))
LOG.info("Update teams")
scrape.fetch_teamlist.download_team_list(base_url=config.get("base_url"),
username=config.get("username"),
password=config.get("password"),
base_path=config.get("base_path"))
LOG.info("Update coaches")
scrape.fetch_coachlist.download_coach_list(base_url=config.get("base_url"),
username=config.get("username"),
password=config.get("password"),
base_path=config.get("base_path"))
LOG.info("Update recent matches")
match.fetch.recent_matches(base_url=config.get("base_url"),
base_path=config.get("base_path"),
force=True)
def main():
"""Run import_bloodbowlleague from command line"""
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
import_bbleague(sys.argv[1], sys.argv[2], sys.argv[3])
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,711 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/stats/team_list.py | #!/usr/bin/env python3
from collections import Counter
import copy
from operator import itemgetter
import logging
from match import match
from team import team
from coach import coach
LOG = logging.getLogger(__package__)
def team_data(the_team, team_matches):
data_for_team = {}
data_for_team["head_coach"] = the_team["coach"]
data_for_team["co_coach"] = the_team["co-coach"]
data_for_team["retired_coach"] = set([match["home_coach"] for match in team_matches if match["home_coach"] not in [the_team["coach"], the_team["co-coach"]]])
data_for_team["last_game"] = team_matches[0]["date"] if len(team_matches) > 0 else "Never"
data_for_team["first_game"] = team_matches[-1]["date"] if len(team_matches) > 0 else None
data_for_team["gamesplayed"] = len(team_matches)
data_for_team["teamvalue"] = the_team["teamvalue"]
return data_for_team
def matchresult(match, team1, team2):
return {"teamid": match[team1+"_teamid"],
'td_for': match[team1+"_td"],
'td_against': match[team2+"_td"],
'cas_for': match[team1+"_cas"],
'cas_against': match[team2+"_cas"],
'kill_for': match[team1+"_dead"],
'kill_against': match[team2+"_dead"],
'matchid': match["matchid"],
'date': match["date"],
"result": match[team1+"_result"],
"coach": match[team1+"_coachid"],
"coach_against": match[team2+"_coachid"]
}
def add_result(result, match):
#import pprint
#pprint.pprint(match, indent=4, width=200)
teamid = match["teamid"]
if not teamid in result:
result[teamid] = { "teamid": teamid,
"W": 0, "L": 0, "T": 0 ,
'td_for': 0,
'td_against': 0,
'cas_for': 0,
'cas_against': 0,
'kill_for': 0,
'kill_against': 0,
'matches': [],
'coaches': Counter(),
'first_match': None,
'last_match': None}
result[teamid][match["result"]] = result[teamid][match["result"]] + 1
result[teamid]["td_for"] = result[teamid]["td_for"] + match["td_for"]
result[teamid]["td_against"] = result[teamid]["td_against"] + match["td_against"]
result[teamid]["cas_for"] = result[teamid]["cas_for"] + match["cas_for"]
result[teamid]["cas_against"] = result[teamid]["cas_against"] + match["cas_against"]
result[teamid]["kill_for"] = result[teamid]["kill_for"] + match["kill_for"]
result[teamid]["kill_against"] = result[teamid]["kill_against"] + match["kill_against"]
result[teamid]["matches"].append(match["matchid"])
if result[teamid]["first_match"] == None or result[teamid]["first_match"] > match["date"]:
result[teamid]["first_match"] = match["date"]
if result[teamid]["last_match"] == None or result[teamid]["last_match"] < match["date"]:
result[teamid]["last_match"] = match["date"]
result[teamid]["coaches"][match["coach"]] += 1
def rank(matches):
result = {}
for match in matches:
add_result(result, matchresult(match, "home", "away"))
add_result(result, matchresult(match, "away", "home"))
return result
def add_teamdata(ranking):
all_teams = team.dict_teams()
all_coaches = coach.dict_coaches()
result = []
for rankedteam in ranking.values():
rankedteam["team"] = all_teams[rankedteam["teamid"]]
rankedteam["coach"] = all_coaches[rankedteam["team"]["coach"]] if rankedteam["team"]["coach"] else ""
#Retired team can have coach==None
rankedteam["coaches"] = rankedteam["coaches"].items()
return ranking
def format_for_teamlist(ranked_team):
#import pprint
#pprint.pprint(ranked_team, indent=4, width=200)
return {"teamid": ranked_team["teamid"],
"name": ranked_team["team"]["name"],
"race": ranked_team["team"]["race"],
"coach": ranked_team["team"]["coach"],
"teamvalue": ranked_team["team"]["teamvalue"]/1000 if ranked_team["team"]["teamvalue"] else 0,
"gamesplayed": len(ranked_team["matches"]),
"first_match": ranked_team["first_match"],
"last_match": ranked_team["last_match"],
"coach_count": len(ranked_team["coaches"]),
"coaches": ranked_team["coaches"],
"win": ranked_team["W"],
"tie": ranked_team["T"],
"loss": ranked_team["L"],
"performance": (((ranked_team["W"]*2)+(ranked_team["T"]*1))/ (len(ranked_team["matches"])*2))*100,
"td": ranked_team["td_for"] - ranked_team["td_against"],
"td_for": ranked_team["td_for"],
"td_against": ranked_team["td_against"],
"cas": ranked_team["cas_for"] - ranked_team["cas_against"],
"cas_for": ranked_team["cas_for"],
"cas_against": ranked_team["cas_against"],
"kill": ranked_team["kill_for"] - ranked_team["kill_against"],
"kill_for": ranked_team["kill_for"],
"kill_against": ranked_team["kill_against"],
"points": (ranked_team["W"]*5)+(ranked_team["T"]*3)+ranked_team["L"]
}
def format_for_average(teams):
gamesplayed = sum(map(lambda x: x["gamesplayed"], teams))
wins = sum(map(lambda x: x["win"], teams))
ties = sum(map(lambda x: x["tie"], teams))
formatted = {"win": sum(map(lambda x: x["win"], teams))/gamesplayed if gamesplayed > 0 else 0,
"tie": sum(map(lambda x: x["tie"], teams))/gamesplayed if gamesplayed > 0 else 0,
"loss" : sum(map(lambda x: x["loss"], teams))/gamesplayed if gamesplayed > 0 else 0,
"td": sum(map(lambda x: x["td_for"]/gamesplayed-x["td_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"td_for": sum(map(lambda x: x["td_for"], teams))/gamesplayed if gamesplayed > 0 else 0,
"td_against": sum(map(lambda x: x["td_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"cas": sum(map(lambda x: x["cas_for"]/gamesplayed-x["cas_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"cas_for": sum(map(lambda x: x["cas_for"], teams))/gamesplayed if gamesplayed > 0 else 0,
"cas_against": sum(map(lambda x: x["cas_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"kill": sum(map(lambda x: x["kill_for"]/gamesplayed-x["kill_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"kill_for": sum(map(lambda x: x["kill_for"], teams))/gamesplayed if gamesplayed > 0 else 0,
"kill_against": sum(map(lambda x: x["kill_against"], teams))/gamesplayed if gamesplayed > 0 else 0,
"performance" : sum(map(lambda x: x["performance"], teams)) / len(teams) if len(teams) > 0 else 0, #(wins*2+ties)/(gamesplayed*2)*100 if gamesplayed > 0 else 0,
"gamesplayed": gamesplayed/len(teams) if len(teams) > 0 else 0,
"points": sum(map(lambda x: x["points"], teams))/gamesplayed if gamesplayed > 0 else 0
}
return formatted
def format_for_total(teams):
gamesplayed = sum(map(lambda x: x["gamesplayed"], teams))
wins = sum(map(lambda x: x["win"], teams))
ties = sum(map(lambda x: x["tie"], teams))
return {"win": sum(map(lambda x: x["win"], teams)),
"tie": sum(map(lambda x: x["tie"], teams)),
"loss" : sum(map(lambda x: x["loss"], teams)),
"td": sum(map(lambda x: x["td_for"]-x["td_against"], teams)),
"td_for": sum(map(lambda x: x["td_for"], teams)),
"td_against": sum(map(lambda x: x["td_against"], teams)),
"cas": sum(map(lambda x: x["cas_for"]-x["cas_against"], teams)),
"cas_for": sum(map(lambda x: x["cas_for"], teams)),
"cas_against": sum(map(lambda x: x["cas_against"], teams)),
"kill": sum(map(lambda x: x["kill_for"]-x["kill_against"], teams)),
"kill_for": sum(map(lambda x: x["kill_for"], teams)),
"kill_against": sum(map(lambda x: x["kill_against"], teams)),
"performance" : (wins*2+ties)/(gamesplayed*2)*100 if gamesplayed > 0 else 0,
"gamesplayed": gamesplayed,
"points": sum(map(lambda x: x["points"], teams))
}
def rank_teams(matches):
teamlist = list(map(format_for_teamlist, matches))
teams = sorted(teamlist, key=itemgetter("name"))
teams = sorted(teams, key=lambda x: x["cas_for"]-x["cas_against"], reverse=True)
teams = sorted(teams, key=lambda x: x["td_for"]-x["td_against"], reverse=True)
teams = sorted(teams, key=itemgetter("points"), reverse=True)
return teams
def list_all_teams_by_year(year):
start_date = "{}-99-99".format(year-1)
end_date = "{}-00-00".format(int(year)+1)
return list_all_teams_by_period(start_date, end_date)
def list_all_teams_by_period(start_date, end_date):
matches = filter(
lambda x: x["date"] > start_date and x["date"] < end_date,
match.match_list())
return list(rank_teams(add_teamdata(rank(matches)).values()))
def list_all_teams_by_points(data=None, games=None):
gamesplayed = games
if not games and data:
gamesplayed = data["game"].values()
elif not games:
gamesplayed = match.match_list()
return list(rank_teams(add_teamdata(rank(gamesplayed)).values()))
def team_count_by_race(teams):
team_count = {}
for t in teams:
if t["race"] not in team_count:
team_count[t["race"]] = 0
team_count[t["race"]] = team_count[t["race"]] + 1
return team_count
def list_all_games_by_race(data, no_mirror=False):
# return list_all_teams_by_points()
matches = copy.deepcopy(list(data["game"].values()))
teams = data["team"]
team_count = team_count_by_race(teams.values())
for m in matches:
m["home_teamid"] = teams[m["home_teamid"]]["race"]
m["away_teamid"] = teams[m["away_teamid"]]["race"]
matches = rank( filter(lambda m: m["home_teamid"] != m["away_teamid"], matches) if no_mirror else matches)
for m in matches.values():
m["team"] = {"coach": "-", "race": "{} ({})".format(m["teamid"], team_count[m["teamid"]]), "name": m["teamid"], "teamid": m["teamid"], "teamvalue": ""}
m["coach"] = "-"
return sorted(
sorted(
rank_teams(
matches.values()),
key=itemgetter("performance"),
reverse=True),
key = lambda x: x["gamesplayed"] > 24,
reverse=True)
def main():
import pprint
import sys
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
for t in filter(lambda x: not "gamesplayed" in x or x["gamesplayed"] > 0, list_all_teams_by_year(int(sys.argv[1]) if len(sys.argv) > 1 else 2017)):
print("{}:".format(t["name"] if "name" in t else t["team"]["name"]))
pprint.pprint(t, indent=4, width=250)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,712 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/all_data.py | #!/usr/bin/env python3
"""Run the entire process of generating stats and exporting to HTML. Run from commandline or as an import.
Progess is written to stdout using print"""
import datetime
from export import game_data, coach_data, race_data, index, team_data, player_data
def export_all_data(config=None):
"""Export all data to HTML"""
import stats.collate
collated_data = stats.collate.collate()
print("Exporting all data")
print("Exporting teams by points")
team_data.export_all_teams(collated_data)
print("Exporting teams by year")
team_data.teams_by_year(collated_data, 2007, datetime.datetime.now().year+1)
print("Exporting games by date")
game_data.export_games_by_date(collated_data)
print("Exporting games by year")
game_data.games_by_year(collated_data, 2007, datetime.datetime.now().year+1)
print("Exporting games by team")
team_data.all_games_by_team(collated_data)
print("Exporting races by performance")
race_data.export_race_by_performance(collated_data)
print("Exporting teams by race")
race_data.teams_by_race(collated_data)
print("Exporting coach")
coach_data.teams_by_coach(collated_data)
print("Exporting coaches")
coach_data.all_coaches(collated_data)
print("Exporting coaches by year")
coach_data.all_coaches_by_year(collated_data)
print("Exporting players")
player_data.all_players(collated_data)
print("Exporting index")
index.index()
def main():
"""Run from commandline. Add --rsync to copy data to server"""
import sys
export_all_data()
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,713 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/game_data.py | #!/usr/bin/env python3
"""Write all game data to disk using jinja2 templates"""
import datetime
from team import team
from stats.team_list import list_all_teams_by_points, list_all_games_by_race
from stats.match_list import list_all_matches, list_all_games_by_year
from stats.team_list import format_for_total, format_for_average
from export import export, coach_data, race_data
from export import index
def all_games_by_year(data, year):
return export.get_template("game/all_games.html").render(
matches = list_all_games_by_year(data, year),
title="All games in {}".format(year),
subtitle="sorted by date")
def all_games(data):
games = list_all_matches(data)
return export.get_template("game/all_games.html").render(
matches = games,
title="All games",
subtitle="sorted by date")
def games_by_year(data, start, end):
games = list_all_matches(data)
for year in range(start, end):
with open("output/games-{}.html".format(year), "w") as teams:
teams.write(all_games_by_year(data, year))
def export_games_by_date(data):
with open("output/games.html", "w") as matches:
matches.write(all_games(data))
def main():
import stats.collate
collated_data = stats.collate.collate()
print("Exporting games by date")
with open("output/games.html", "w") as matches:
matches.write(all_games(collated_data))
print("Exporting games by year")
games_by_year(collated_data, 2007, datetime.datetime.now().year+1)
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,714 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/export/filter.py | def coach_anchor(input):
#return input
if not input:
return "None"
return "<a href='coach/{}.html'>{}</a>".format(input.replace(' ','-'), input)
def team_value(input):
if not input:
return "Unknown"
return "{}k".format(int(input/1000))
def race_short(input):
lowered_input = input.lower()
if not input:
return ""
if "undead" in lowered_input or "renegades" in lowered_input:
return input.split(" ")[-1]
if "horne" in lowered_input or "underworld" in lowered_input or "necromantic" in lowered_input or "chosen" in lowered_input:
return input.split(" ")[0]
if "union" in lowered_input:
return "{}lf".format(input[0])
return input
def race_link(input):
return "race/{}.html".format(input.replace(' ', '-'))
def team_link(input):
return "team/{}.html".format(input.replace(' ', '-'))
def player_link(input):
return "player/{}.html".format(input.replace(' ', '-'))
def load_filter(environment):
environment.filters["race_short"] = race_short
environment.filters["race_link"] = race_link
environment.filters["player_link"] = player_link
environment.filters["team_link"] = team_link
environment.filters["coach_anchor"] = coach_anchor
environment.filters["team_value"] = team_value
return environment
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,715 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/coach/coach.py | #!/usr/bin/env python
import sys
import os
import json
import logging
from coach import parse
import coach.parse_from_team
from importer.bbleague.defaults import BASEPATH
LOG = logging.getLogger(__package__)
def dict_coaches(use_key="nick"):
coaches = list_coaches()
result = {}
for coach in coaches:
result[coach[use_key]] = coach
# result[coach["uid"]] = coach
return result
def dict_coaches_by_uid():
return dict_coaches("uid")
def load_from_json(basepath = BASEPATH):
LOG.debug("Loading %sjson/coaches.json", basepath)
data = open(basepath + "json/coaches.json", "rb").read()
return json.loads(data.decode())
def save_to_json(coaches, basepath = BASEPATH):
LOG.debug("Saving %s/json/coaches.json", basepath)
data = json.dumps(coaches)
json_file = open(basepath+"json/coaches.json", "wb")
json_file.write(data.encode())
json_file.close()
def load_from_parser(basepath = BASEPATH):
LOG.debug("Loading from parser")
LOG.debug("Data root is %s", basepath)
if parse.data_exists(basepath):
LOG.debug("Found data for parse")
return parse.load(basepath)
elif coach.parse_from_team.data_exists(basepath):
LOG.debug("Found data for parse_from_team")
return coach.parse_from_team.list_coaches(basepath)
LOG.error("Found no usable coach data")
sys.exit(1)
def list_coaches(basepath = BASEPATH):
if not os.path.isfile(basepath + "json/coaches.json") or (
os.path.isfile(basepath + "html/coach/coaches-8.html") and os.stat(basepath + "json/coaches.json").st_mtime < os.stat(
basepath + "html/coach/coaches-8.html").st_mtime):
coaches = load_from_parser(basepath)
save_to_json(coaches, basepath)
return coaches
return load_from_json(basepath)
def find_uid_for_nick(coaches, nick):
for the_coach in coaches.values():
if the_coach["nick"].lower() == nick.lower():
return the_coach["uid"]
return None
# return [key for key, value in coaches if value["nick"] == nick]
def parse_options():
LOG.debug("Options: %s ", sys.argv)
if len(sys.argv) < 2:
LOG.debug("Less than 2 options")
return BASEPATH, None
if os.path.isdir(sys.argv[1]):
LOG.debug("Argument 1 is a directory")
return sys.argv[1], sys.argv[2:] if len(sys.argv) > 2 else None
LOG.debug("Argument 1 is not a directory")
return BASEPATH, sys.argv[1:]
#= sys.argv[1] if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]) else "input/bloodbowlleague/anarchy.bloodbowlleague.com/"
#search_options = sys.argv[1:] if not os.path.isdir(sys.argv[1]) else sys.argv[2:]
def main():
log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=log_format)
basepath, search_options = parse_options()
LOG.debug("%s :: %s", basepath, search_options)
LOG.info("Loading coaches")
coaches = list_coaches(basepath)
for coach in coaches:
if not search_options or coach["nick"] == " ".join(search_options) or coach["nick"] in search_options or coach[ "uid"] in search_options:
print(coach)
print("Total: {}".format(len(coaches)))
if __name__ == "__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,716 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/importer/__main__.py | #!/usr/bin/env python3
import sys
from importer import bbleague
if __name__ == '__main__':
host = "www.anarchy.bloodbowlleague.com"
username = sys.argv[1]
password = sys.argv[2]
bbleague.import_bloodbowlleague(host, username, password)
#all_data.export_all_data()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,717 | ketilkn/bloodbowl-utility | refs/heads/master | /bbl-scraper/player/display.py | #!/usr/env python3
import sys
import player.player
from .load import load_all
def plformat(p):
return "{:>4} {:>32} {:>18} t:{:<4} c:{:>2} p:{:>3} i:{:>2} m:{:>2} g:{:>2} *:{:>3} {} {}".format(
p["playerid"],
p["playername"],
p["position"][:18],
p["team"] if p["team"] else "0000",
p["spp"]["casualty"],
p["spp"]["completion"],
p["spp"]["interception"],
p["spp"]["mvp"],
p["spp"]["td"],
p["spp"]["total"],
",".join(p["upgrade"]["normal"]+p["upgrade"]["extra"]+p["status"]["injury"]),
p["status"]["active"]["reason"])
def plprint(p, end='\n'):
print(plformat(p) , end=end)
def psa(players):
for p in players:
plprint(p)
def main():
players = list(load_all())
psa(sorted(players, key=lambda p: int(p["spp"]["total"]) if p["spp"]["total"] else 0))
if __name__=="__main__":
main()
| {"/bbl-scraper/coach/parse_from_team.py": ["/bbl-scraper/coach/coach.py"], "/bbl-scraper/player/display.py": ["/bbl-scraper/player/load.py"]} |
44,718 | manu621311/ss42 | refs/heads/master | /company/api/urls.py | from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
urlpatterns = [
path('register/', views.Company.as_view({'post': 'create'})),
path('view/', views.CompanyRead.as_view({'get': 'list'})),
path('post/', views.PostViewSet.as_view({'get': 'list'})),
]
| {"/company/api/views.py": ["/company/models.py"]} |
44,719 | manu621311/ss42 | refs/heads/master | /accounts/urls.py | from .views import create_verification, confirm_verification
from django.urls import path
urlpatterns = [
path('create/<int:id>', create_verification),
path('confirm/<str:complex>/<int:id>/<int:otp>', confirm_verification),
]
| {"/company/api/views.py": ["/company/models.py"]} |
44,720 | manu621311/ss42 | refs/heads/master | /company/models.py | from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
dev_name = models.CharField(max_length=80, null=False)
company_name = models.CharField(max_length=80, null=True)
email = models.EmailField(null=False)
city = models.CharField(max_length=100, null=False)
country = models.CharField(max_length=255, null=False)
description = models.TextField(max_length=1024, null=False)
api_key = models.TextField(max_length=1024, null=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.dev_name
| {"/company/api/views.py": ["/company/models.py"]} |
44,721 | manu621311/ss42 | refs/heads/master | /company/api/views.py | import json
from rest_framework.views import APIView
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, AllowAny
from rest_framework_api_key.permissions import HasAPIKey
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from django.http import JsonResponse, HttpResponse
from rest_framework import status
from rest_framework_api_key.models import APIKey
from django.db import close_old_connections
from company.api.serializers import CompanySerializer, CompanySerializer_read # Importing serializer
from posts.api.serializers import PostSerializer_read
from company.models import Company # Importing models
from posts.models import Post
from rest_framework import filters
generic_emails = ['gmail', 'yahoo', 'rediff', 'outlook', 'yandex', 'aol', 'gmx', ]
class CompanyRead(viewsets.ModelViewSet):
permission_classes =[HasAPIKey, ]
authentication_classes =()
serializer_class = CompanySerializer
queryset = Company.objects.all()
http_method_names = ['get']
def get_queryset(self):
key = self.request.META['HTTP_API_KEY']
company = APIKey.objects.get_from_key(key)
return self.queryset.filter(company_name=company)
# def list(self, request, *args, **kwargs):
# key = request.META['HTTP_API_KEY']
# company = APIKey.objects.get_from_key(key)
# return Response({ "detail": "Method \"GET\" not allowed..." }, status=status.HTTP_405_METHOD_NOT_ALLOWED)
class Company(viewsets.ModelViewSet):
permission_classes =[]
authentication_classes =()
serializer_class = CompanySerializer_read
queryset = Company.objects.all()
def create(self, request, *args, **kwargs):
request.data._mutable = True
i = self.request.data['email'].index('@')
company_name = self.request.data['email'][i+1:]
j = company_name.index('.')
company_name = company_name[:j]
if company_name in generic_emails:
return Response({ "detail": "Please register with your company email !!" }, status=status.HTTP_403_FORBIDDEN)
self.request.data["company_name"] = company_name
if self.queryset.filter(company_name=company_name):
print(True)
self.request.data["api_key"] = self.queryset.filter(company_name=company_name)[0].api_key
else:
print(False)
api_key, key = APIKey.objects.create_key(name=self.request.data['company_name'])
self.request.data["api_key"] = str(key)
# serializer = self.get_serializer(data=request.data)
serializer = CompanySerializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
class PostViewSet(viewsets.ModelViewSet):
close_old_connections()
queryset = Post.objects.all()
filter_backends = (filters.SearchFilter,)
search_fields = ['url']
permission_classes =[HasAPIKey, ]
authentication_classes =()
serializer_class = PostSerializer_read
close_old_connections()
| {"/company/api/views.py": ["/company/models.py"]} |
44,725 | andrewixl/satoshitraveler | refs/heads/master | /apps/login_app/models.py | from __future__ import unicode_literals
from django.db import models
import re
import bcrypt
# Create your models here.
class UserManager(models.Manager):
def registerVal(self, postData):
results = {'status': True, 'errors': [], 'user': None}
if len(postData['first_name']) < 3:
results['status'] = False
results['errors'].append('First Name must be at least 3 chars.')
if len(postData['last_name']) < 3:
results['status'] = False
results['errors'].append('Last Name must be at least 3 chars.')
if not re.match(r"[^@]+@[^@]+\.[^@]+", postData['email']):
results['status'] = False
results['errors'].append('Please enter a valid email.')
if len(postData['password']) < 4 or postData['password'] != postData['c_password']:
results['status'] = False
results['errors'].append('Please enter a valid password.')
user = User.objects.filter(email = postData['email'])
print user, '*****', len(user)
if len(user) >= 1:
results['status'] = False
results['errors'].append('User already exists')
#check to see if user is not in db
return results
def createUser(self, postData):
p_hash = bcrypt.hashpw(postData['password'].encode(), bcrypt.gensalt())
user = User.objects.create(first_name = postData['first_name'], last_name = postData['last_name'], email = postData['email'], password = p_hash,)
return user
def loginVal(self, postData):
results = {'status': True, 'errors': [], 'user': None}
results['user'] = User.objects.filter(email = postData['email'])
if len(results['user'] ) <1:
results['status'] = False
results['errors'].append('Something went wrong')
else:
hashed = bcrypt.hashpw(postData['password'].encode(), results['user'][0].password.encode())
if hashed != results['user'][0].password:
results['status'] = False
results['errors'].append('Something went wrong')
return results
class User(models.Model):
first_name = models.CharField(max_length = 400)
last_name = models.CharField(max_length = 400)
email = models.CharField(max_length = 400)
password = models.CharField(max_length = 400)
satoshi = models.FloatField(default=0)
section_1_level = models.IntegerField(default=1)
section_2_level = models.IntegerField(default=0)
section_3_level = models.IntegerField(default=0)
section_4_level = models.IntegerField(default=0)
section_5_level = models.IntegerField(default=0)
section_6_level = models.IntegerField(default=0)
section_7_level = models.IntegerField(default=0)
section_8_level = models.IntegerField(default=0)
section_9_level = models.IntegerField(default=0)
section_10_level = models.IntegerField(default=0)
section_11_level = models.IntegerField(default=0)
section_12_level = models.IntegerField(default=0)
objects = UserManager()
def __str__(self):
return self.first_name + " " + self.last_name
| {"/apps/main/views.py": ["/apps/login_app/models.py"]} |
44,726 | andrewixl/satoshitraveler | refs/heads/master | /apps/login_app/urls.py | from . import views
from django.conf.urls import url
def test(request):
print 'in app'
urlpatterns = [
url(r'^login$', views.index),
url(r'^register$', views.register),
url(r'^login_verify$', views.login_verify),
url(r'^logout$', views.logout),
]
| {"/apps/main/views.py": ["/apps/login_app/models.py"]} |
44,727 | andrewixl/satoshitraveler | refs/heads/master | /apps/main/views.py | from django.shortcuts import render, redirect
from ..login_app.models import User
# Create your views here.
def index(request):
return render(request, 'main/index.html')
def dashboard(request):
try:
request.session['user_id']
except KeyError:
return redirect("/login")
user = User.objects.get(id = request.session['user_id'])
context = {
'user': user,
}
return render(request, 'main/dashboard.html', context)
| {"/apps/main/views.py": ["/apps/login_app/models.py"]} |
44,728 | andrewixl/satoshitraveler | refs/heads/master | /apps/login_app/migrations/0002_auto_20180611_0949.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-06-11 16:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='section_10_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_11_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_12_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_1_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_2_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_3_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_4_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_5_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_6_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_7_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_8_level',
field=models.IntegerField(default=1),
),
migrations.AddField(
model_name='user',
name='section_9_level',
field=models.IntegerField(default=1),
),
migrations.AlterField(
model_name='user',
name='satoshi',
field=models.FloatField(default=0),
),
]
| {"/apps/main/views.py": ["/apps/login_app/models.py"]} |
44,729 | andrewixl/satoshitraveler | refs/heads/master | /apps/login_app/urls-100000000000001.py | from . import views
from django.conf.urls import url
def test(request):
print 'in app'
urlpatterns = [
url(r'^login', views.index),
url(r'^register', views.register),
url(r'^verify', views.login),
url(r'^logout', views.logout),
]
| {"/apps/main/views.py": ["/apps/login_app/models.py"]} |
44,750 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventoryapp/admin.py | from django.contrib import admin
from .models import Lender,Borrower
#class PlaceAdmin(admin.ModelAdmin):
# list_display = ('product_name')
#admin.site.register(Lender,LenderAdmin)
admin.site.register(Lender)
admin.site.register(Borrower)
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,751 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventorysite/forms.py | from django import forms
from django.contrib.auth.models import User
class LenderForm(forms.Form):
lender = forms.CharField()
product_name = forms.CharField()
product_description = forms.CharField()
department=forms.CharField()
safety_deposit=forms.IntegerField()
contact_number=forms.IntegerField()
image = forms.FileField()
'''
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')
'''
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,752 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventoryapp/migrations/0003_auto_20200202_0827.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.18 on 2020-02-02 08:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventoryapp', '0002_auto_20200201_2038'),
]
operations = [
migrations.AlterField(
model_name='lender',
name='image',
field=models.FileField(blank=True, null=True, upload_to=''),
),
]
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,753 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventoryapp/views.py |
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from .models import Lender,Borrower
from django.utils import timezone
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from inventorysite.forms import LenderForm
from django.template import RequestContext
from django.shortcuts import render_to_response
from textblob import TextBlob
import random
import re
import nexmo
def logout_inventory(request):
if request.user.is_authenticated():
logout(request)
return redirect('/login/')
else:
return HttpResponseRedirect('/login')
def index(request):
current_mood = api_call()
if(current_mood == "fear"):
music = "/static/audio/Fight_Song.mp3"
elif(current_mood == "anger"):
music = "/static/audio/Let_it_Go.mp3"
elif(current_mood == "sadness"):
music = "/static/audio/burn.mp3"
else:
music = "static/audio/Hall_Of_Fame.mp3"
return render(request,'index.html',{'music':music})
def about(request):
return render(request,'aboutus2.html')
def blog(request):
return render(request,'blogtwo.html')
def portfolio(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a valid chat')
else:
resp,link1,link2,link3=reply(q)
return render(request, 'portfolio-details.html',
{'resp':resp,'link1':link1,'link2':link2,'link3':link3})
return render(request, 'portfolio-details.html',
{'errors': errors})
def shortcodes(request):
return render(request,'shortcodes.html')
def contact(request):
return render(request,'contact2.html')
def arrival(request):
return render(request,'arrival.html')
def service(request):
return render(request,'service.html')
#if request.user.is_authenticated():
#currentuser = request.user
def register(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
name = request.POST.get('name')
username = request.POST.get('sap_id')
user = User.objects.create(
first_name = name,
username = username,
email=email,
)
user.set_password(password)
user.save()
user = authenticate(username = username, password = password)
login(request, user)
return redirect('/login/')
else:
return render(request,'register.html')
def login_inventory(request):
if request.method == 'POST':
username = request.POST.get('sap_id')
password = request.POST.get('password')
user = authenticate(username = username, password = password)
if user :
if user.is_active:
login(request,user)
return redirect('/index/')
else:
return HttpResponse('Disabled Account')
else:
return HttpResponse("Invalid Login details.Are you trying to Sign up?")
else:
return render(request,'register.html')
def lenderform(request):
if request.method == 'POST':
form = LenderForm(request.POST ,request.FILES or None )
if form.is_valid():
cd = form.cleaned_data
Lender.objects.create(lender=cd['lender'],product_name=cd['product_name'],product_description=cd['product_description'],image=request.FILES['image'],department=cd['department'],safety_deposit=cd['safety_deposit'],contact_number=cd['contact_number'])
form = LenderForm()
return render(request,'testlenderform.html',{'form': form})
else:
form = LenderForm()
return render(request, 'testlenderform.html', {'form': form})
def inventorylist(request):
if request.user.is_authenticated():
currentuser = request.user
errors = []
if 'q' in request.GET :
q = request.GET['q']
if not q:
errors.append('Enter a search term.')
elif len(q) > 20:
errors.append('Please enter at most 20 characters.')
else:
items = Lender.objects.filter(product_name__icontains=q)
equipment=items[0]
product_name=equipment.product_name
name=currentuser.first_name
sap_id=currentuser.username
email=currentuser.email
print(currentuser)
student=Borrower(borrower=name,sap_id=sap_id,email=email,product_name=product_name)
student.save()
return render(request, 'inventoryresulttest.html',
{'items': items, 'query': q})
full=Lender.objects.all()
return render(request, 'inventorytest.html',
{'errors': errors,'full':full})
def cart(request):
if request.user.is_authenticated():
currentuser = request.user
name=currentuser.first_name
items = Borrower.objects.filter(borrower__icontains=name)
return render(request, 'cart.html',
{'items':items})
else:
return HttpResponse("Please login")
def arrival(request):
items = Lender.objects.all()
return render(request, 'arrival.html',
{'items':items})
def check_for_anxiety(sentence):
resp = "Believe in yourself and all that you are. Know that there is something inside of you that is greater than any obstacle. I think you should try meditation or yoga. Here are some links that could help you"
link1 ="https://youtu.be/L1QOh-n-eus"
link2="https://youtu.be/_iGWdUTifIQ"
link3="https://youtu.be/nKHBIAdBvZ4"
return resp,link1,link2,link3
def check_for_anger(sentence):
resp = "Holding on to anger is like grasping a hot coal with the intent of throwing it at someone else; you are the one who gets burned. I think you should first calm down, and talk to me, open your heart out. Also, here are some additional videos you could check out and learn to divert your anger into a positive direction. I am always here for you. Lets get this together."
link1 ="https://youtu.be/BsVq5R_F6RA"
link2 ="https://youtu.be/T235jK9xR8Q"
link3="https://youtu.be/de2TdvDaS5A"
return resp,link1,link2,link3
def check_for_sad(sentence):
resp = "Hey, why are you feeling so low. Did you know why you often feel so cold? Because you have a lot of fans. Hahahaha, aint I funny? Let's think about doing some fun things, look at out socialising page or check out these links."
link1 ="https://youtu.be/qHvUUoSj1oM"
link2 ="https://youtu.be/yqHH0IpPupg"
link3="https://youtu.be/UkM-FjfN6Mc"
return resp,link1,link2,link3
def check_for_fear(sentence):
resp = "Be the warrior, not the worrier. Fear does not exist anywhere except in the mind."
link1 ="https://youtu.be/-FyVetL1MEw"
link2 ="https://youtu.be/1XDpa2HLXV0"
link3="https://youtu.be/aE0pRMtQeu0"
return resp,link1,link2,link3
danger_pattern = re.compile("^kill|^die|^suffer|^fail|^quit")
anxiety_pattern = re.compile("^tensed|^worried|^nervous|^panic|^concern|^uneasy|^stressed|^sick")
angry_pattern = re.compile("^angry|^anger|^furious|^hit|^annoyed|^irriated|^fuming|^snap|^fier|^rage|^rant|^storm|^pissed|^red|^boiling|^mad|^swear|^fuck")
sad_pattern = re.compile("^low|^sad|^disappoint|^broken|^fallen|^break|^sorrow|^depressed|^gloomy")
fear_pattern = re.compile("^horror|^scared|^phobia|^terror|^nightmare|^fright|^fear")
def check_for_keywords(sentence):
link1=None
link2=None
link3=None
resp=None
for word in sentence.words:
if danger_pattern.match(word.lower()):
client = nexmo.Client(key='75d84653', secret='SoDG2ayMGG4huX9O')
client.send_message({'from': '13092828727', 'to': '16462339846', 'text': 'This is an Emergency, Please Help me!!',})
resp = "You are strong and have a thousand reasons to be happy :) We are always here for you !"
break
elif anxiety_pattern.match(word.lower()):
resp,link1,link2,link3 =check_for_anxiety(sentence)
break
elif angry_pattern.match(word.lower()):
resp,link1,link2,link3 =check_for_anger(sentence)
break
elif sad_pattern.match(word.lower()):
resp,link1,link2,link3=check_for_sad(sentence)
break
elif fear_pattern.match(word.lower()):
resp,link1,link2,link3 =check_for_fear(sentence)
break
return resp,link1,link2,link3
greeting_pattern = re.compile("^hello|^hi|^greeting|^sup|^what's up|^hey")
GREETING_RESPONSES = ["Hey, welcome ..", "Oh hi there :p ", "Hey there ! " , "Hey, what's up ?"]
NONE_RESPONSES = [
"I didn't get what you said...",
"I didn't understand..",
"Umm, could you please elaborate ? ",
]
def check_for_greeting(sentence):
"""If any of the words in the user's input was a greeting, return a greeting response"""
for word in sentence.words:
if greeting_pattern.match(word.lower()) :
return random.choice(GREETING_RESPONSES)
def request(sentence):
#cleaned = preprocess_text(sentence)
parsed = TextBlob(sentence)
resp= None
link1=None
link2=None
link3=None
resp,link1,link2,link3 = check_for_keywords(parsed)
if not resp:
resp = check_for_greeting(parsed)
if not resp:
resp = random.choice(NONE_RESPONSES)
return resp,link1,link2,link3
def reply(sentence):
resp,link1,link2,link3 = request(sentence)
return resp,link1,link2,link3
def read_log_string():
import re
fp = open('/Users/shreya_naik/logfile.txt', 'r')
s = ""
for i,line in enumerate(fp):
if i == 1 or i == 2:
continue
s += line
# s.replace("[return]", "\n")
ret = ""
skip1c = 0
for i in s:
if i == '[':
skip1c += 1
elif i == ']' and skip1c > 0:
skip1c -= 1
elif skip1c == 0:
ret += i
return (ret)
def api_call():
import json
from ibm_watson import ToneAnalyzerV3
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson import ApiException
authenticator = IAMAuthenticator('OI0G_Rf5fzFMERmUnnbDA6kkyuXM0f_9EYVBUSEJoLSj')
tone_analyzer = ToneAnalyzerV3(
version='2017-09-21',
authenticator=authenticator
)
tone_analyzer.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/1d285fb1-002f-4d28-a024-032d169f7cb0')
text = read_log_string()
tone_analysis = tone_analyzer.tone({'text': text},content_type='application/json').get_result()
c = json.dumps(tone_analysis, indent=2)
#print(c)
#print(tone_analysis["sentences_tone"][-1]["tones"][0]["tone_id"])
return tone_analysis["sentences_tone"][-1]["tones"][0]["tone_id"]
#current_mood = tone_analysis["document_tone"]["tones"][0]["tone_id"]
#print(current_mood)
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,754 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventoryapp/migrations/0002_auto_20200201_2038.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2020-02-01 20:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventoryapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Borrower',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('borrower', models.CharField(max_length=200)),
('sap_id', models.IntegerField()),
('email', models.CharField(max_length=100)),
('product_name', models.CharField(max_length=200)),
],
),
migrations.AddField(
model_name='lender',
name='availability',
field=models.BooleanField(default=True),
),
migrations.AddField(
model_name='lender',
name='department',
field=models.CharField(default='', max_length=100),
),
migrations.AlterField(
model_name='lender',
name='contact_number',
field=models.IntegerField(),
),
migrations.AlterField(
model_name='lender',
name='safety_deposit',
field=models.IntegerField(),
),
]
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,755 | yashinil/HappyHearts | refs/heads/master | /health/inventorysite/inventoryapp/models.py | from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Lender(models.Model):
lender = models.CharField(max_length=200)
image = models.FileField(null=True,blank=True)
product_name = models.CharField(max_length=100)
product_description = models.CharField(max_length=500)
department=models.CharField(max_length=100,default="")
safety_deposit= models.IntegerField()
contact_number= models.IntegerField()
availability=models.BooleanField(default=True)
def __str__(self):
return self.product_name
class Borrower(models.Model):
borrower = models.CharField(max_length=200)
sap_id = models.IntegerField()
email = models.CharField(max_length=100)
product_name=models.CharField(max_length=200)
def __str__(self):
return self.borrower
| {"/health/inventorysite/inventoryapp/admin.py": ["/health/inventorysite/inventoryapp/models.py"], "/health/inventorysite/inventoryapp/views.py": ["/health/inventorysite/inventoryapp/models.py"]} |
44,768 | gatournament/gat-games | refs/heads/master | /tests/game_engine/test_gat_json.py | # coding: utf-8
import tempfile
import unittest
from gat_games.game_engine.gat_json import *
class Normal(object):
def __init__(self):
self.a = 1
class JSONTests(unittest.TestCase):
def test_encode_object(self):
encoded_object = encode_object(Normal())
self.assertEquals(encoded_object, dict(a=1))
def test_dump(self):
obj = dict(a='b', c=1)
fd, filepath = tempfile.mkstemp(text=True)
fd = open(filepath, 'w')
string = dump(obj, fd, sort_keys=True)
fd = open(filepath, 'r')
self.assertEquals(fd.read(), '{"a": "b", "c": 1}')
def test_dumps(self):
obj = dict(a='b', c=1)
string = dumps(obj, sort_keys=True)
self.assertEquals(string, '{"a": "b", "c": 1}')
def test_load(self):
string = '{"a": "b", "c": 1}'
fd, filepath = tempfile.mkstemp(text=True)
fd = open(filepath, 'w')
fd.write(string)
fd.close()
fd = open(filepath, 'r')
obj = load(fd)
self.assertEquals(obj, dict(a='b', c=1))
def test_loads(self):
string = '{"a": "b", "c": 1}'
obj = loads(string)
self.assertEquals(obj, dict(a='b', c=1))
def test_loads_dumps(self):
obj = dict(a='b', c=1)
string = dumps(obj)
obj2 = loads(string)
self.assertEquals(obj, obj2)
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,769 | gatournament/gat-games | refs/heads/master | /tests/game_engine/test_engine.py | # coding: utf-8
import unittest
from nose.tools import raises
from gat_games.game_engine.engine import *
class PlayerTests(unittest.TestCase):
def test_default_name_is_the_class_name_with_the_id(self):
player = Player()
self.assertEquals(True, player.name.startswith('Player'))
def test_custom_name(self):
player = Player('me')
self.assertEquals('me', player.name)
class GameTests(unittest.TestCase):
def setUp(self):
self.game = Game(1, [Player(), Player()])
self.game.is_the_end = lambda: False
@raises(ValueError)
def test_one_game_must_not_have_players_with_the_same_name(self):
Game(1, [Player(name='x'), Player(name='x')])
def test_summary(self):
report = self.game.summary()
self.assertEquals(True, 'winners' in list(report.keys()))
self.assertEquals(True, 'losers' in list(report.keys()))
self.assertEquals(True, 'error' in list(report.keys()))
self.assertEquals(False, report['draw'])
self.assertEquals(False, report['no_contest'])
self.assertEquals([], report['error_responsibles'])
self.assertEquals(None, report['error'])
self.assertEquals(None, report['error_message'])
def test_error_must_set_reason_and_responsible(self):
p = Player()
try:
self.game.set_runtime_error(p, 'some error', Exception('some error'))
except AlgorithmError:
pass
self.assertEquals('some error', self.game.error_message)
self.assertEquals([str(p)], self.game.error_responsibles)
def test_random_is_reproducible(self):
game1 = Game(1, [])
game2 = Game(1, [])
self.assertEquals(game1.random.randint(1, 100), game2.random.randint(1, 100))
self.assertEquals(game1.random.randint(1, 100), game2.random.randint(1, 100))
def test_gat_error_generate_a_no_contest(self):
class BuggedGame(Game):
def play(self):
raise Exception('ops')
self.game = BuggedGame(1, [Player(), Player()])
self.game.start()
report = self.game.summary()
self.assertEquals(True, report['no_contest'])
class TurnBasedGameTests(unittest.TestCase):
def setUp(self):
self.p1 = Player(name='p1')
self.p2 = Player(name='p2')
self.game = TurnBasedGame(1, [self.p1, self.p2])
self.game.is_the_end = lambda: True
def test_each_player_play_at_a_time_in_cycles(self):
p1 = self.game.players[0]
p2 = self.game.players[1]
self.assertEquals(p1, self.game.next_player())
self.game.player_in_turn = p1
self.assertEquals(p2, self.game.next_player())
self.game.player_in_turn = p2
self.assertEquals(p1, self.game.next_player())
def test_must_start_new_cycle_if_all_players_has_played(self):
p1 = self.game.players[0]
p2 = self.game.players[1]
self.game.player_in_turn = None
self.assertEquals(True, self.game.must_start_new_cycle())
self.game.player_in_turn = p1
self.assertEquals(False, self.game.must_start_new_cycle())
self.game.player_in_turn = p2
self.assertEquals(True, self.game.must_start_new_cycle())
def test_player_strategy_may_raise_exceptions(self):
class BuggedPlayer(Player):
def play(self, context, **kwargs):
raise Exception('ops')
self.p2 = BuggedPlayer('bugged')
self.game = TurnBasedGame(1, [self.p1, self.p2])
self.game.is_the_end = lambda: False
result = self.game.start()
self.assertEquals('ops', result['error_message'])
self.assertEquals([str(self.p2)], result['error_responsibles'])
self.assertEquals(str(self.p1), result['winners'][0])
self.assertEquals(str(self.p2), result['losers'][0])
class GameCompositeTests(unittest.TestCase):
def setUp(self):
self.game = GameComposite(1, [Player(), Player()])
self.game.is_the_end = lambda: True
def test_new_round(self):
newround = self.game.new_round()
self.assertEquals(True, isinstance(newround, self.game.Round))
# self.assertEquals(1, len(self.game.games))
def test_propagate_seed_to_rounds_and_it_is_reproducible(self):
game2 = GameComposite(self.game.seed, [Player(), Player()])
self.assertEquals(self.game.new_round().seed, game2.new_round().seed)
self.assertEquals(self.game.new_round().seed, game2.new_round().seed)
def test_propagate_players_to_rounds(self):
newround = self.game.new_round()
self.assertEquals(self.game.players, newround.players)
def test_propagate_custom_attrs_to_rounds(self):
self.game = GameComposite(1, [Player(), Player()], x=2)
newround = self.game.new_round()
self.assertEquals(2, newround.kwargs['x'])
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,770 | gatournament/gat-games | refs/heads/master | /tests/games/test_pokertexasholdem.py | # coding: utf-8
import unittest
from nose.tools import raises
from gat_games.games.poker_texasholdem import *
class PokerTests(unittest.TestCase):
def setUp(self):
self.p1 = PokerPlayer()
self.p2 = PokerPlayer()
self.poker = Poker(1, [self.p1, self.p2])
def test_game_attributes(self):
self.assertEquals(1000, self.poker.initial_chips)
self.assertEquals(10, self.poker.ante_price)
self.assertEquals(None, self.poker.last_dealer)
self.assertEquals({str(self.p1):0, str(self.p2):0}, self.poker.chips)
def test_poker_initial_chips_and_ante_price_can_be_customizable(self):
self.poker = Poker(1, [], initial_chips=2000, ante_price=20)
self.assertEquals(2000, self.poker.initial_chips)
self.assertEquals(20, self.poker.ante_price)
def test_start_game_distribute_chips_to_each_player(self):
self.assertEquals(0, self.poker.amount_of_chips(self.p1))
self.assertEquals(0, self.poker.amount_of_chips(self.p2))
self.poker.execute_command(StartGameCommand())
self.assertEquals(1000, self.poker.amount_of_chips(self.p1))
self.assertEquals(1000, self.poker.amount_of_chips(self.p2))
def test_end_game_decide_the_winners_based_on_the_chips(self):
self.poker.execute_command(StartGameCommand())
self.poker.add_chips(self.p1, -1000)
self.poker.add_chips(self.p2, 1000)
self.poker.execute_command(EndGameCommand())
self.assertEquals([self.p2], self.poker.winners)
self.assertEquals([self.p1], self.poker.losers)
def test_context(self):
ctx = self.poker.get_context(self.p1)
self.assertEquals(1000, ctx['initial_chips'])
self.assertEquals(10, ctx['ante_price'])
self.assertEquals(None, ctx['last_dealer'])
self.assertEquals({str(self.p1):0, str(self.p2):0}, ctx['chips'])
class PokerRoundTests(unittest.TestCase):
def setUp(self):
self.p1 = PokerPlayer()
self.p2 = PokerPlayer()
self.poker_game = Poker(1, [self.p1, self.p2])
self.poker_game.execute_command(StartGameCommand())
self.poker = PokerRound(1, [self.p1, self.p2])
self.poker.parent = self.poker_game
def test_game_attributes(self):
self.assertEquals(0, self.poker.pot_total)
self.assertEquals({str(self.p1):0, str(self.p2):0}, self.poker.pot)
self.assertEquals(None, self.poker.dealer)
self.assertEquals(Deck(), self.poker.community_cards)
def test_start_round_take_player_chips_to_the_pot(self):
self.poker.execute_command(StartRoundCommand())
self.assertEquals(20, self.poker.pot_total)
self.assertEquals(990, self.poker_game.amount_of_chips(self.p1))
self.assertEquals(990, self.poker_game.amount_of_chips(self.p2))
def test_start_round_decide_the_next_dealer(self):
self.assertEquals(None, self.poker.dealer)
self.assertEquals(None, self.poker_game.last_dealer)
d1 = StartRoundCommand().next_dealer(self.poker)
d2 = self.poker.players[(self.poker.players.index(d1) + 1) % len(self.poker.players)]
self.poker.execute_command(StartRoundCommand())
self.assertEquals(d1, self.poker.dealer)
self.poker_game.last_dealer = d1
self.poker.execute_command(StartRoundCommand())
self.assertEquals(d2, self.poker.dealer)
self.poker_game.last_dealer = d2
self.poker.execute_command(StartRoundCommand())
self.assertEquals(d1, self.poker.dealer)
def test_end_round_update_the_last_dealer(self):
self.assertEquals(None, self.poker_game.last_dealer)
self.poker.execute_command(StartRoundCommand())
self.poker.execute_command(EndRoundCommand())
self.assertEquals(self.poker.dealer, self.poker_game.last_dealer)
def test_deal_distribute_two_cards_for_each_player(self):
self.poker.execute_command(StartRoundCommand())
self.poker.execute_command(DealCardsCommand())
self.assertEquals(2, len(self.poker.hand(self.p1)))
self.assertEquals(2, len(self.poker.hand(self.p2)))
def test_flop_face_up_three_cards_to_the_board(self):
self.poker.execute_command(StartRoundCommand())
self.poker.execute_command(FlopCommand())
self.assertEquals(3, len(self.poker.community_cards))
def test_turn_round_face_up_one_more_card_to_the_board(self):
self.poker.execute_command(StartRoundCommand())
self.poker.execute_command(FlopCommand())
self.poker.execute_command(TurnCommand())
self.assertEquals(4, len(self.poker.community_cards))
def test_river_round_face_up_last_card_to_the_board(self):
self.poker.execute_command(StartRoundCommand())
self.poker.execute_command(FlopCommand())
self.poker.execute_command(TurnCommand())
self.poker.execute_command(RiverCommand())
self.assertEquals(5, len(self.poker.community_cards))
def test_context(self):
ctx = self.poker.get_context(self.p1)
self.assertEquals(0, ctx['pot_total'])
self.assertEquals({str(self.p1):0, str(self.p2):0}, ctx['pot'])
self.assertEquals(None, ctx['dealer'])
self.assertEquals(Deck(), ctx['community_cards'])
class PokerTestBase(unittest.TestCase):
def setUp(self):
self.p1 = PokerPlayer()
self.p2 = PokerPlayer()
self.poker_game = Poker(1, [self.p1, self.p2])
self.poker_game.execute_command(StartGameCommand())
self.poker = PokerRound(1, [self.p1, self.p2])
self.poker.parent = self.poker_game
self.poker.execute_command(StartRoundCommand())
self.poker.play()
self.poker.player_in_turn = self.p1
class PassTests(PokerTestBase):
def test_validate(self):
pass
def test_execute(self):
self.poker.execute_command(Pass(self.p1))
class PayTests(PokerTestBase):
def test_validate(self):
pass
def test_execute(self):
self.poker.execute_command(Pay(self.p1))
class IncreaseBetTests(PokerTestBase):
def test_validate(self):
pass
def test_execute(self):
self.poker.execute_command(IncreaseBet(self.p1))
class GiveUpTests(PokerTestBase):
def test_validate(self):
pass
@raises(EndGame)
def test_execute(self):
self.poker.execute_command(GiveUp(self.p1))
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,771 | gatournament/gat-games | refs/heads/master | /gat_games/games/truco_clean_deck.py | # coding: utf-8
from gat_games.games.truco import *
class TrucoCleanDeckCard(TrucoCard):
ranks = (Q, J, K, AS, 2, 3)
class TrucoCleanDeckDeck(TrucoDeck):
Card = TrucoCleanDeckCard
class TrucoCleanDeckRound(TrucoRound):
Deck = TrucoCleanDeckDeck
class TrucoCleanDeck(Truco):
Round = TrucoCleanDeckRound
class RandomTrucoCleanDeckPlayer(RandomTrucoPlayer):
pass
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,772 | gatournament/gat-games | refs/heads/master | /tests/games/test_truco.py | # coding: utf-8
import unittest
from gat_games.game_engine.cardgame import *
from gat_games.games.truco import *
class TrucoPlayerTests(unittest.TestCase):
def test_gat_player_must_be_serializable(self):
result = json.dumps(TrucoPlayer(['python', 'x']))
self.assertEquals('{}', result)
class TrucoCardTests(unittest.TestCase):
def test_rank_order(self):
self.assertEquals(True, TrucoCard(AS, SPADES) > TrucoCard(K, SPADES))
self.assertEquals(True, TrucoCard(3, SPADES) > TrucoCard(AS, SPADES))
self.assertEquals(True, TrucoCard(3, SPADES) > TrucoCard(K, SPADES))
self.assertEquals(True, TrucoCard(3, SPADES) > TrucoCard(7, SPADES))
self.assertEquals(True, TrucoCard(4, SPADES) < TrucoCard(2, SPADES))
self.assertEquals(True, TrucoCard(4, SPADES) < TrucoCard(AS, SPADES))
self.assertEquals(True, TrucoCard(4, SPADES) < TrucoCard(Q, SPADES))
def test_manilha(self):
self.assertEquals(True, TrucoCard(2, SPADES).is_manilha(TrucoCard(AS, SPADES)))
self.assertEquals(True, TrucoCard(3, SPADES).is_manilha(TrucoCard(2, SPADES)))
self.assertEquals(True, TrucoCard(AS, SPADES).is_manilha(TrucoCard(K, SPADES)))
self.assertEquals(True, TrucoCard(K, SPADES).is_manilha(TrucoCard(J, SPADES)))
self.assertEquals(True, TrucoCard(J, SPADES).is_manilha(TrucoCard(Q, SPADES)))
self.assertEquals(True, TrucoCard(Q, SPADES).is_manilha(TrucoCard(7, SPADES)))
self.assertEquals(True, TrucoCard(4, SPADES).is_manilha(TrucoCard(3, SPADES)))
self.assertEquals(False, TrucoCard(2, SPADES).is_manilha(TrucoCard(2, SPADES)))
self.assertEquals(False, TrucoCard(3, SPADES).is_manilha(TrucoCard(AS, SPADES)))
class TrucoDeckTests(unittest.TestCase):
def test_build(self):
deck = TrucoDeck()
deck.build()
self.assertEquals(10*4, len(deck))
class TrucoRoundTests(unittest.TestCase):
def setUp(self):
self.p1 = TrucoPlayer()
self.p2 = TrucoPlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start_new_cycle()
self.truco.player_in_turn = self.p1
def test_truco_context(self):
context = self.truco.get_context(self.truco.player_in_turn)
print(context)
# self.assertEquals(1, context['game_number'])
self.assertEquals(self.truco.hands[self.truco.player_in_turn.name], context['hand'])
self.assertEquals(self.truco.value, context['round_value'])
self.assertEquals(self.truco.truco_value, context['round_truco_value'])
self.assertEquals(self.truco.center_card, context['round_center_card'])
self.assertEquals(self.truco.table, context['round_table'])
def test_start_distribute_3_cards_to_each_player(self):
self.assertEquals(3, len(self.truco.hands[self.p1.name]))
self.assertEquals(3, len(self.truco.hands[self.p2.name]))
def test_truco_next_player(self):
self.assertEquals(self.p2, self.truco.next_player())
self.truco.player_in_turn = self.truco.next_player()
self.assertEquals(self.p1, self.truco.next_player())
def test_upcard(self):
card = self.truco.hand(self.truco.player_in_turn).see(0)
self.truco.player_in_turn.upcard(card)
self.assertEquals(1, len(self.truco.table))
self.assertEquals(2, self.truco.hands[self.truco.player_in_turn.name].count())
def test_winning_card_without_manilha(self):
card = self.truco.winning_card([TrucoCard(4, SPADES), TrucoCard(3, SPADES)], TrucoCard(AS, SPADES))
self.assertEquals(TrucoCard(3, SPADES), card)
def test_winning_card_with_one_manilha(self):
card = self.truco.winning_card([TrucoCard(3, SPADES), TrucoCard(AS, SPADES)], TrucoCard(K, SPADES))
self.assertEquals(TrucoCard(AS, SPADES), card)
def test_winning_card_with_many_manilhas(self):
card = self.truco.winning_card([TrucoCard(AS, CLUBS), TrucoCard(AS, SPADES)], TrucoCard(K, SPADES))
self.assertEquals(TrucoCard(AS, CLUBS), card)
def test_p1_wins(self):
pass
def test_draw(self):
pass
class DefaultPlayer(TrucoPlayer):
def has_accepted_truco(self, context):
return True
def upcard_or_truco(self, context):
self.upcard(context['hand'].see(0))
class AgressivePlayer(TrucoPlayer):
def has_accepted_truco(self, context):
return True
def upcard_or_truco(self, context):
if self.can_truco(context):
self.truco()
else:
self.upcard(context['hand'].see(0))
class DefensivePlayer(TrucoPlayer):
def has_accepted_truco(self, context):
return False
def upcard_or_truco(self, context):
self.upcard(context['hand'].see(0))
class BuggedPlayer(TrucoPlayer):
def has_accepted_truco(self, context):
return True
def upcard_or_truco(self, context):
self.truco()
class TrucoRoundPlayingTests(unittest.TestCase):
def test_round_without_truco(self):
self.p1 = DefaultPlayer()
self.p2 = DefaultPlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start()
self.assertEquals(None, self.truco.error)
def test_round_with_accepted_truco(self):
self.p1 = AgressivePlayer()
self.p2 = DefensivePlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start()
self.assertEquals(None, self.truco.error)
def test_round_with_gived_up_truco(self):
self.p1 = DefensivePlayer()
self.p2 = DefensivePlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start()
self.assertEquals(None, self.truco.error)
def test_round_only_with_truco(self):
self.p1 = AgressivePlayer()
self.p2 = AgressivePlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start()
self.assertEquals(None, self.truco.error)
def test_bugged_algorithms(self):
self.p1 = BuggedPlayer()
self.p2 = BuggedPlayer()
self.truco = TrucoRound(0, [self.p1, self.p2])
self.truco.start()
self.assertEquals('RE', self.truco.error)
class TrucoTests(unittest.TestCase):
def test_truco_empty_context(self):
truco = Truco(0, [])
self.assertEquals({}, truco.scoreboard)
def test_truco_context(self):
truco = Truco(0, [TrucoPlayer(), TrucoPlayer()])
self.assertEquals([0, 0], list(truco.scoreboard.values()))
def test_round_summary_is_propagated_to_game_summary_in_case_of_error(self):
truco = Truco(0, [BuggedPlayer(), BuggedPlayer()])
truco.start()
self.assertEquals('RE', truco.error)
self.assertEquals('You can not truco until another player re-truco', truco.error_message)
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,773 | gatournament/gat-games | refs/heads/master | /gat_games/games/__init__.py | # coding: utf-8
import sys
if sys.version_info[0] == 2:
from gat_games.games.truco import *
from gat_games.games.truco_clean_deck import *
else:
from .truco import *
from .truco_clean_deck import *
SUPPORTED_GAMES = [Truco, TrucoCleanDeck]
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,774 | gatournament/gat-games | refs/heads/master | /gat_games/games/poker_texasholdem.py | # coding: utf-8
from itertools import combinations
import random
from gat_games.game_engine.engine import *
from gat_games.game_engine.cardgame import *
class PokerPlayer(Player):
def play(self, context, **kwargs):
if kwargs.get('action', 'play') == 'x':
self.blind_bet(context)
def blind_bet(self, context):
self.game.execute_command(BlindBet(self, chips=10))
def bet_pre_flop(self, context): pass
def bet_pos_flop(self, context): pass
def bet_pos_4_card(self, context): pass
def bet_pos_5_card(self, context): pass
def can_increase_the_bet(self, context):
return context['round_can_increase_the_bet']
class RandomPokerPlayer(PokerPlayer):
pass
class PokerCard(Card):
ranks = (AS, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, AS)
class PokerDeck(Deck):
Card = PokerCard
class Pass(PlayerGameCommand):
def validate(self, game, context):
if game.player_in_turn != self.player:
raise InvalidCommandError('Player can not pass right now')
# player has enough chips
# another player increase the bet
def execute(self, game):
pass
class Pay(PlayerGameCommand):
def validate(self, game, context):
if game.player_in_turn != self.player:
raise InvalidCommandError('Player can not pass right now')
# player has enough chips
def execute(self, game):
pass
class IncreaseBet(PlayerGameCommand):
def validate(self, game, context):
if game.player_in_turn != self.player:
raise InvalidCommandError('Player can not pass right now')
# player has enough chips
def execute(self, game):
pass
class GiveUp(PlayerGameCommand):
def validate(self, game, context):
if game.player_in_turn != self.player:
raise InvalidCommandError('Player can not give up right now')
def execute(self, game):
game.remove_player(self.player)
if len(game.players) == 1:
raise EndGame()
class StartGameCommand(StartGameCommand):
def execute(self, game):
for player in game.players:
game.add_chips(player, game.initial_chips)
def read_context(self, game):
for p in game.players:
pass
# game.chips(p) = 1000
class EndGameCommand(EndGameCommand):
def execute(self, game):
max_chips = 0
for player in game.players:
total = game.amount_of_chips(player)
max_chips = max(max_chips, total)
for player in game.players:
total = game.amount_of_chips(player)
if total == max_chips:
game.winners.append(player)
else:
game.losers.append(player)
def read_context(self, game):
for p in game.players:
pass
# game.chips(p) = 1000
class StartRoundCommand(StartRoundCommand):
def execute(self, game):
for player in game.players: # Ante
game.parent.add_chips(player, -game.parent.ante_price)
game.add_player_bet(player, game.parent.ante_price)
game.pot_total += game.parent.ante_price
game.dealer = self.next_dealer(game)
def next_dealer(self, game):
if game.parent.last_dealer:
index = game.players.index(game.parent.last_dealer) + 1
index %= len(game.players)
return game.players[index]
else:
# return game.random.choice(game.players)
return game.players[0]
def read_context(self, game):
pass
class EndRoundCommand(EndRoundCommand):
def read_context(self, game):
pass
def execute(self, game):
game.parent.last_dealer = game.dealer
class DealCardsCommand(GameCommand):
def execute(self, game):
game.distribute_cards_to_each_player(2)
class FlopCommand(GameCommand):
def execute(self, game):
game.deck.distribute([game.community_cards], 3)
class TurnCommand(GameCommand):
def execute(self, game):
game.deck.distribute([game.community_cards], 1)
class RiverCommand(GameCommand):
def execute(self, game):
game.deck.distribute([game.community_cards], 1)
class PokerRound(CardGameRound):
Deck = PokerDeck
StartGameCommand = StartRoundCommand
# def play(self):
# self.player_in_turn = self.next_player()
# self.player_play(self.player_in_turn, action='blind_bet')
def prepare(self):
self.pot_total = 0
self.pot = {}
for player in self.players:
self.pot[str(player)] = 0
self.dealer = None
self.community_cards = Deck()
def add_player_bet(self, player, amount):
self.pot[str(player)] += amount
def get_context(self, player):
ctx = super(PokerRound, self).get_context(player)
ctx['pot_total'] = self.pot_total
ctx['pot'] = self.pot
ctx['dealer'] = self.dealer
ctx['community_cards'] = self.community_cards
return ctx
def showdown(self):
for player in self.players:
self.best_player_combination(player)
def best_player_combination(self, player):
deck = self.community_cards.clone()
hand = self.hand(player)
deck.push(hand.get_cards())
combs = combinations(deck.get_cards(), 5)
combs = [PokerCombination(cards) for cards in combs]
combs.sort()
return combs[-1]
def before_play(self): pass
def start_new_cycle(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self):
return len(self.players) == 1
def the_end(self): pass
def summary(self): return super(PokerRound, self).summary()
def start_round(self): pass
class Poker(CardGame):
Round = PokerRound
StartGameCommand = StartGameCommand
EndGameCommand = EndGameCommand
RandomStrategy = RandomPokerPlayer
Player = PokerPlayer
def prepare(self):
self.initial_chips = self.kwargs.get('initial_chips', 1000)
self.ante_price = self.kwargs.get('ante_price', 10)
self.chips = {}
for player in self.players:
self.chips[str(player)] = 0
self.last_dealer = None
def amount_of_chips(self, player):
return self.chips[str(player)]
def add_chips(self, player, amount):
self.chips[str(player)] += amount
def new_round(self):
players = []
for player in self.players:
if self.amount_of_chips(player) >= self.ante_price:
players.append(player)
round_game = self.Round(self.random.randint(1, 999999), players, **self.kwargs)
# self.games.append(round_game)
return round_game
def get_context(self, player):
ctx = super(Poker, self).get_context(player)
ctx['initial_chips'] = self.initial_chips
ctx['ante_price'] = self.ante_price
ctx['last_dealer'] = self.last_dealer
ctx['chips'] = self.chips
return ctx
def before_play(self): pass
# def play(self): pass
def before_start_round(self, round_game): pass
def after_end_round(self, round_game): pass
def after_play(self): pass
def is_the_end(self): return False
def the_end(self): pass
def summary(self): return super(Poker, self).summary()
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,775 | gatournament/gat-games | refs/heads/master | /gat_games/__init__.py | # coding: utf-8
VERSION = '0.0.2'
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,776 | gatournament/gat-games | refs/heads/master | /gat_games/game_engine/engine.py | # coding: utf-8
import logging
import random
import sys
import six
import gat_games.game_engine.gat_json as json
class EndGame(Exception): pass
class AlgorithmError(Exception): pass
class AlgorithmInitializationError(AlgorithmError): pass
class AlgorithmTimeoutError(AlgorithmError): pass
class InvalidCommandError(AlgorithmError): pass
class GATLogger(object):
FORMAT = '%(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger('GAT')
logger.setLevel(logging.INFO)
verbose = False
@classmethod
def set_level(cls, log_level):
cls.logger.setLevel(log_level)
@classmethod
def set_verbose(cls):
cls.verbose = True
@classmethod
def get_log_level(cls):
return cls.logger.getEffectiveLevel()
@classmethod
def is_verbose(cls):
return cls.verbose or cls.get_log_level() == logging.DEBUG
@classmethod
def log(cls, message, prefix='', level=logging.INFO):
# print(message)
cls.logger.log(level, '[GAT][%s] %s' % (prefix, message))
if cls.get_log_level() == logging.DEBUG:
sys.stdout.flush()
@classmethod
def debug(cls, message, prefix=''):
cls.log(message, prefix=prefix, level=logging.DEBUG)
@classmethod
def info(cls, message, prefix=''):
cls.log(message, prefix=prefix, level=logging.INFO)
@classmethod
def error(cls, message, prefix=''):
cls.log(message, prefix=prefix, level=logging.ERROR)
@classmethod
def exception(cls, e):
cls.logger.exception(e)
class Player(object):
'''
Override:
def play(self, context, **kwargs): pass
def start(self): pass
def stop(self): pass
'''
def __init__(self, name=None):
self.name = name if name else '%s-%s' % (self.__class__.__name__, id(self))
self.game = None
def __str__(self):
return self.name
def __getstate__(self):
odict = self.__dict__.copy()
odict.pop('game', None)
return odict
def log(self, message, level=logging.INFO):
GATLogger.log(message, prefix=self.name, level=level)
def play(self, context, **kwargs): pass
def start(self, **kwargs): pass
def stop(self): pass
class GameCommand(object):
'''
Override:
def execute(self, game): pass
'''
def __init__(self, **kwargs):
self.kwargs = kwargs or {}
@classmethod
def name(cls):
return cls.__name__.replace('Command', '')
def pretty_log(self):
args = []
for name, values in self.kwargs.items():
if hasattr(values, '__iter__'):
arg = ','.join([str(v) for v in values])
else:
arg = str(values)
args.append('%s=%s' % (name, arg))
kwargs = ' ; '.join(args)
return '%s(%s)' % (self.name(), kwargs)
def replay_data(self):
data = dict(name=self.name())
if self.kwargs:
data['args'] = self.kwargs
return data
def __str__(self):
data = self.replay_data()
return json.dumps(data, sort_keys=True)
def process(self, game):
self.execute(game)
def read_context(self, game):
pass
def execute(self, game):
pass
class PlayerGameCommand(GameCommand):
'''
Override:
def validate(self, game, context): pass
def execute(self, game): pass
'''
def __init__(self, player, **kwargs):
super(PlayerGameCommand, self).__init__(**kwargs)
self.player = player
def pretty_log(self):
pretty_log = super(PlayerGameCommand, self).pretty_log()
return '[%s] %s' % (str(self.player), pretty_log)
def replay_data(self):
data = super(PlayerGameCommand, self).replay_data()
data['player'] = str(self.player)
return data
def process(self, game):
context = game.get_context(self.player)
self.validate(game, context)
super(PlayerGameCommand, self).process(game)
def validate(self, game, context):
'may raise an InvalidCommandError'
pass
class StartGameCommand(GameCommand):
def read_context(self, game):
pass
class EndGameCommand(GameCommand):
def read_context(self, game):
self.kwargs['summary'] = game.get_final_result()
self.kwargs['winners'] = game.winners
self.kwargs['losers'] = game.losers
self.kwargs['error_responsibles'] = game.error_responsibles
self.kwargs['no_contest'] = game.no_contest
self.kwargs['error'] = game.error
self.kwargs['draw'] = game.draw
class StartRoundCommand(StartGameCommand):
def read_context(self, game):
pass
class EndRoundCommand(EndGameCommand):
def read_context(self, game):
pass
class Game(object):
'''
Usage:
game = Game()
game.start()
game.print_summary()
Override:
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def play(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
'''
RandomStrategy = Player
Player = Player
StartGameCommand = StartGameCommand
EndGameCommand = EndGameCommand
def __init__(self, seed, players, **kwargs):
self.seed = seed
self.random = random.Random()
self.random.seed(seed)
names = [player.name for player in players]
if len(names) != len(set(names)):
raise ValueError('A game can not have more thab one player with the same name.')
self.players = players
for player in self.players:
player.game = self
self.winners = []
self.losers = []
self.draw = False
self.no_contest = False
self.error = None
self.error_message = None
self.error_responsibles = []
self.commands = []
self.kwargs = kwargs
self.prepare()
def __getstate__(self):
odict = self.__dict__.copy()
return odict
def add_player(self, player):
self.players.append(player)
player.game = self
def remove_player(self, player):
self.players.remove(player)
def log(self, message, level=logging.INFO):
GATLogger.log(message, prefix=self.__class__.__name__, level=level)
def save_command(self, command):
command.read_context(self)
self.log(command.pretty_log(), logging.INFO)
# take a snapshot of the object to avoid the original be modified
self.commands.append(json.loads(json.dumps(command.replay_data())))
def execute_command(self, command):
self.save_command(command)
command.process(self)
if self.is_the_end() and not issubclass(command.__class__, EndGameCommand):
raise EndGame()
def set_no_contest(self, reason):
self.log(reason, logging.ERROR)
self.no_contest = True
self.error = 'U'
self.error_message = reason
self.winners = []
self.losers = []
self.draw = False
def set_runtime_error(self, player, error, exception):
self.log(str(exception), logging.ERROR)
self.error = error
self.error_message = str(exception) # optimization
self.error_responsibles = [str(player)]
self.loser = player
for p in self.players:
if str(p) != str(player):
self.winners.append(p)
break
self.losers = [player]
if sys.exc_info()[1] and sys.exc_info()[2]:
raise AlgorithmError(exception)
# six.reraise(AlgorithmError(exception), sys.exc_info()[1], sys.exc_info()[2])
else:
raise AlgorithmError(exception)
def set_draw(self):
self.draw = True
self.winners = []
self.losers = []
# Engine methods
def prepare(self): pass
def start(self):
try:
self.save_command(self.StartGameCommand())
while not self.is_the_end() and len(self.players) > 0 and not self.error:
self.before_play()
self.play()
self.after_play()
self.the_end()
except AlgorithmError as e:
# set_runtime_error has already setted all variables
pass
except EndGame:
self.log('Games stopped by a command', logging.DEBUG)
self.after_play()
self.the_end()
except Exception as e:
GATLogger.exception(e)
self.set_no_contest(str(e))
finally:
self.save_command(self.EndGameCommand())
return self.summary()
def get_context(self, player):
return {}
def before_play(self): pass
def play(self): pass
def after_play(self): pass
def before_player_play(self, player, context): pass
def player_play(self, player, action='play'):
context = self.get_context(player)
self.log('-' * 50, logging.DEBUG)
self.log('%s playing: %s' % (player, self.printable_data(context)), logging.DEBUG)
self.before_player_play(player, context)
try:
response = player.play(context, action=action)
except EndGame as e:
self.after_player_play(player, context, None)
except AlgorithmTimeoutError as e:
self.set_runtime_error(player, 'T', e)
except Exception as e:
self.set_runtime_error(player, 'RE', e)
else:
self.after_player_play(player, context, response)
def after_player_play(self, player, context, response=None): pass
def is_the_end(self): raise NotImplementedError('%s: is_the_end' % (self.__class__.__name__))
def the_end(self): pass
def summary(self):
return {
'draw': self.draw,
'no_contest': self.no_contest,
'winners': [str(winner) for winner in self.winners],
'losers': [str(loser) for loser in self.losers],
'error': self.error,
'error_message': self.error_message,
'error_responsibles': self.error_responsibles,
'summary': self.get_final_result(),
}
def printable_data(self, data):
if GATLogger.is_verbose():
return json.dumps(data, sort_keys=True, indent=2 * ' ')
else:
return json.dumps(data, sort_keys=True)
def print_summary(self):
summary = self.summary()
self.log('_' * 75, logging.DEBUG)
self.log(':: Summary', logging.DEBUG)
self.log(self.printable_data(summary), logging.DEBUG)
return summary
def get_final_result(self):
winners = ','.join([str(player) for player in self.winners])
if self.error:
if self.no_contest:
return 'No contest! %(error)s' % dict(error=self.error_message)
else:
error_responsibles = ','.join([str(player) for player in self.error_responsibles])
return 'Error: %(error)s. Winners: %(winners)s. Error responsibles: %(losers)s.' % dict(error=self.error_message, winners=winners, losers=error_responsibles)
else:
if self.draw:
return 'Draw!'
else:
losers = ','.join([str(player) for player in self.losers])
return 'Winners: %(winners)s. Losers: %(losers)s.' % dict(winners=winners, losers=losers)
class TurnBasedGame(Game):
'''
Override:
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def start_new_cycle(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
'''
def __init__(self, seed, players, **kwargs):
super(TurnBasedGame, self).__init__(seed, players, **kwargs)
self.random.shuffle(self.players)
self.player_in_turn = None
def next_player(self):
# with this implementation, the game can remove a player safely
if self.player_in_turn:
index = self.players.index(self.player_in_turn)
return self.players[(index + 1) % len(self.players)]
else:
return self.players[0]
def must_start_new_cycle(self):
return self.player_in_turn == None or self.players.index(self.player_in_turn) == len(self.players) - 1
def start_new_cycle(self):
pass
def play(self):
if self.must_start_new_cycle():
self.start_new_cycle()
self.player_in_turn = self.next_player()
self.player_play(self.player_in_turn)
class GameComposite(Game):
'''
Override:
Round = CustomRound
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def before_start_round(self, round_game): pass
def after_end_round(self, round_game): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
'''
Round = Game
def __init__(self, seed, players, **kwargs):
super(GameComposite, self).__init__(seed, players, **kwargs)
self.games = []
def get_context(self, player):
context = super(GameComposite, self).get_context(player)
context['game_number'] = len(self.games)
return context
def current_game(self):
return self.games[-1]
def new_round(self):
round_game = self.Round(self.random.randint(1, 999999), self.players[:], **self.kwargs)
round_game.parent = self
# self.games.append(round_game)
return round_game
def before_start_round(self, round_game):
pass
def play(self):
self.log('=' * 100, logging.DEBUG)
self.log('New round', logging.DEBUG)
round_game = self.new_round()
self.before_start_round(round_game)
round_game.start()
if round_game.error:
if round_game.error == 'U':
self.set_no_contest(round_game.error_message)
elif round_game.error == 'RE':
self.set_runtime_error(round_game.error_responsibles[0], round_game.error, round_game.error_message)
else:
self.after_end_round(round_game)
self.commands.extend(round_game.commands)
round_game.print_summary()
def after_end_round(self, round_game):
pass
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,777 | gatournament/gat-games | refs/heads/master | /tests/test_init.py | # coding: utf-8
import re
import unittest
class InitTests(unittest.TestCase):
def test_version(self):
from gat_games import VERSION
print(re.match(r'\d[.]\d[.]\d', VERSION))
self.assertEquals(True, bool(re.match(r'\d[.]\d[.]\d', VERSION)))
def test_game_import_shortcut(self):
from gat_games.games import SUPPORTED_GAMES, Truco
from gat_games.games.truco import Truco
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,778 | gatournament/gat-games | refs/heads/master | /gat_games/games/truco_gaucho.py | # coding: utf-8
from gat_games.game_engine.engine import *
from gat_games.game_engine.cardgame import *
# http://pt.wikipedia.org/wiki/Truco | {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,779 | gatournament/gat-games | refs/heads/master | /gat_games/games/truco.py | # coding: utf-8
import random
from gat_games.game_engine.engine import *
from gat_games.game_engine.cardgame import *
# TODOs:
# who wins start next round => must_start_new_cycle BUG?
class TrucoPlayer(Player):
def play(self, context, **kwargs):
if kwargs.get('action', 'play') == 'accept_truco':
if self.has_accepted_truco(context):
self.accept_truco()
else:
self.reject_truco()
else:
self.upcard_or_truco(context)
def has_accepted_truco(self, context): pass
def upcard_or_truco(self, context): pass
def can_truco(self, context):
return context['round_can_truco']
def upcard(self, card):
self.game.execute_command(Upcard(self, card=card))
def truco(self):
self.game.execute_command(TrucoCommand(self))
def accept_truco(self):
self.game.execute_command(AcceptTruco(self))
def reject_truco(self):
self.game.execute_command(RejectTruco(self))
class RandomTrucoPlayer(TrucoPlayer):
def has_accepted_truco(self, context):
return bool(random.randint(0, 1))
def upcard_or_truco(self, context):
option = random.randint(0, 10)
if self.can_truco(context) and option > 5:
self.truco()
else:
hand = context['hand']
random_index = random.randint(0, len(hand)-1)
random_card = hand.see(random_index)
self.upcard(random_card)
class TrucoCard(Card):
suit_weights = {SPADES: 2, HEARTS: 3, DIAMONDS: 1, CLUBS: 4}
ranks = (4, 5, 6, 7, Q, J, K, AS, 2, 3)
# ranks = (Q, J, K, AS, 2, 3)
def is_manilha(self, center_card):
i1 = self.ranks.index(self.rank)
i2 = self.ranks.index(center_card.rank)
return i1 == i2 + 1 or (i2 == len(self.ranks) - 1 and i1 == 0)
class TrucoDeck(Deck):
Card = TrucoCard
def get_key_by_value(the_dict, value):
index = list(the_dict.values()).index(value)
key = list(the_dict.keys())[index]
return key
class Upcard(PlayerGameCommand):
def validate(self, game, context):
card = self.kwargs.get('card')
if game.player_in_turn != self.player:
raise InvalidCommandError('Player can not upcard right now')
if not game.hand(self.player).contains(card):
raise InvalidCommandError('Invalid card to upcard')
if game.state != 'playing':
raise InvalidCommandError('Need to accept/reject Truco before upcard')
def execute(self, game):
card = self.kwargs.get('card')
card = game.hand(self.player).remove(card)
game.table[str(self.player)] = card
class TrucoCommand(PlayerGameCommand):
def validate(self, game, context):
if game.player_in_turn != self.player and game.next_player() != self.player:
raise InvalidCommandError('It is not your resposibility to Truco right now')
if game.last_player_who_truco == self.player:
raise InvalidCommandError('You can not truco until another player re-truco')
if game.value >= 12:
raise InvalidCommandError('Game has already been setted to all-in')
if game.truco_value >= 12:
raise InvalidCommandError('Game has already been setted to all-in')
def execute(self, game):
if game.value == 1:
game.truco_value = 3
else:
game.truco_value = game.value + 3
game.last_player_who_truco = self.player
game.state = 'truco'
class AcceptTruco(PlayerGameCommand):
def validate(self, game, context):
if game.last_player_who_truco == self.player:
raise InvalidCommandError('You can not accept your own Truco')
if game.state != 'truco':
raise InvalidCommandError('No truco to accept')
def execute(self, game):
game.value = game.truco_value
game.truco_value = 0
game.state = 'playing'
class RejectTruco(PlayerGameCommand):
def validate(self, game, context):
if game.last_player_who_truco == self.player:
raise InvalidCommandError('You can not reject your own Truco')
if game.state != 'truco':
raise InvalidCommandError('No truco to reject')
def execute(self, game):
self.truco_rejected = True
game.wins[str(game.player_in_turn)] = 3
game.state = 'playing'
raise EndGame()
class StartRoundCommand(StartRoundCommand):
def read_context(self, game):
self.kwargs['center_card'] = game.center_card
for player in game.players:
self.kwargs[str(player)] = game.hand(player).get_cards()
class TrucoRound(CardGameRound):
Deck = TrucoDeck
StartGameCommand = StartRoundCommand
def prepare(self): pass
def start_round(self):
self.truco_rejected = False
self.wins = {}
for player in self.players:
self.wins[str(player)] = 0
self.value = 1 # accepted truco update round value
self.truco_value = 0
self.last_player_who_truco = None
self.center_card = self.deck.pop()
self.new_deck()
self.distribute_cards_to_each_player(3)
self.table = {}
self.state = 'playing'
def get_context(self, player):
context = super(TrucoRound, self).get_context(player)
context['round_value'] = self.value
context['round_truco_value'] = self.truco_value
context['round_center_card'] = self.center_card
context['round_table'] = self.table
context['round_wins'] = self.wins
context['round_state'] = self.state
context['round_can_truco'] = self.player_in_turn != self.last_player_who_truco and self.value < 12 and self.truco_value < 12
return context
def before_play(self): pass
def must_start_new_cycle(self):
return len(self.table) == len(self.players)
def start_new_cycle(self):
self.table = {}
# FIXME player_in_turn = self.winner_last_cycle
def before_player_play(self, player, context): pass
def play(self):
if self.must_start_new_cycle():
self.start_new_cycle()
self.player_in_turn = self.next_player()
if self.state == 'truco':
self.player_play(self.player_in_turn, action='accept_truco')
else:
self.player_play(self.player_in_turn)
def after_player_play(self, player, context, response=None):
if len(self.table) == len(self.players):
cards = list(self.table.values())
winning_card = self.winning_card(cards, self.center_card)
indexes = [i for i, x in enumerate(list(self.table.values())) if x == winning_card] # can have a draw
# draw count one win for each player
for index in indexes:
winner = list(self.table.keys())[index]
self.wins[winner] += 1
def after_play(self): pass
def is_the_end(self):
# draw count one win for each player
return max(self.wins.values()) >= 2 or self.truco_rejected
def the_end(self):
winner_wins = max(self.wins.values())
loser_wins = min(self.wins.values())
self.winners = [get_key_by_value(self.wins, winner_wins)]
self.losers = [get_key_by_value(self.wins, loser_wins)]
def summary(self):
s = super(TrucoRound, self).summary()
s.update({
'round_value': self.value,
'wins': self.wins,
})
return s
# Auxiliar methods
def winning_card(self, cards, center_card):
manilhas = []
for card in cards:
if card.is_manilha(center_card):
manilhas.append(card)
if manilhas:
manilhas = sorted(manilhas, key=lambda card: card.suit_weight())
return manilhas[-1]
else:
return max(cards)
class Truco(CardGame):
Round = TrucoRound
RandomStrategy = RandomTrucoPlayer
Player = TrucoPlayer
def __init__(self, seed, players, **kwargs):
super(Truco, self).__init__(seed, players, **kwargs)
self.scoreboard = {}
for player in self.players:
self.scoreboard[str(player)] = 0
def prepare(self): pass
def get_context(self, player):
return super(Truco, self).get_context(player)
def before_play(self): pass
def before_start_round(self, round_game): pass
def after_end_round(self, round_game):
for winner in round_game.winners:
self.scoreboard[str(winner)] += round_game.value
def after_play(self): pass
def is_the_end(self):
return max(self.scoreboard.values()) >= 12
def the_end(self):
index_winner = max(self.scoreboard.values())
index_loser = min(self.scoreboard.values())
self.winners = [get_key_by_value(self.scoreboard, index_winner)]
self.losers = [get_key_by_value(self.scoreboard, index_loser)]
def summary(self):
s = super(Truco, self).summary()
s.update({
'scoreboard': self.scoreboard
})
return s
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,780 | gatournament/gat-games | refs/heads/master | /gat_games/game_engine/gat_json.py | try:
import simplejson as json
except ImportError:
import json
def encode_object(obj):
if hasattr(obj, '__getstate__'):
return obj.__getstate__
if hasattr(obj, '__dict__'):
return obj.__dict__
return obj
def dumps(obj, skipkeys=True, default=encode_object, **kwargs):
return json.dumps(obj, skipkeys=skipkeys, default=default, **kwargs)
def loads(s, **kwargs):
return json.loads(s, **kwargs)
def dump(obj, stream, skipkeys=True, default=encode_object, **kwargs):
return json.dump(obj, stream, skipkeys=skipkeys, default=default, **kwargs)
def load(file_obj, **kwargs):
return json.load(file_obj, **kwargs)
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,781 | gatournament/gat-games | refs/heads/master | /tests/game_engine/test_cardgame.py | # coding: utf-8
import unittest
from gat_games.game_engine.cardgame import *
class CardTests(unittest.TestCase):
def test_valid_card(self):
card = Card(AS, SPADES)
self.assertEquals(SPADES, card.suit)
self.assertEquals(AS, card.rank)
def test_card_validate_rank(self):
try:
Card(999, SPADES)
self.assertFalse(True)
except AttributeError as e:
self.assertEquals('Invalid card rank', str(e))
def test_card_validate_suit(self):
try:
Card(AS, 999)
self.assertFalse(True)
except AttributeError as e:
self.assertEquals('Invalid card suit', str(e))
def test_cards_print_niceley(self):
self.assertEquals('AS-1', str(Card(AS, SPADES)))
self.assertEquals('J-1', str(Card(J, SPADES)))
self.assertEquals('5-1', str(Card(5, SPADES)))
def test_cards_are_ordered_by_rank(self):
self.assertEquals(True, Card(2, SPADES) > Card(1, SPADES))
self.assertEquals(False, Card(2, SPADES) > Card(2, SPADES))
self.assertEquals(True, Card(2, SPADES) >= Card(1, SPADES))
self.assertEquals(True, Card(2, SPADES) >= Card(2, SPADES))
self.assertEquals(False, Card(2, SPADES) >= Card(3, SPADES))
self.assertEquals(True, Card(1, SPADES) < Card(2, SPADES))
self.assertEquals(False, Card(2, SPADES) < Card(2, SPADES))
self.assertEquals(True, Card(1, SPADES) <= Card(2, SPADES))
self.assertEquals(True, Card(2, SPADES) <= Card(2, SPADES))
self.assertEquals(False, Card(3, SPADES) <= Card(2, SPADES))
def test_cards_are_compared(self):
self.assertEquals(True, Card(2, SPADES) == Card(2, SPADES))
self.assertEquals(False, Card(2, SPADES) == Card(3, SPADES))
self.assertEquals(True, Card(2, SPADES) != Card(3, SPADES))
self.assertEquals(False, Card(2, SPADES) != Card(2, SPADES))
def test_cards_can_be_included_in_sets(self):
cards = set()
cards.add(Card(AS, SPADES))
cards.add(Card(2, SPADES))
cards.add(Card(2, SPADES))
self.assertEquals(2, len(cards))
class DeckTests(unittest.TestCase):
def setUp(self):
self.deck = Deck()
def test_equal(self):
self.assertEquals(Deck(), Deck())
self.assertNotEquals(Deck(), Deck().build())
def test_len(self):
self.assertEquals(0, len(self.deck))
def test_count(self):
self.assertEquals(0, self.deck.count())
def test_clone(self):
self.assertEquals(Deck().build(), Deck().build().clone())
def test_deck_print_niceley(self):
self.deck.push(Card(AS, SPADES))
self.assertEquals('AS-1', str(self.deck))
self.deck.push(Card(5, SPADES))
self.assertEquals('AS-1,5-1', str(self.deck))
def test_build(self):
self.assertEquals(0, len(self.deck))
self.deck.build()
self.assertEquals(13*4, len(self.deck))
def test_build_rebuild(self):
self.deck.build()
self.deck.pop()
self.deck.build()
self.assertEquals(13*4, len(self.deck))
def test_push(self):
self.deck.push(1)
self.assertEquals(1, len(self.deck))
def test_see(self):
self.deck.push(Card(AS, SPADES))
self.assertEquals('AS-1', str(self.deck.see(0)))
def test_pop(self):
self.deck.push(9)
result = self.deck.pop()
self.assertEquals(9, result)
self.assertEquals(0, len(self.deck))
def test_remove(self):
self.deck.push(9)
result = self.deck.remove(9)
self.assertEquals(9, result)
self.assertEquals(0, len(self.deck))
def test_clear(self):
self.deck.push(9)
self.deck.push(99)
self.deck.clear()
self.assertEquals(0, len(self.deck))
def test_pop_with_index(self):
self.deck.push(9)
self.deck.push(99)
self.deck.push(999)
result = self.deck.pop(1)
self.assertEquals(99, result)
self.assertEquals(2, len(self.deck))
def test_shuffle(self):
pass
def test_sort(self):
pass
def test_distribute(self):
self.deck.build()
decks = [Deck(), Deck()]
self.deck.distribute(decks, 5)
self.assertEquals(13*4 - 10, len(self.deck))
self.assertEquals(5, len(decks[0]))
self.assertEquals(5, len(decks[1]))
class CardGameRoundTests(unittest.TestCase):
def test_deck(self):
pass
def test_hands(self):
game = CardGameRound(0, [])
self.assertEquals(0, len(game.hands))
game = CardGameRound(0, [Player()])
self.assertEquals(1, len(game.hands)) | {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,782 | gatournament/gat-games | refs/heads/master | /gat_games/games/hole.py |
# https://github.com/paulocheque/python-cardgameengine/blob/master/cardgames/hole/__init__.py | {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,783 | gatournament/gat-games | refs/heads/master | /gat_games/games/chess.py | # coding: utf-8
import random
from gat_games.game_engine.engine import *
# http://en.wikipedia.org/wiki/Chess
class ChessNativePlayer(Player):
def play(self, context, **kwargs):
pass
class RandomChessPlayer(ChessNativePlayer):
def play(self, context, **kwargs):
option = random.randint(0, 10)
class Move(GameCommand):
def validate(self, game, context):
origin = self.kwargs.get('origin')
target = self.kwargs.get('target')
if game.player_in_turn != self.player:
raise InvalidCommandError('It is not your turn')
raise InvalidCommandError('Invalid piece movement: %s-%s' % (origin, target))
raise InvalidCommandError('Invalid movement because checkmate threat: %s-%s' % (origin, target))
def execute(self, game):
pass
class ChessPiece(object):
'''
Conventions: White starts in the bottom and Black in the top.
'''
WHITE = 'W'
BLACK = 'B'
def __init__(self, color):
self.color = color
def name(self):
return '%s-%s' % (self.color, self.__class__.__name__.lower())
def is_diagonal_movement(self, x, y, fx, fy):
return abs(fy - y) == abs(fx - x)
def is_horizontal_movement(self, x, y, fx, fy):
return y == fy and x != fx
def is_vertical_movement(self, x, y, fx, fy):
return x == fx and y != fy
def is_forward_movement(self, x, y, fx, fy):
if self.color == ChessPiece.WHITE:
return fy > y
else:
return fy < y
def is_backward_movement(self, x, y, fx, fy):
return not self.is_forward_movement(x, y, fx, fy)
def is_valid_movement(self, x, y, fx, fy): # x => column, y => line
pass
class Pawn(ChessPiece):
def is_valid_position(self, x, y, fx, fy):
if self.color == ChessPiece.WHITE:
if y == 0 or fy == 0:
return False
else:
if y == 7 or fy == 7:
return False
return True
def is_first_movement(self, x, y, fx, fy):
if self.color == ChessPiece.WHITE and y == 1:
return True
if self.color == ChessPiece.BLACK and y == 6:
return True
return False
def is_capturing_another_piece(self, x, y, fx, fy):
return False # FIXME self.board[fx][fy] != None
def is_valid_movement(self, x, y, fx, fy):
if not self.is_valid_position(x, y, fx, fy):
return False
if self.is_horizontal_movement() or self.is_backward_movement():
return False
if self.is_first_movement(x, y, fx, fy):
if self.is_vertical_movement(x, y, fx, fy):
if self.color == ChessPiece.WHITE:
if fy == 2 or fy == 3:
return True # FIXME squares tem que estarem vazios
else:
if fy == 5 or fy == 4:
return True # FIXME squares tem que estarem vazios
# if self.is_capturing_another_piece(x, y, fx, fy):
# pass
# if self.is_capturing_another_piece(x, y, fx, fy):
# pass
return True
class ChessBoard(object):
def __init__(self, current_color=ChessPiece.WHITE, board={}):
self.current_color = current_color
self.board = board
def create_initial_board(self):
self.board = [ # a b c d e f g h
[ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK], # 8
[PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN], # 7
[None]*8, # 6
[None]*8, # 5
[None]*8, # 4
[None]*8, # 3
[PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN, PAWN], # 2
[ROOK, KNIGHT, BISHOP, QUEEN, KING, BISHOP, KNIGHT, ROOK], # 1
]
def valid_movements(self):
movements = []
for i in list(range(0, 8)):
for j in list(range(0, 8)):
unit = self.board[i][j]
movements.extend([])
return movements
def is_check(self):
pass
def is_checkmate(self):
return self.is_check() and not bool(self.valid_movements())
def is_valid_movement(self, origin, target):
return '' in self.valid_movements()
def change_player(self):
if self.current_color == ChessPiece.WHITE:
self.current_color = ChessPiece.BLACK
else:
self.current_color = ChessPiece.WHITE
def move(self, origin, target):
self.board[target[0]][target[1]] = self.board[origin[0]][origin[1]]
self.board[origin[0]][origin[1]] = None
self.change_player()
return ChessBoard(current_color=self.current_color, board=self.board)
# Chess => board => valid movements
# ChessGame
# - board
# - current color turn (associar jogador a branco ou preto)
# - valid movements:
# current color:
# pega todas as peças
# is check?
# is checkmate?
# possible moviments
# En passant: peao
# test king+tower: Castling
# Promotion: pawn vira qq coisa
# The king moves one square in any direction. The king has also a special move which is called castling and involves also moving a rook.
# The rook can move any number of squares along any rank or file, but may not leap over other pieces. Along with the king, the rook is involved during the king's castling move.
# The bishop can move any number of squares diagonally, but may not leap over other pieces.
# The queen combines the power of the rook and bishop and can move any number of squares along rank, file, or diagonal, but it may not leap over other pieces.
# The knight moves to any of the closest squares that are not on the same rank, file, or diagonal, thus the move forms an "L"-shape: two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The knight is the only piece that can leap over other pieces.
# The pawn may move forward to the unoccupied square immediately in front of it on the same file; or on its first move it may advance two squares along the same file provided both squares are unoccupied; or it may move to a square occupied by an opponent's piece which is diagonally in front of it on an adjacent file, capturing that piece. The pawn has two special moves: the en passant capture and pawn promotion.
def move(self, current_cell, final_cell):
unit = self.board.get(current_cell, None)
if not unit or not self.is_valid_movement(current_cell, final_cell):
raise AlgorithmError('Invalid movement')
else:
self.board[final_cell] = self.board[current_cell]
del self.board[current_cell]
def to_dict(self):
pass
class Chess(TurnBasedGame):
RandomStrategy = RandomChessPlayer
Player = ChessPlayer
PAWN = 'pawn'
KNIGHT = 'knight'
BISHOP = 'bishop'
ROOK = 'rook'
QUEEN = 'queen'
KING = 'king'
pieces = [PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING]
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def play(self): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
def is_game_over(self):
# Although the objective of the game is to checkmate the opponent, chess games do not have to end in checkmate—either player may resign which is a win for the other player. It is considered bad etiquette to continue playing when in a truly hopeless position.[3] If it is a game with time control, a player may run out of time and lose, even with a much superior position. Games also may end in a draw (tie). A draw can occur in several situations, including draw by agreement, stalemate, threefold repetition of a position, the fifty-move rule, or a draw by impossibility of checkmate (usually because of insufficient material to checkmate). As checkmate from some positions cannot be forced in fewer than 50 moves (such as in the pawnless chess endgame and two knights endgame), the fifty-move rule is not applied everywhere,[note 2] particularly in correspondence chess.
return False
def get_context(self, player):
context = super(Chess, self).get_context(player)
return context
def summary(self):
s = super(Chess, self).summary()
s.update({
})
return s
def the_end(self):
self.winner = None
self.loser = None
self.draw = None
return super(Chess, self).the_end()
def player_finished_his_turn(self):
pass
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,784 | gatournament/gat-games | refs/heads/master | /gat_games/games/__game_model__.py | # coding: utf-8
import random
from gat_games.game_engine.engine import *
from gat_games.game_engine.cardgame import *
class XPlayer(Player):
def play(self, context, **kwargs):
pass
class RandomXPlayer(XPlayer):
def play(self, context, **kwargs):
option = random.randint(0, 10)
class XCard(Card):
suit_weights = {SPADES: 2, HEARTS: 3, DIAMONDS: 1, CLUBS: 4}
ranks = (4, 5, 6, 7, Q, J, K, AS, 2, 3)
class XDeck(Deck):
Card = XCard
class XRound(CardGameRound):
Deck = XDeck
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def start_new_cycle(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
class X(CardGame):
Round = XRound
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def start_new_cycle(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,785 | gatournament/gat-games | refs/heads/master | /gat_games/game_engine/cardgame.py | # coding: utf-8
from gat_games.game_engine.engine import *
AS = 1
J = 11
Q = 12
K = 13
SPADES = 1
HEARTS = 2
DIAMONDS = 3
CLUBS = 4
class Card(object):
'''
Override:
suit_weights = {...}
ranks = (...)
'''
ranks = (AS, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K)
suits = (SPADES, HEARTS, DIAMONDS, CLUBS)
suit_weights = {SPADES: 0, HEARTS: 0, DIAMONDS: 0, CLUBS: 0}
rank_labels = {AS:'AS', J:'J', Q:'Q', K:'K'}
# http://en.wikipedia.org/wiki/Suit_(cards)
def __init__(self, rank, suit, **kwargs):
if rank not in self.ranks:
raise AttributeError('Invalid card rank')
if suit not in self.suits:
raise AttributeError('Invalid card suit')
self.rank = rank
self.suit = suit
def suit_weight(self):
return self.suit_weights[self.suit]
def __lt__(self, other):
return self.ranks.index(self.rank) < self.ranks.index(other.rank) if other else False
def __le__(self, other):
return self.ranks.index(self.rank) <= self.ranks.index(other.rank) if other else False
def __gt__(self, other):
return self.ranks.index(self.rank) > self.ranks.index(other.rank) if other else True
def __ge__(self, other):
return self.ranks.index(self.rank) >= self.ranks.index(other.rank) if other else True
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit if other else False
def __ne__(self, other):
return self.rank != other.rank or self.suit != other.suit if other else True
def __hash__(self):
return hash(self.rank) + hash(self.suit)
def __str__(self):
return '%s-%s' % (self.rank_labels.get(self.rank, self.rank), self.suit)
class Deck(object):
'''
Override:
Card = CustomCard
'''
Card = Card
def __init__(self):
self.cards = []
def __len__(self):
return self.count()
def __eq__(self, other):
return self.cards == other.cards
def __ne__(self, other):
return self.cards != other.cards
def __str__(self):
return ','.join([str(card) for card in self.cards])
def clone(self):
deck = Deck()
deck.cards = self.cards[:]
return deck
def get_cards(self):
return self.cards
def count(self):
return len(self.cards)
def clear(self):
self.cards = []
def build(self):
self.clear()
for suit in self.Card.suits:
for rank in self.Card.ranks:
self.cards.append(self.Card(rank, suit))
return self
def contains(self, card):
return card in self.cards
def see(self, index):
return self.cards[index]
def push(self, card):
self.cards.append(card)
return card
def pop(self, index=None):
if index:
return self.cards.pop(index)
return self.cards.pop()
def remove(self, card):
if card in self.cards:
self.cards.remove(card)
return card
def shuffle(self, random):
random.shuffle(self.cards)
def sort(self):
self.cards.sort()
def distribute(self, decks, amount):
for i in range(amount):
for deck in decks:
deck.push(self.cards.pop())
class CardGameRound(TurnBasedGame):
'''
Override:
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def start_new_cycle(self): pass
def before_player_play(self, player, context): pass
def after_player_play(self, player, context, response=None): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
Deck = CustomDeck
def start_round(self): pass
'''
Deck = Deck
StartGameCommand = StartRoundCommand
EndGameCommand = EndRoundCommand
def __init__(self, seed, players, **kwargs):
super(CardGameRound, self).__init__(seed, players, **kwargs)
self.hands = {}
for player in self.players:
self.hands[str(player)] = self.Deck()
self.new_deck()
self.start_round()
def hand(self, player):
return self.hands[str(player)]
def new_deck(self):
self.deck = self.Deck()
self.deck.build()
self.deck.shuffle(self.random)
def start_round(self):
pass
def get_context(self, player):
context = super(CardGameRound, self).get_context(player)
context['hand'] = self.hands[str(player)]
return context
def distribute_cards_to_each_player(self, amount):
self.deck.distribute(list(self.hands.values()), amount)
class CardGame(GameComposite):
'''
Override:
Round = CustomRound
def prepare(self): pass
def get_context(self, player): return super(Game, self).get_context(player)
def before_play(self): pass
def play(self): pass
def before_start_round(self, round_game): pass
def after_end_round(self, round_game): pass
def after_play(self): pass
def is_the_end(self): return True
def the_end(self): pass
def summary(self): return super(Game, self).summary()
'''
Round = CardGameRound
| {"/tests/game_engine/test_gat_json.py": ["/gat_games/game_engine/gat_json.py"], "/tests/game_engine/test_engine.py": ["/gat_games/game_engine/engine.py"], "/tests/games/test_pokertexasholdem.py": ["/gat_games/games/poker_texasholdem.py"], "/gat_games/games/truco_clean_deck.py": ["/gat_games/games/truco.py"], "/tests/games/test_truco.py": ["/gat_games/game_engine/cardgame.py", "/gat_games/games/truco.py"], "/gat_games/games/__init__.py": ["/gat_games/games/truco.py", "/gat_games/games/truco_clean_deck.py"], "/gat_games/games/poker_texasholdem.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/engine.py": ["/gat_games/game_engine/gat_json.py"], "/tests/test_init.py": ["/gat_games/__init__.py", "/gat_games/games/__init__.py", "/gat_games/games/truco.py"], "/gat_games/games/truco_gaucho.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/games/truco.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/tests/game_engine/test_cardgame.py": ["/gat_games/game_engine/cardgame.py"], "/gat_games/games/chess.py": ["/gat_games/game_engine/engine.py"], "/gat_games/games/__game_model__.py": ["/gat_games/game_engine/engine.py", "/gat_games/game_engine/cardgame.py"], "/gat_games/game_engine/cardgame.py": ["/gat_games/game_engine/engine.py"]} |
44,816 | alyson6918/tabuada_e_calculadora | refs/heads/main | /CLass_calculator.py | #criando classes
class Calculadora:
def __init__(self, valor1, valor2):
self.a = valor1
self.b = valor2
def soma (self):
return self.a + self.b
def subtracao (self):
return self.a - self.b
def divisao (self):
return self.a / self.b
def multiplicacao (self):
return self.a * self.b | {"/script.py": ["/CLass_calculator.py"]} |
44,817 | alyson6918/tabuada_e_calculadora | refs/heads/main | /script.py | #importação:
from CLass_calculator import Calculadora
#declarando variaveis:
pergunta1 = "n"
#estruturas de repetição:
while pergunta1 == "nao" or pergunta1 == "n" or pergunta1 == "não":
pergunta = "sim"
tc = str(input("Você deseja calcular ou fazer uma tabuada ?\n(Escreva:tabuada ou calcular)\n."))
while not(tc == "tabuada" or tc == "calcular"):
tc = str(input("O valor escrito n é valido por favor digite novamente\n."))
if tc == "calcular":
print("Calculadora\n")
while pergunta == "sim" or pergunta == "s":
#variaveis internas:
n1=int(input("Escreva um numero inteiro:\n."))
n2=int(input("Escreva mais um numero inteiro:\n."))
q=str(input("Você deseja multiplicar, dividir, somar ou subtrair esses valores?\n."))
calculadora=Calculadora(n1,n2)
#estrutura de repetição interna
while not(q == "somar" or q == "multiplicar" or q == "dividir" or q == "subtrair" or q == "+" or q == "-" or q == "/" or q == "x" or q == "*"):
q =input("Voce escreveu um valor incompativel, por favor digite novemente:\n.")
#o programa:
if q == "somar" or q == "+":
print ("{} + {} = {}\nObrigado!".format(n1, n2, calculadora.soma()))
elif q == "subtrair" or q == "-":
print ("{} - {} = {}\nObrigado!".format(n1, n2, calculadora.subtracao()))
elif q == "multiplicar" or q == "x" or q == "*":
print ("{} x {} = {}\nObrigado!".format(n1, n2, calculadora.multiplicacao()))
else:
print ("{} / {} = {}\nObrigado!".format(n1, n2, calculadora.divisao()))
#finalização do programa:
pergunta=input("\nVoce deseja continuar calculando ?\n.")
elif tc == "tabuada":
print("Tabuadas:")
while pergunta == "sim" or pergunta == "s":
#variaveis internas:
n1=int(input("escreva um numero inteiro:\n"))
#o programa
print("\nObrigado\nA tabuada completa desse numero é:\n")
for x in range(11):
calculadora = Calculadora(n1, x)
print("{} x {} = {}".format(n1, x, calculadora.multiplicacao()))
#pergunta de finalização
pergunta= input("\nDeseja fazer outra tabuada ?\n (digite: sim ou nao)\n")
#final do programa:
pergunta1=input("fechar o programa ?\n.")
print("Obrigado!\nFim do programa") | {"/script.py": ["/CLass_calculator.py"]} |
44,818 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/order/migrations/0003_auto_20160805_1916.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-05 23:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('order', '0002_orderdetail_item'),
]
operations = [
migrations.AlterField(
model_name='order',
name='date_order',
field=models.DateField(auto_now=True),
),
]
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,819 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/order/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-05 22:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('clients', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_order', models.DateField(auto_now_add=True)),
('amount_total', models.DecimalField(decimal_places=2, max_digits=6)),
('weight', models.DecimalField(decimal_places=2, max_digits=6)),
('client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clients.Client')),
],
),
migrations.CreateModel(
name='OrderDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('qty', models.IntegerField()),
('price', models.DecimalField(decimal_places=2, max_digits=6)),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.Order')),
],
),
migrations.CreateModel(
name='OrderLog',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(auto_now_add=True)),
('event', models.CharField(max_length=255)),
('reference', models.CharField(max_length=255)),
('note', models.TextField(blank=True, null=True)),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.Order')),
],
),
migrations.CreateModel(
name='OrderPayments',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(auto_now_add=True)),
('amount', models.DecimalField(decimal_places=2, max_digits=6)),
('concept', models.CharField(max_length=255)),
('consignee', models.CharField(max_length=255)),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.Order')),
],
),
migrations.CreateModel(
name='Status',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('state', models.CharField(max_length=30)),
],
),
migrations.AddField(
model_name='order',
name='status',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.Status'),
),
]
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,820 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/order/admin.py | from django.contrib import admin
from .models import *
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ('client', 'date_order', 'status', 'amount_total', 'weight')
@admin.register(OrderDetail)
class OrderDetailAdmin(admin.ModelAdmin):
list_display = ('order', 'item', 'qty', 'price')
@admin.register(OrderLog)
class OrderLogAdmin(admin.ModelAdmin):
list_display = ('order', 'date', 'event', 'reference', 'note')
@admin.register(OrderPayments)
class OrderPaymentsAdmin(admin.ModelAdmin):
list_display = ('order', 'date', 'amount', 'concept', 'consignee')
@admin.register(Status)
class StatusAdmin(admin.ModelAdmin):
list_display = ('state',) | {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,821 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/items/models.py | from __future__ import unicode_literals
from django.db import models
class Item(models.Model):
description = models.CharField(max_length=255)
brand = models.CharField(max_length=255)
code = models.CharField(max_length=30)
picture = models.ImageField(upload_to="media/items")
price = models.DecimalField(max_digits=6, decimal_places=2)
weight = models.DecimalField(max_digits=6, decimal_places=2)
def __unicode__(self):
return self.description
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,822 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/items/admin.py | from django.contrib import admin
from .models import *
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
list_display = ('description', 'brand', 'code', 'picture', 'price', 'weight')
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,823 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/order/models.py | from __future__ import unicode_literals
from django.db import models
from clients.models import Client
from items.models import Item
class Status(models.Model):
state = models.CharField(max_length=30)
def __unicode__(self):
return self.state
class Order(models.Model):
client = models.ForeignKey(Client)
date_order = models.DateField(auto_now=True)
status = models.ForeignKey(Status)
amount_total = models.DecimalField(max_digits=6, decimal_places=2)
weight = models.DecimalField(max_digits=6, decimal_places=2)
def __unicode__(self):
return str(self.pk)
class OrderDetail(models.Model):
order = models.ForeignKey(Order)
item = models.ForeignKey(Item)
qty = models.IntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2)
class OrderLog(models.Model):
order = models.ForeignKey(Order)
date = models.DateTimeField(auto_now_add=True)
event = models.CharField(max_length=255)
reference = models.CharField(max_length=255)
document = models.ImageField(upload_to="media/order-log", blank=True)
note = models.TextField(blank=True, null=True)
class OrderPayments(models.Model):
order = models.ForeignKey(Order)
date = models.DateTimeField(auto_now_add=True)
amount = models.DecimalField(max_digits=6, decimal_places=2)
concept = models.CharField(max_length=255)
consignee = models.CharField(max_length=255)
document = models.ImageField(upload_to="media/order-payment", blank=True)
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
44,824 | elektrodx/omcor-beta-v01 | refs/heads/master | /omcor/items/migrations/0002_auto_20160808_2134.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-09 01:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('items', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='item',
name='picture',
field=models.ImageField(upload_to='media/items'),
),
]
| {"/omcor/order/admin.py": ["/omcor/order/models.py"], "/omcor/items/admin.py": ["/omcor/items/models.py"], "/omcor/clients/admin.py": ["/omcor/clients/models.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.