示例#1
0
    def checkNewRegistration(self, user):
        content = ""
        player_name = self.request.get("player_name")
        player_age = self.request.get("player_age")
        if helpers.validateName(player_name) is False:
            content = """
				<div id="fail_message"><h3>Trouble! Your player name has some issues.<h3></div>
			"""
        if self.checkAlreadyExists(player_name):
            content = (
                content
                + """
				<div id="fail_message"><h3>Dadgum it! Someone already took that name.<h3></div>
			"""
            )
        if not helpers.is_number(player_age):
            content = (
                content
                + """
				<div id="fail_message"><h3>It appears you didn't enter a valid number for your age. You do know your age, don't you?<h3></div>
			"""
            )
        else:
            player_age = int(player_age)
        if player_age < 13 or player_age > 135:
            content = (
                content
                + """
				<div id="fail_message"><h3>Your age is outside the valid range. Either you're too young or you're impossibly old.<h3></div>
			"""
            )
        if content != "":
            content = content + '<div><a href="/"><h3>Click here to return and try again.<h3></a></div>'
        return content
示例#2
0
    def edit_balance(self, amount, opperation):

        if is_number(amount) and float(amount) > 0 and amount <= self.balance:

            if opperation == "+":
                self.balance += float(amount)
            elif opperation == "-":
                self.balance -= float(amount)
            self.save()
            return True
        else:
            return False
示例#3
0
def add():

    # If new cost submitted
    if request.method == "POST":

        # Check number was submitted
        # for cost per unit field
        t = request.form.get("unitCost")
        ppu = is_number(t)

        # If not a number, prompt user
        # for a number by using if statement
        # in Jinja template to render error message
        if not ppu:
            return render_template("addcost.html", s=session["s"], ppu=ppu)

        # Get variables from new cost form
        cost_name = request.form.get("costName")
        unit = request.form.get("unit")
        currency = request.form.get("currency")
        unit_cost = request.form.get("unitCost")
        quantity = request.form.get("quantity")

        # Calculate total amount of cost
        cost_total = float(unit_cost) * float(quantity)

        # Get id of project selected
        x = db.execute(
            "SELECT id FROM projects WHERE project_name = :project_name",
            project_name=session["s"])
        project_id = x[0]["id"]

        # Add cost details to database
        db.execute(
            "INSERT INTO costs (project_id, cost_name, total_cost, unit, unit_cost, quantity, currency) VALUES (:project_id, :cost_name, :cost_total, :unit, :unit_cost, :quantity, :currency)",
            project_id=project_id,
            cost_name=cost_name,
            cost_total=cost_total,
            unit=unit,
            unit_cost=unit_cost,
            quantity=quantity,
            currency=currency)

        # If valid form submitted
        # render table showing breakdown of
        # all project costs
        return redirect("/breakdown")

    # If new cost from requested
    # render cost form
    else:
        return render_template("addcost.html", s=session["s"])
示例#4
0
def solve(input):
    lines = input.splitlines()
    letters = 'abcdefgh'
    items = {}
    for num in range(len(letters)):
        items[letters[num]] = 0
    items['a'] = 1
    currentIndex = 0
    i = 1
    count = 0
    while currentIndex < len(lines) and currentIndex >= 0:
        i += 1
        line = lines[currentIndex]
        splitLine = line.split(" ")
        command = splitLine[0]
        key = splitLine[1]
        value = 0
        if len(splitLine) == 3:
            if is_number(splitLine[2]):
                value = int(splitLine[2])
            else:
                value = items[splitLine[2]]

        if command == 'set':
            items[key] = value
        if command == 'sub':
            items[key] -= value
        if command == 'mul':
            count += 1
            items[key] *= value
        if command == 'jnz':
            if (is_number(key) and key != 0) or items[key] != 0:
                currentIndex += value
            else:
                currentIndex += 1
        else:
            currentIndex += 1
    return items['h']
示例#5
0
def calc_avg_angles():
    # TODO: To Be Continued...
    sums = np.zeros(NUM_OF_ANGLES)
    with open(ANGLES_PATH, 'r') as angles:
        for line_count, line in enumerate(angles):
            curr_angles = json.loads(line)
            for n, angle in enumerate(curr_angles):
                if is_number(angle[3]):
                    sums[n] += angle[3]
    avgs = []
    for i, j in enumerate(sums):
        avgs.append(j / (line_count + 1))
    with open(ANGLES_AVG_PATH, 'w') as avgs_file:
        json.dump(avgs, avgs_file)
示例#6
0
def solve(input):
    lines = input.splitlines()
    letters = 'abcdefghijklmnopqrstuvwxyz'
    items = {}
    for num in range(len(letters)):
        items[letters[num]] = 0
    lastPlayedSound = 0
    recoveredSound = 0
    currentIndex = 0
    i = 1
    while currentIndex < len(lines) and currentIndex >= 0:
        i += 1
        line = lines[currentIndex]
        splitLine = line.split(" ")
        command = splitLine[0]
        key = splitLine[1]
        value = 0
        if len(splitLine) == 3:
            if is_number(splitLine[2]):
                value = int(splitLine[2])
            else:
                value = items[splitLine[2]]
        if command == 'set':
            items[key] = value
        if command == 'add':
            items[key] += value
        if command == 'mul':
            items[key] *= value
        if command == 'mod':
            items[key] = items[key] % value
        if command == 'snd':
            lastPlayedSound = items[key]
        if command == 'jgz':
            if items[key] > 0:
                currentIndex += value
            else:
                currentIndex += 1
        else:
            currentIndex += 1
        if command == 'rcv':
            if items[key] > 0:
                recoveredSound = lastPlayedSound
                break
    return recoveredSound
示例#7
0
def golden_test(img_name):
    img = cv2.imread(IMG_PATH + img_name)
    lands = lands_from_img(img)

    all_dists = all_distances(lands, allow_repeats=True)
    rs = ratios(all_dists)
    angs = angles(lands)

    for i, j in enumerate(rs):
        if abs(j[3] - PHI) < 0.005:
            ang = angs[tuple(sorted((j[0], j[1], j[2])))]
            if not is_number(ang) or ang < 90:
                continue
            p1 = tuple(lands[rs[i][0]])
            p2 = tuple(lands[rs[i][1]])
            p3 = tuple(lands[rs[i][2]])
            draw_lines(img, p1, p2, p3)
    cv2.imshow('golden-test', img)
    cv2.imwrite('golden-test-angles.jpg', img)
    cvwait()
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.cross_validation import KFold
from sklearn.tree import DecisionTreeClassifier

from settings import *
from helpers import is_number
from functions import get_user_by_name, get_interesting_user, \
    build_data_set, vectorize, StackOverflow


print "Running with feature level", FEATURES_LEVEL

user = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_USER
if not is_number(user):
    elem = get_user_by_name(user) if user else get_interesting_user()
    if elem is None:
        print "User '%s' not found" % user
        exit(1)
    user_id = int(elem.get("Id"))
else:
    user_id = int(user)
print "Building ML model for user %d" % user_id


instances, classes, tags_cnt = build_data_set(user_id, FEATURES_LEVEL == 0)

print "Set built, %d(%d+%d) (ratio: %.2f)" % (len(classes),
                                              classes.count(Classes.INTERESTED),
                                              classes.count(Classes.UNKNOWN),
示例#9
0
def solve(input):
    lines = input.splitlines()
    letters = 'abcdefghijklmnopqrstuvwxyz'
    items1 = {}
    items2 = {}
    for num in range(len(letters)):
        items1[letters[num]] = 0
    items1['p'] = 0
    for num in range(len(letters)):
        items2[letters[num]] = 0
    items2['p'] = 1
    items1Queue = []
    items2Queue = []
    currentIndex1 = 0
    currentIndex2 = 0
    deadLocked1 = False
    deadLocked2 = False
    count = 0
    while True:
        if currentIndex1 >= 0 and currentIndex1 < len(lines):
            line = lines[currentIndex1]
            splitLine = line.split(" ")
            command = splitLine[0]
            key = splitLine[1]
            value = 0
            if len(splitLine) == 3:
                if is_number(splitLine[2]):
                    value = int(splitLine[2])
                else:
                    value = items1[splitLine[2]]
            if command == 'set':
                items1[key] = value
            if command == 'add':
                items1[key] += value
            if command == 'mul':
                items1[key] *= value
            if command == 'mod':
                items1[key] = items1[key] % value
            if command == 'snd':
                items2Queue.append(items1[key])
            if command == 'jgz':
                if (is_number(key) and int(key) > 0) or items1[key] > 0:
                    currentIndex1 += value
                else:
                    currentIndex1 += 1
            else:
                if command != 'rcv' or (command == 'rcv'
                                        and len(items1Queue) > 0):
                    currentIndex1 += 1
            if command == 'rcv':
                if len(items1Queue) > 0:
                    items1[key] = items1Queue[0]
                    items1Queue = items1Queue[1:]
                else:
                    deadLocked1 = True

        if currentIndex2 >= 0 and currentIndex2 < len(lines):
            line = lines[currentIndex2]
            splitLine = line.split(" ")
            command = splitLine[0]
            key = splitLine[1]
            value = 0
            if len(splitLine) == 3:
                if is_number(splitLine[2]):
                    value = int(splitLine[2])
                else:
                    value = items2[splitLine[2]]
            if command == 'set':
                items2[key] = value
            if command == 'add':
                items2[key] += value
            if command == 'mul':
                items2[key] *= value
            if command == 'mod':
                items2[key] = items2[key] % value
            if command == 'snd':
                items1Queue.append(items2[key])
                count += 1
            if command == 'jgz':
                if (is_number(key) and int(key) > 0) or items2[key] > 0:
                    currentIndex2 += value
                else:
                    currentIndex2 += 1
            else:
                if command != 'rcv' or (command == 'rcv'
                                        and len(items2Queue) > 0):
                    currentIndex2 += 1
            if command == 'rcv':
                if len(items2Queue) > 0:
                    items2[key] = items2Queue[0]
                    items2Queue = items2Queue[1:]
                else:
                    deadLocked2 = True
        print(deadLocked1, deadLocked2)
        if deadLocked1 and deadLocked2:
            break
    return count
示例#10
0
    def get_matching_columns(self, phrase, value, tags=[], table_name=""):
        """
        Goes through all the tables
        Matches with all columns
        Returns potential matches
        :param phrase: phrase for which we are figuring out query
        :param value: value to be looked up in cached data
        :return: list of (table_name, column_name)
        """
        to_return = []

        # it's possible that we get numbers as strings
        if helpers.is_number(value):
            value = float(value)

        # go through all the tables
        for table in self._columns.keys():

            # if a table name is provided, search only in that table
            if table_name.strip() != "" and table != table_name:
                continue

            # go through each column in the table
            found_some_column = False
            for column in self._columns[table]:
                # check if types match
                if type(value) == str and column[1] == "TEXT":
                    # check if it's a perfect match
                    if column[0] in self._distinct_values[table]:
                        match_result = self.match_with_values(
                            self._distinct_values[table][column[0]], value)

                        # sometimes we can have substring in names
                        # in such cases, let's make similarity score 0.5
                        if helpers.similarity_score(helpers.to_unicode(column[0]), helpers.to_unicode("name")) > 0.5 \
                                and any(value in string for string in self._distinct_values[table][column[0]]):
                            if match_result[0] < 0.5:
                                match_result = 0.5

                        if match_result[0] > 0:
                            to_return.append(table, column[0], match_result[0])
                            found_some_column = True

                # TODO::Improve matching logic by considering a small error range
                elif (type(value) == int
                      or type(value) == float) and (column[1] == "INTEGER"
                                                    or column[1] == "REAL"):
                    if column[0] in self._distinct_values[table]:
                        match_result = self.match_for_numbers(
                            self._distinct_values[table][column[0]], value)
                        if (match_result[0] > 0):
                            to_return.append(
                                (table, column[0], match_result[0]))
                            found_some_column = True

            if not found_some_column:
                # find the column which matches the most
                match_score = 0.0
                match_col = ""
                for column in self._columns[table]:
                    col_score = self.match_with_column_name(
                        phrase, value, column[0], tags)
                    # TODO::Refine the filtering logic
                    if col_score > 0 and col_score > match_score:
                        match_score = col_score
                        match_col = column[0]

                to_return.append((table, match_col, match_score))

        return to_return
示例#11
0
import numpy as np
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
from sklearn.cross_validation import KFold
from sklearn.tree import DecisionTreeClassifier

from settings import *
from helpers import is_number
from functions import get_user_by_name, get_interesting_user, \
    build_data_set, vectorize, StackOverflow

print "Running with feature level", FEATURES_LEVEL

user = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_USER
if not is_number(user):
    elem = get_user_by_name(user) if user else get_interesting_user()
    if elem is None:
        print "User '%s' not found" % user
        exit(1)
    user_id = int(elem.get("Id"))
else:
    user_id = int(user)
print "Building ML model for user %d" % user_id

instances, classes, tags_cnt = build_data_set(user_id, FEATURES_LEVEL == 0)

print "Set built, %d(%d+%d) (ratio: %.2f)" % (
    len(classes), classes.count(
        Classes.INTERESTED), classes.count(Classes.UNKNOWN), ML_DATA_RATIO)
    def get_matching_columns(self, phrase, value):
        """
        Goes through all the tables
        Matches with all columns
        Returns potential matches
        :param phrase: phrase for which we are figuring out query
        :param value: value to be looked up in cached data
        :return: list of (table_name, column_name)
        """
        to_return = []

        # it's possible that we get numbers as strings
        if helpers.is_number(value):
            value = float(value)

        # go through all the tables
        for table in self._columns.keys():
            # go through each column in the table
            found_some_column = False
            for column in self._columns[table]:
                # check if types match
                if type(value) == str and column[1] == "TEXT":
                    # check if it's a perfect match
                    if column[0] in self._distinct_values[table] and \
                            value in self._distinct_values[table][column[0]]:
                        # it's a perfect match
                        to_return.append((table, column[0], 1))
                        found_some_column = True

                    elif column[0] in self._distinct_values[table] and \
                            any(value in string for string in self._distinct_values[table][column[0]]):
                        # it's an imperfect match
                        # TODO::Add better logic here based on string lengths, matching length, context, etc.
                        # scope for improvement
                        to_return.append((table, column[0], 0.5))
                        found_some_column = True

                # TODO::Improve matching logic by considering a small error range
                elif (type(value) == int
                      or type(value) == float) and (column[1] == "INT"
                                                    or column[1] == "REAL"):
                    if column[0] in self._distinct_values[table] and \
                            value in self._distinct_values[table][column[0]]:
                        # perfect match
                        to_return.append((table, column[0], 1))
                        found_some_column = True

            if not found_some_column:
                # find the column which matches the most
                match_score = 0.0
                match_col = ""
                for column in self._columns[table]:
                    col_score = self.match_with_column_name(
                        phrase, value, column[0])
                    # TODO::Refine the filtering logic
                    if col_score > 0 and col_score > match_score:
                        match_score = col_score
                        match_col = column[0]

                to_return.append((table, match_col, match_score))

        return to_return