Exemplo n.º 1
0
def jsonify(git_data):
    """ Converts git log data json formatted for the /commitList endpoint

    Description
    
    **Args**:
        **git_data** (dict): A dictionary containing the git commit list: ::
            
            {
                "name1": [
                    {
                        "date": datetime,
                        "time_spent": int (seconds),
                        "files": ["file1",...],
                    },
                    ...
                ],
                ...
            }

    **Returns**:
        dict: A dictionary identical to **git_data**, except all "date" and "time_spent"
        properties are converted to human readable strings

    """
    # Create complete copy. Copy module may be removed in the future
    data = copy.deepcopy(git_data)
    for student in data:
        student_data = data[student]
        for day in student_data:
            day["date"] = date_string(day["date"])
            day["time_spent"] = time_string(day["time_spent"])
    eprint(data)
    return json.dumps(data)
Exemplo n.º 2
0
async def process_request(request):
    try:
        path = request.path.lower()
        state = request.app['state']

        if path in ("/start", ):
            clue = random.randint(0, 1000)
            state['current_run'] = [0, clue]
            return web.Response(status=200, text=str(clue))
        elif path[1:].isdecimal():
            (steps, clue) = state['current_run']
            text = path[1:]
            if text.isdecimal() and int(text) == clue:
                if steps == STATIONS - 1:
                    state['current_run'] = [steps + 1, None]
                    return web.Response(status=202, text="It works!")
                clue = random.randint(0, 1000)
                state['current_run'] = [steps + 1, clue]
                return web.Response(status=200, text=str(clue))

        state['current_run'][1] = None
        return web.Response(status=500, text="MORTIS")

    except Exception as e:
        helper.eprint(e)
        return web.Response(status=400, text="Yikes!")
Exemplo n.º 3
0
async def main_loop(app):
    state = app['state']
    state['buffer'] = []
    state['client'] = None

    state['current_run'] = None
    rates = []
    msg = ["Results:"]
    try:
        while True:
            outs = helper.update_client(state, timeout=1)
            if outs is not None:
                if outs.timeout:
                    points = (0 if state['current_run'] is None else
                              state['current_run'][0])
                    rates.append(points / STATIONS)
                    msg.append("- Timeout (partial run possible)")
                    state['current_run'] = None
                elif outs.code != 0:
                    helper.eprint(outs, state['current_run'])
                    points = (0 if state['current_run'] is None else
                              state['current_run'][0])
                    rates.append(points / STATIONS)
                    msg.append(f"- Runtime error (partial run possible)\n")
                    state['current_run'] = None
                elif state['current_run'] is None:
                    msg.append("- Session wasn't started")
                    rates.append(0)
                else:
                    msg.append("- Normal run (either good or bad)")
                    rates.append(state['current_run'][0] / STATIONS)
                    state['current_run'] = None
            elif state['current_run']:
                if state['current_run'][1] is None:
                    helper.eprint("early_bird", state['current_run'])
                    msg.append("- Normal run (either good or bad)")
                    rates.append(state['current_run'][0] / STATIONS)
                    helper.kill_client(state)
                    state['current_run'] = None
            await asyncio.sleep(0.005)
            if len(rates) >= 20:
                score = helper.mean(rates)
                helper.exit_grader(score, "\n".join(msg))
    except asyncio.CancelledError:
        pass
    except Exception as e:
        helper.bail_exception()
Exemplo n.º 4
0
def open_editor(filename):
    """
    Function that tries to find the best suited editor to use and then
    opens the status file in the editor.
    """
    if "EDITOR" in os.environ:
        editor = os.environ['EDITOR']
    elif "VISUAL" in os.environ:
        editor = os.environ['VISUAL']
    elif os.path.exists("/usr/bin/editor"):
        editor = "/usr/bin/editor"
    elif os.path.exists("/usr/bin/vim"):
        editor = "/usr/bin/vim"
    elif os.path.exists("/usr/bin/vi"):
        editor = "/usr/bin/vi"
    else:
        eprint("Could not load an editor.  Please define EDITOR or VISUAL")
        sys.exit(os.EX_CONFIG)

    call(editor.split() + [filename])
Exemplo n.º 5
0
def main(argv):
    parser = get_parser()

    # The parser arguments (cfg.args) are accessible everywhere after this call.
    cfg.args = parser.parse_args()

    # This initiates the global yml configuration instance so it will be
    # accessible everywhere after this call.
    cfg.initiate_config()

    if not cfg.args.file and not cfg.args.q:
        eprint("No file provided and not in query mode\n")
        parser.print_help()
        sys.exit(os.EX_USAGE)

    jira, username = jiralogin.get_jira_instance(cfg.args.t)

    if cfg.args.x or cfg.args.e:
        if not cfg.args.q:
            eprint(
                "Arguments '-x' and '-e' can only be used together with '-q'")
            sys.exit(os.EX_USAGE)

    if cfg.args.p and not cfg.args.q:
        eprint("Arguments '-p' can only be used together with '-q'")
        sys.exit(os.EX_USAGE)

    if cfg.args.q:
        (filename, issues) = get_jira_issues(jira, username)

        if cfg.args.p:
            print_status_file(filename)
            sys.exit(os.EX_OK)
    elif cfg.args.file is not None:
        filename = cfg.args.file
    else:
        eprint(
            "Trying to run script with unsupported configuration. Try using --help."
        )
        sys.exit(os.EX_USAGE)

    if get_editor():
        open_editor(filename)

    try:
        issues
    # issues is not defined, we haven't made any query yet.
    except NameError:
        parse_status_file(jira, filename, None)
    else:
        parse_status_file(jira, filename, issues)
Exemplo n.º 6
0
    parser = argparse.ArgumentParser()
    parser.add_argument("logfile", help="path to commit log file")
    parser.add_argument("timefile", help="path to commit time file")
    parser.add_argument("name", help="user name")
    parser.add_argument("-l",
                        "--limit",
                        help="ignore file changes above limit")
    parser.add_argument("-O",
                        "--obfuscate",
                        action="store_true",
                        help="obfuscate flag")

    args = parser.parse_args()

    commit_data_file = open(args.logfile, "r")
    commit_times_file = open(args.timefile, "r")
    student_id = args.name

    data = (get_progress(commit_data_file, max_change=int(args.limit))
            if args.limit else get_progress(commit_data_file))
    individual_data = data[student_id]
    # print("\n")
    reformatted_data = reformat(individual_data)

    commit_times = commit_data(commit_times_file)
    eprint(commit_times)
    individual_commit_times = commit_times[student_id]

    api_json = jsonify_data(reformatted_data, individual_commit_times)
    print(api_json)
Exemplo n.º 7
0
	async def liveWordFilter(self, message):
		global strikes
		spaces = ('\u0020', '\u00a0', '\u1680', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', 
			'\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u202f', '\u205f', '\u3000', '\u2800')
		symbols = ('.', '-', '_', '`', '~', ":", '/', '\\', ';', '+', '(', ')', '*', '^')
		regional_indicators = ('🇦','🇧','🇨','🇩','🇪','🇫','🇬','🇭','🇮','🇯','🇰','🇱','🇲','🇳','🇴','🇵','🇶','🇷','🇸','🇹','🇺','🇻','🇼','🇽','🇾','🇿')
		number_emojis = ('0⃣','1⃣','2⃣','3⃣','4⃣','5⃣','6⃣','7⃣','8⃣','9⃣')
		special_words = []
		settings = self.bot.settings['moderation']['word filter'].copy()

		if not settings['enabled']:
			return
		elif message.author == self.bot.user:
			return
		if settings['threshold'] < 1:
			eprint("Invalid threshold set({value}), value must be larger than 0.".
				format(value=settings['threshold']))
			return

		settings['words'] = list(set(settings['words'])) # Make element unique
		# Separate precise entries from words list
		for i, word in enumerate(settings['words']):
			word = word.lower()
			settings['words'][i] = word
			for space in spaces:
				if (space in word) and (word not in special_words):
					special_words.append(word)
					del settings['words'][i]
					break
			for symbol in symbols:
				if (symbol in word) and (word not in special_words):
					special_words.append(word)
					del settings['words'][i]
					break

		content = message.content.lower()
		# filter out possible seperator
		for c in spaces:
			content = content.replace(c, '')
		for s in symbols:
			content = content.replace(s, '')
		# convert regional indicator and number emojis to plain text
		for i,ri in enumerate(regional_indicators):
			content = content.replace(ri, chr(i+97))
		for i,ne in enumerate(number_emojis):
			content = content.replace(ne, chr(i+48))
		# detect bad word(s)
		if strikes.get(message.author, None) is None:
			strikes[message.author] = 0
		words = settings['words']
		striked = False
		for spword in special_words:
			if spword in message.content.lower():
				striked = True
				strikes[message.author] += 1
				break
		if not striked:
			for word in words:
				if word in content:
					striked = True
					strikes[message.author] += 1
					break
		if striked:
			await message.channel.send("🛑 {mention}, usage of bad word is not tolerated at here!".
				format(mention=message.author.mention))
		if strikes[message.author] >= settings['threshold']:
			if settings['action'].lower() == 'kick':
				await message.author.kick(reason="User exceeded word filter's limit | By Automod")
				strikes[message.author] = 0
			elif settings['action'].lower() == 'ban':
				await message.author.ban(reason="User exceeded word filter's limit | By Automod")