Exemplo n.º 1
0
 def load(self, ctx):
     self.compiler = HackerRankAPI(api_key=KEY)
     env = Environment(loader=FileSystemLoader('templates'))
     self.res_out = env.get_template('result.txt')
     self.lang_out = env.get_template('languages.txt')
     self.err_out = env.get_template('error.txt')
     self.help_out = env.get_template('help.txt')
Exemplo n.º 2
0
def run_testcases(request):
    #code runs just fine, make sure that there is atleast one sample test cases to not let this view blow up
    API_KEY = settings.HACKERRANK_API
    source_code = request.POST.get("code")
    compiler = HackerRankAPI(API_KEY)
    lang = request.POST["lang"]
    lang = lang.lower()
    prob_id = request.POST["prob_id"]
    cases = TestCase.objects.select_related().filter(is_sample=True,
                                                     problem=prob_id)
    cases_list = list(cases)
    inputsequences = list()
    outputsequences = list()
    for case in cases_list:
        inputsequences.append(str(case.input_sequence).replace('\r', ''))
        outputsequences.append(str(case.output_sequence.replace('\r', '')))
    print inputsequences
    print outputsequences
    result = compiler.run({
        'source': source_code,
        'lang': lang,
        'testcases': inputsequences,
    })
    i = 0
    actualoutputs = list()
    data = dict()
    output = list()
    msg = result.message
    error = result.error
    print "Msg: " + str(msg)
    print "Error: " + str(error)
    print result.output
    try:
        for res in result.output:
            data["id"] = i
            data["input"] = inputsequences[i].strip()
            data["expectedoutput"] = outputsequences[i].strip()
            data["actualoutput"] = res.strip()
            if error[i]:
                data["actualoutput"] = error[i]
            data["status"] = data["actualoutput"] == data["expectedoutput"]
            i = i + 1
            output.append(data)
            data = dict()
    except:
        return HttpResponse(msg)
    js = json.dumps(output)
    print js
    print prob_id
    print lang
    print source_code

    return HttpResponse(js, content_type='application/json')
Exemplo n.º 3
0
    def Code_Check(src, test_cases, language, expected_return):
        API_kEY = "hackerrank|1850276-1999|ba2a4949a4b24ec8a3245053cde0e3b53da869e6"
        compiler = HackerRankAPI(api_key=API_kEY)

        result = compiler.run({
            'source': src,
            'lang': language,
            'testcases': test_cases
        })

        # Returns the received data from HackerRank API
        if expected_return == 'all':
            return result
        elif expected_return == 'output':
            return result.output
        elif expected_return == 'message':
            return result.message
        elif expected_return == 'time':
            return result.time
Exemplo n.º 4
0
    def setUp(self):
        self.reddit_client_id = os.environ.get("reddit_client_id")
        self.reddit_client_secret = os.environ.get("reddit_client_secret")
        self.hackerrank_key = os.environ.get("hackerrank_key")
        self.giphy_key = os.environ.get("giphy_key")

        self.reddit = praw.Reddit(client_id=self.reddit_client_id,
                                  client_secret=self.reddit_client_secret,
                                  user_agent=USER_AGENT)
        self.compiler = HackerRankAPI(api_key=self.hackerrank_key)
Exemplo n.º 5
0
from hackerrank.HackerRankAPI import HackerRankAPI

API_KEY = "hackerrank|1713589-1967|6dece1a695458bf9da0c8461c760b947f4dd54a9"  #your API-KEY here

compiler = HackerRankAPI(api_key=API_KEY)

#print (compiler.supportedlanguages())     #prints a list of supported languages

source = '''
x = input()
x= int(x)
for j in range(0,10000000):
    x=x
    
print(x*2)
'''

lan = "python3"
tes = ["10", "20"]
result = compiler.run({'source': source, 'lang': lan, 'testcases': tes})

print(result.output, result.time)
Exemplo n.º 6
0
from hackerrank.HackerRankAPI import HackerRankAPI

key = ""
compiler = HackerRankAPI(api_key=key)

source = """
for i in range(5):
    print i
"""

sample_msg = """:compile cpp
```
#include <iostream> 
int main() { 
    std::cout << "hello world" << std::endl; 
    return 0;
}
```
"""

# if sample_msg.startswith(":compile"):
#     arr = sample_msg.split('```')

#     lang = arr[0].split(' ')[1]
#     source = arr[1]

#     result = compiler.run({
#         'source': source,
#         'lang':'cpp'
#     })
Exemplo n.º 7
0
from hackerrank.HackerRankAPI import HackerRankAPI

API_KEY = 'hackerrank|751319-994|d057e21968795c38201ca37d376201eff936f29b'

compiler = HackerRankAPI(api_key=API_KEY)

source = '''
N, M = map(int,raw_input().split()) 
for i in xrange(1,N,2): 
    print (".|."*i).center(M,'-')
    
print "WELCOME".center(M,'-')

for i in xrange(N-2,-1,-2): 
    print (".|."*i).center(M,'-') 
'''

result = compiler.run({
    'source': source,
    'lang': 'python',
    'testcases': ["9 27"]
})
print(result.output[0])
Exemplo n.º 8
0
from commands import *

### keys go here
reddit_client_id = os.environ.get("reddit_client_id")
reddit_client_secret = os.environ.get("reddit_client_secret")
hackerrank_key = os.environ.get("hackerrank_key")
discord_key = os.environ.get("discord_key")
giphy_key = os.environ.get("giphy_key")

# hello
client = discord.Client()
reddit = praw.Reddit(client_id=reddit_client_id,
                     client_secret=reddit_client_secret,
                     user_agent=USER_AGENT)
reddit.read_only = True
compiler = HackerRankAPI(api_key=hackerrank_key)


async def send_response(channel, content):
    try:
        await client.send_message(channel, content)
    except Exception as e:
        print("ERROR: " + str(e))


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
Exemplo n.º 9
0
class CompilePlugin(Plugin):
    def load(self, ctx):
        self.compiler = HackerRankAPI(api_key=KEY)
        env = Environment(loader=FileSystemLoader('templates'))
        self.res_out = env.get_template('result.txt')
        self.lang_out = env.get_template('languages.txt')
        self.err_out = env.get_template('error.txt')
        self.help_out = env.get_template('help.txt')

    @Plugin.command('run', '<src:str...>')
    def on_run_command(self, event, src):
        tokens = list((x.strip() for x in src.split('```') if x.strip()))
        lang = tokens[0]
        args = tokens[1:-1] or ['']
        source = tokens[-1]

        if lang not in self.compiler.supportedlanguages():
            event.msg.reply(self.err_out.render(
                mention=event.msg.member.user.mention,
                error=lang + ' is not a valid language',
                helpcmd='languages'),
                            tts=True)
            return

        if len(tokens) < 2:
            event.msg.reply(self.err_out.render(
                mention=event.msg.member.user.mention,
                error='You must include source to compile.',
                helpcmd='help'),
                            tts=True)
            return

        result = self.compiler.run({
            'source': source,
            'lang': lang,
            'testcases': args
        })

        if not result:
            event.msg.reply(
                self.err_out.render(
                    mention=event.msg.member.user.mention,
                    error='Something weird happened, result object is falsy',
                    helpcmd='.`<@195428466450104329>`.'))

        event.msg.reply(
            self.res_out.render(mention=event.msg.member.user.mention,
                                result=result or '\n'))

        print(
            self.res_out.render(mention=event.msg.member.user.mention,
                                result=result))

    @Plugin.command('languages')
    def on_lang_command(self, event):
        event.msg.reply('• ' +
                        '\n• '.join(self.compiler.supportedlanguages())).pin()

    @Plugin.command('help')
    def on_help_command(self, event):
        event.msg.reply(
            self.help_out.render(mention=event.msg.member.user.mention))

    @Plugin.command('repl')
    def on_repl_command(self, event):
        event.msg.reply(event.msg.member.user.mention + " shell running")
        code.interact(local=dict(globals(), **locals()))
        event.msg.reply(event.msg.member.user.mention + " shell stopped")

    @Plugin.command('pin')
    def on_pin_command(self, event):
        event.msg.pin()
Exemplo n.º 10
0
def run_submission(request):

    # Variable Declarations
    API_KEY = settings.HACKERRANK_API
    source_code = request.POST.get("code")
    compiler = HackerRankAPI(API_KEY)
    lang = request.POST["lang"]
    language = lang
    lang = lang.lower()
    prob_id = request.POST["prob_id"]
    user = request.user
    sub = Submission()
    sub.prob = Problem.objects.filter(id=prob_id)[0]
    sub.attempted = timezone.now()
    sub.submitted_code = source_code
    sub.sub_made_by = user
    sub.lang = ConsoleLanguage.objects.filter(lang=language)[0]
    cases = TestCase.objects.select_related().filter(is_sample=False,
                                                     problem=prob_id)
    cases_list = list(cases)
    inputsequences = list()
    outputsequences = list()
    case_marks = list()
    i = 0
    actualoutputs = list()
    data = dict()
    output = list()
    total_time = 0.0
    total_memory = 0.0
    achieved_score = 0
    max_score = 0
    contest_question = False
    contest_score = 0

    if request.POST['contest_id']:
        contest_id = int(request.POST['contest_id'])
        contest = Contest.objects.filter(id=contest_id)[0]
        print "Contest ID: %d" % contest_id
        contest_question = True

    # Total Marks Calculations
    for case in cases_list:
        inputsequences.append(str(case.input_sequence).replace('\r', ''))
        case_marks.append(int(case.score))
        outputsequences.append(str(case.output_sequence.replace('\r', '')))
    result = compiler.run({
        'source': source_code,
        'lang': lang,
        'testcases': inputsequences,
    })
    msg = result.message
    error = result.error
    try:
        # Memory and Time Calculations
        for time_taken in result.time:
            total_time = total_time + time_taken
        sub.total_execution_time = total_time
        for memory_consumed in result.memory:
            total_memory = total_memory + memory_consumed
        sub.total_memory_used = total_memory

        # Storing ouput of testcases in data

        for res in result.output:
            tcresult = TestCaseResult()
            data["id"] = i
            data["input"] = inputsequences[i].strip()
            data["expectedoutput"] = outputsequences[i].strip()
            data["actualoutput"] = res.strip()
            data["status"] = data["actualoutput"] == data["expectedoutput"]
            data["memory"] = result.memory[i]
            data["time"] = result.time[i]
            max_score = max_score + case_marks[i]
            sub.achieved_score = 0
            sub.save()
            tcresult.submission = sub
            if data["status"]:
                tcresult.status = "P"
            else:
                tcresult.status = "F"
            tcresult.time_submitted = timezone.now()
            tcresult.test_case = cases[i]
            print tcresult
            tcresult.save()
            if data["status"]:
                achieved_score = achieved_score + case_marks[i]
            i = i + 1

            output.append(data)
            data = dict()

        # Calculating Reward Points
        max_reward_points = Problem.objects.values('reward_points').filter(
            id=prob_id)[0]['reward_points']
        scaled_marks = (achieved_score * max_reward_points) / max_score
        sub.achieved_score = int(scaled_marks)

        # Printing Stored and Calculated Variables
        print "Achieved Score: %d" % achieved_score
        print "Max Reward %d" % max_reward_points
        print "Max Score   : %f" % max_score
        print "Scaled Score: %f" % scaled_marks

        current_xp = user.profile.experience_points
        print "Current XP : %d" % current_xp
        previous_max_score = Submission.objects.filter(
            sub_made_by=user,
            prob=sub.prob).aggregate(Max('achieved_score')).values()[0]
        print "Previous Score: %d" % previous_max_score

        # Logic for XP Calculation
        if previous_max_score < scaled_marks:
            sub.sub_made_by.profile.experience_points = (
                current_xp - previous_max_score) + scaled_marks
            print "New XP : %d" % sub.sub_made_by.profile.experience_points
            sub.sub_made_by.profile.save()

        # Saving Contest
        if contest_question:
            #contest_participant = ContestParticipant.objects.filter(contest__id = contest_id, user = user)[0]
            contest_participant, created = ContestParticipant.objects.get_or_create(
                contest=contest, user=user)
            print contest_participant.user
            if created:
                contest_participant.achieved_score = 0

            #previous_contest_score = ContestParticipant.objects.filter(user = user, contest = contest_id).aggregate(Max('achieved_score')).values()[0]
            prev_sub_score = Submission.objects.filter(
                sub_made_by=user, contest=contest,
                prob=sub.prob).aggregate(Max('achieved_score')).values()[0]
            if prev_sub_score:
                if prev_sub_score < max_reward_points:
                    contest_participant.achieved_score = contest_participant.achieved_score - prev_sub_score + scaled_marks
            else:
                contest_participant.achieved_score = contest_participant.achieved_score + scaled_marks
            print "Prev contest sub : " + str(prev_sub_score)
            print "Current Contest : %d" % contest_participant.achieved_score

            sub.contest = contest
            contest_participant.save()

            # Do Not Erase or make any changes
            # print "Previous Contest: %d" % previous_contest_score
            # total_contest_score = Problem.objects.filter(contest = contest).aggregate(Sum('reward_points')).values()[0]
            # print "Total Contest Score : %d" % total_contest_score
            # if (contest_participant.achieved_score + scaled_marks) <= total_contest_score:
            # contest_participant.achieved_score = contest_participant.achieved_score + scaled_marks
            # print "New Contest Marks: %d" % contest_participant.achieved_score
            # contest_participant.save()

        # Saving Submissions and JSON
        sub.save()
    except TypeError:
        print msg
        return HttpResponse(msg)
    js = json.dumps(output)
    print js
    # print prob_id
    # print lang
    # print source_code

    return HttpResponse(js, content_type='application/json')
Exemplo n.º 11
0
import discord
import asyncio
import requests
import re
from hackerrank.HackerRankAPI import HackerRankAPI

HACKERRANK_API_KEY = 'hackerrank|3491785-2301|18ff1e697a4f9435ceba9e9c87f01ad8d1bfc854'
DISCORD_API_KEY = 'MzYxNDI2NjMxNjIzMDQ5MjE2.D1D53w.zvCrlUmNIjEclBk74V_rFHe2YY0'

compiler = HackerRankAPI(api_key = HACKERRANK_API_KEY)
client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    # example commands
    # if message.content.startswith('!test'):
    #     counter = 0
    #     tmp = await client.send_message(message.channel, 'Calculating messages...')
    #     async for log in client.logs_from(message.channel, limit=100):
    #         if log.author == message.author:
    #             counter += 1
    #
    #     await client.edit_message(tmp, 'You have {} messages.'.format(counter))
    # elif message.content.startswith('!sleep'):