def _calc_rating(self, subsfile, file_original_path):
        file_name = os.path.basename(file_original_path)
        folder_name = os.path.split(os.path.dirname(file_original_path))[-1]

        subsfile = re.sub("\W+", ".", subsfile).lower()
        file_name = re.sub("\W+", ".", file_name).lower()
        folder_name = re.sub("\W+", ".", folder_name).lower()
        log(
            __scriptname__,
            "# Comparing Releases:\n [subtitle-rls] %s \n [filename-rls] %s \n [folder-rls] %s"
            % (subsfile, file_name, folder_name),
        )

        subsfile = subsfile.split(".")
        file_name = file_name.split(".")[:-1]
        folder_name = folder_name.split(".")

        if len(file_name) > len(folder_name):
            diff_file = list(set(file_name) - set(subsfile))
            rating = (1 - (len(diff_file) / float(len(file_name)))) * 5
        else:
            diff_folder = list(set(folder_name) - set(subsfile))
            rating = (1 - (len(diff_folder) / float(len(folder_name)))) * 5

        log(
            __scriptname__,
            "\n rating: %f (by %s)" % (round(rating, 1), "file" if len(file_name) > len(folder_name) else "folder"),
        )

        return round(rating, 1)
Example #2
1
def getIndices(shape, offset):
    "returns a list with 2 lists: vertices and face indexes, offsetted with the given amount"
    vlist = []
    elist = []
    flist = []
    for v in shape.Vertexes:
        vlist.append(" " + str(round(v.X, p)) + " " + str(round(v.Y, p)) + " " + str(round(v.Z, p)))
    if not shape.Faces:
        for e in shape.Edges:
            if DraftGeomUtils.geomType(e) == "Line":
                ei = " " + str(findVert(e.Vertexes[0], shape.Vertexes) + offset)
                ei += " " + str(findVert(e.Vertexes[-1], shape.Vertexes) + offset)
                elist.append(ei)
    for f in shape.Faces:
        if len(f.Wires) > 1:
            # if we have holes, we triangulate
            tris = f.tessellate(1)
            for fdata in tris[1]:
                fi = ""
                for vi in fdata:
                    vdata = Part.Vertex(tris[0][vi])
                    fi += " " + str(findVert(vdata, shape.Vertexes) + offset)
                flist.append(fi)
        else:
            fi = ""
            # OCC vertices are unsorted. We need to sort in the right order...
            edges = DraftGeomUtils.sortEdges(f.Wire.Edges)
            # print edges
            for e in edges:
                # print e.Vertexes[0].Point,e.Vertexes[1].Point
                v = e.Vertexes[0]
                fi += " " + str(findVert(v, shape.Vertexes) + offset)
            flist.append(fi)
    return vlist, elist, flist
Example #3
1
def do_padding(img, padding):
    if not padding:
        return img
    try:
        padding = float(padding)*2.0
        if padding > .9:
            padding = .9
        if padding <= 0.0:
            return img
    except ValueError:
        return

    iw, ih = img.size

    img.thumbnail(
        (
            int( round( float(img.size[0]) * (1.0 - padding) ) ),
            int( round( float(img.size[1]) * (1.0 - padding) ) )
        ),
        pil.ANTIALIAS
        )

    img = do_fill(img, "ffffff00", iw, ih)

    return img
Example #4
1
def compareEvents(archApplURL, xmlRPCURL, pvName, startTime, endTime):
    print archApplURL, xmlRPCURL, pvName
    jsonData = fetchJSON(archApplURL, pvName, startTime, endTime)
    print "Event from appliance = {0}".format(len(jsonData))
    caData = fetchCAData(xmlRPCURL, pvName, startTime, endTime)
    print "Event from CA = {0}".format(len(caData))
    jsonevnum = 0
    caevnum = 0
    while jsonevnum < len(jsonData) and caevnum < len(caData):
        if jsonevnum < len(jsonData):
            jsonEvent = jsonData[jsonevnum]
        if caevnum < len(caData):
            caEvent = caData[caevnum]
        if jsonEvent and caEvent:
            if jsonEvent["secs"] > caEvent["secs"]:
                caevnum = caevnum + 1
                print "\t\t\t\t{0}".format(caEvent["secs"])
            elif jsonEvent["secs"] < caEvent["secs"]:
                jsonevnum = jsonevnum + 1
                print "{0}".format(jsonEvent["secs"])
            else:
                jsonevnum = jsonevnum + 1
                caevnum = caevnum + 1
                jsval = round(float(jsonEvent["val"]), 2)
                caval = round(float(caEvent["value"][0]), 2)
                if jsval != caval:
                    print "Values are different JS:{0} and CA{1}".format(jsval, caval)
Example #5
1
    def doPointsFromGeometry(self, geom, idParcel):
        if (geom != None) and geom.isGeosValid() and (idParcel > 0):
            self.orderPoint = 1
            self.numberPoint = 1

            if geom.isMultipart():
                polygons = geom.asMultiPolygon()
                for polygon in polygons:
                    self.currentSpatialElement = 0
                    for ring in polygon:
                        listPoint = []
                        self.currentSpatialElement += 1
                        for point in ring:
                            x = round(point.x(), 2)
                            y = round(point.y(), 2)
                            listPoint.append([x, y])

                        self.doAppend(listPoint, idParcel)

            else:
                self.currentSpatialElement = 0
                polygon = geom.asPolygon()
                for ring in polygon:
                    listPoint = []
                    self.currentSpatialElement += 1
                    for point in ring:
                        x = round(point.x(), 2)
                        y = round(point.y(), 2)
                        listPoint.append([x, y])

                    self.doAppend(listPoint, idParcel)
Example #6
1
    def testResampleMtGoxDay(self):
        # Resample.
        feed = mtgoxfeed.CSVTradeFeed()
        feed.addBarsFromCSV(common.get_data_file_path("trades-mgtox-usd-2013-01-01.csv"))
        resampledBarDS = resampled.ResampledBarDataSeries(feed["BTC"], bar.Frequency.DAY)
        resampledFile = os.path.join(common.get_temp_path(), "day-mgtox-usd-2013-01-01.csv")
        resample.resample_to_csv(feed, bar.Frequency.DAY, resampledFile)
        resampledBarDS.pushLast()  # Need to manually push the last stot since time didn't change.

        # Load the resampled file.
        feed = csvfeed.GenericBarFeed(bar.Frequency.DAY)
        feed.addBarsFromCSV("BTC", resampledFile)
        feed.loadAll()

        self.assertEqual(len(feed["BTC"]), 1)
        self.assertEqual(feed["BTC"][0].getDateTime(), datetime.datetime(2013, 1, 1))
        self.assertEqual(feed["BTC"][0].getOpen(), 13.51001)
        self.assertEqual(feed["BTC"][0].getHigh(), 13.56)
        self.assertEqual(feed["BTC"][0].getLow(), 13.16123)
        self.assertEqual(feed["BTC"][0].getClose(), 13.30413)
        self.assertEqual(feed["BTC"][0].getVolume(), 28168.9114596)
        self.assertEqual(feed["BTC"][0].getAdjClose(), 13.30413)

        self.assertEqual(len(resampledBarDS), len(feed["BTC"]))
        self.assertEqual(resampledBarDS[0].getDateTime(), dt.as_utc(feed["BTC"][0].getDateTime()))
        self.assertEqual(resampledBarDS[-1].getDateTime(), dt.as_utc(feed["BTC"][-1].getDateTime()))
        self.assertEqual(resampledBarDS[0].getOpen(), feed["BTC"][0].getOpen())
        self.assertEqual(resampledBarDS[0].getHigh(), feed["BTC"][0].getHigh())
        self.assertEqual(resampledBarDS[0].getLow(), feed["BTC"][0].getLow())
        self.assertEqual(resampledBarDS[0].getClose(), feed["BTC"][0].getClose())
        self.assertEqual(round(resampledBarDS[0].getVolume(), 5), round(feed["BTC"][0].getVolume(), 5))
        self.assertEqual(resampledBarDS[0].getAdjClose(), feed["BTC"][0].getAdjClose())
Example #7
1
def expect_model_param(models, attribute_name, expected_values):
    print "param: {0}".format(attribute_name)
    actual_values = list(
        set(
            [
                m.params[attribute_name]["actual"]
                if type(m.params[attribute_name]["actual"]) != list
                else m.params[attribute_name]["actual"][0]
                for m in models.models
            ]
        )
    )
    # possible for actual to be a list (GLM)
    if type(expected_values) != list:
        expected_values = [expected_values]
    # limit precision. Rounding happens in some models like RF
    actual_values = [x if isinstance(x, basestring) else round(float(x), 5) for x in actual_values]
    expected_values = [x if isinstance(x, basestring) else round(float(x), 5) for x in expected_values]
    print "actual values: {0}".format(actual_values)
    print "expected values: {0}".format(expected_values)
    actual_values_len = len(actual_values)
    expected_values_len = len(expected_values)
    assert actual_values_len == expected_values_len, "Expected values len: {0}. Actual values len: " "{1}".format(
        expected_values_len, actual_values_len
    )
    diff = set(actual_values) - set(expected_values)
    assert len(diff) == 0, "Difference between actual and expected values: {0}".format(diff)
Example #8
0
    def _set_time(self, thing, time_created):
        time_uploaded = int(round(time.time()))
        time_created = int(round(time_created))

        to_rfc3339 = strict_rfc3339.timestamp_to_rfc3339_localoffset
        thing["time_uploaded"] = to_rfc3339(time_uploaded)
        thing["time_created"] = to_rfc3339(time_created)
Example #9
0
 def listTorrents(self):
     token = self.getToken()
     url = self.baseurl + "?token=" + token + "&list=1"
     data = self.myClient.HttpCmd(url)
     data = data.split("\n")
     torrentList = []
     for line in data:
         if '"rssfeeds"' in line:
             break
         if len(line) > 80:
             tor = re.findall('"[^"]*"|[0-9\-]+', line)
             hashnum = tor[0][1:-1]
             status = tor[1]
             torname = tor[2].replace('"', "")
             complete = tor[4]
             complete = int(complete)
             complete = complete / 10.0
             size = int(tor[3]) / (1024 * 1024)
             if size >= 1024.00:
                 size_str = str(round(size / 1024.00, 2)) + "Gb"
             else:
                 size_str = str(size) + "Mb"
             up_rate = round(float(tor[8]) / (1024), 2)
             down_rate = round(float(tor[9]) / (1024), 2)
             remain = int(tor[10]) / 60
             if remain >= 60:
                 remain_str = str(remain // 60) + "h " + str(remain % 60) + "m"
             elif remain == -1:
                 remain_str = "?"
             else:
                 remain_str = str(remain) + "m"
             tup = (hashnum, status, torname, complete, size_str, up_rate, down_rate, remain_str)
             print(torname + str(status))
             torrentList.append(Torrent(tup))
     return torrentList
 def obsDetect(self, msg):
     # Calculate the total number of measurements in lidar scan
     numScansTot = int(round((msg.angle_max - msg.angle_min) / msg.angle_increment))
     # Calculate the number we'll use based on thetaMax
     numScansUsed = int(round((2 * self.thetaMax) / msg.angle_increment))
     # Don't use more scans than you have!!
     if numScansUsed > numScansTot:
         numScansUsed = numScansTot
     firstIndex = int(round((numScansTot / 2 - numScansUsed / 2)))
     lastIndex = int(round((numScansTot / 2 + numScansUsed / 2)))
     # Create an empty obstacle array
     obsArray = ObstacleArray()
     obsArray.obstacles = ()
     for x in xrange(firstIndex, lastIndex):
         # Check to make sure the intensity is not zero.
         if msg.intensities[x] != 0:
             # Then make sure it is in range
             if msg.ranges[x] <= self.rangeMax:
                 # If so, stick the measurement's range and angle in an
                 # ObstacleMsg and append it to the ObstacleArray
                 obsMsg = ObstacleMsg()
                 obsMsg.angle = x * msg.angle_increment + msg.angle_min
                 obsMsg.distance = msg.ranges[x]
                 obsArray.obstacles = obsArray.obstacles + (obsMsg,)
     # Then stamp it and add the frame_id
     obsArray.header.stamp = msg.header.stamp
     obsArray.header.frame_id = self.laserFrame
     # And if any obstacles were found, publish it!
     if obsArray.obstacles:
         self.obsPub.publish(obsArray)
Example #11
0
File: Gridify.py Project: qgis/QGIS
    def _gridify(self, points, hSpacing, vSpacing):
        nPoints = []
        for p in points:
            nPoints.append(QgsPoint(round(p.x() / hSpacing, 0) * hSpacing, round(p.y() / vSpacing, 0) * vSpacing))

        i = 0
        # Delete overlapping points
        while i < len(nPoints) - 2:
            if nPoints[i] == nPoints[i + 1]:
                nPoints.pop(i + 1)
            else:
                i += 1

        i = 0
        # Delete line points that go out and return to the same place
        while i < len(nPoints) - 3:
            if nPoints[i] == nPoints[i + 2]:
                nPoints.pop(i + 1)
                nPoints.pop(i + 1)

                # Step back to catch arcs
                if i > 0:
                    i -= 1
            else:
                i += 1

        i = 0
        # Delete overlapping start/end points
        while len(nPoints) > 1 and nPoints[0] == nPoints[len(nPoints) - 1]:
            nPoints.pop(len(nPoints) - 1)

        return nPoints
def print_report(report, total, new_count, console_report):
    if console_report != "":
        with open(console_report, "w") as report_doc:
            report_doc.write("")
            report_doc.write("{0:^19}|{1:^19}|{2:^19}|{3:^19}".format("flag", "single", "best of multi", "of total"))
            report_doc.write("-" * 79)
            for key in report.keys():
                s = report[key][0]
                m = report[key][1]
                report_doc.write(
                    "{0:^19}|{1:^19}|{2:^19}|{3:^19}".format(key, str(s), str(m), round(((s + m) / float(total)), 2))
                )
            report_doc.write("")
            report_doc.write("number of seq: previous " + str(total) + ", now " + str(new_count))
            report_doc.write("")
    print("")
    print("{0:^19}|{1:^19}|{2:^19}|{3:^19}".format("flag", "single", "best of multi", "of total"))
    print("-" * 79)
    for key in report.keys():
        s = report[key][0]
        m = report[key][1]
        print("{0:^19}|{1:^19}|{2:^19}|{3:^19}".format(key, str(s), str(m), round(((s + m) / float(total)), 2)))
    print("")
    print("number of seq: previous " + str(total) + ", now " + str(new_count))
    print("")
Example #13
0
    def find_and_process_refund_vouchers(self, cr, uid, auth, client, voucher, object, transaction):
        eligible_refund_vouchers = self.find_eligible_refund_vouchers(cr, uid, voucher)
        refund_amount = voucher.amount

        if not eligible_refund_vouchers:
            raise osv.except_osv(
                _("User Error"),
                _(
                    "You are trying to process a refund but there are no eligible payments to refund. Please manually refund this transaction in Authorize.net"
                ),
            )

        done = False
        for eligible_voucher in self.pool.get("account.voucher").browse(cr, uid, eligible_refund_vouchers):

            transaction["transId"] = eligible_voucher.transaction_id

            if round(refund_amount, 2) > round(eligible_voucher.amount, 2):
                transaction["amount"] = round(eligible_voucher.amount, 2)
                refund_amount -= round(eligible_voucher.amount, 2)

            else:
                transaction["amount"] = round(refund_amount, 2)
                done = True

            self.refund_transaction(cr, uid, auth, client, eligible_voucher, voucher, object, transaction)

            if done:
                break

        return True
Example #14
0
    def refund_transaction(self, cr, uid, auth, client, original_voucher, voucher, object, trans_vals):

        # If the voucher being refunded contains multiple transactions
        if original_voucher.capture_transaction_id:
            capture_vals = trans_vals

            refund_total = trans_vals["amount"] * -1
            charge_amount = round(original_voucher.amount, 2) - round(original_voucher.capture_addl_amount, 2)
            capture_amount = round(original_voucher.capture_addl_amount, 2)

            # The refund amount is greater than the additional capture amount
            # In this case we need to do 2 calls. Refund the original charge
            # And the extra charge we captured
            if refund_total > capture_amount:
                capture_vals["amount"] = capture_amount
                capture_vals["transId"] = original_voucher.capture_transaction_id
                self.send_refund_transaction(cr, uid, auth, client, object, original_voucher, capture_vals)

                # Once we refund the captured amount, refund the original charge - captured amount.
                trans_vals["amount"] = refund_total - capture_amount
                self.send_refund_transaction(cr, uid, auth, client, object, trans_vals)
                return True

                # The additional captured amount is less or equal to the amount required for refund
            else:
                capture_vals["transId"] = original_voucher.capture_transaction_id
                self.send_refund_transaction(cr, uid, auth, client, object, original_voucher, capture_vals)
                return True

                # There is no additional captures on the voucher
        else:
            self.send_refund_transaction(cr, uid, auth, client, object, original_voucher, trans_vals)
Example #15
0
def tP(point, places=3):
    """
	    return a tuple for a point.
		rounds to the number of places specified to ensure that
		rounding error does not result in non-coincident nodes
	"""
    return (round(point.X(), places), round(point.Y(), places))
Example #16
0
 def __repr__(self):
     s = "image at ("
     s += str(round(self._x0, 3)) + ","
     s += str(round(self._y0, 3)) + "):("
     s += str(round(self._x1, 3)) + ","
     s += str(round(self._y1, 3)) + ")"
     return s
def get_gdf(stop=True):
    """Returns a string containing a GDF file. Setting stop to True will cause
    the trace to stop.
    """
    ret = [
        "nodedef>name VARCHAR, label VARCHAR, hits INTEGER, "
        + "calls_frac DOUBLE, total_time_frac DOUBLE, "
        + "total_time DOUBLE, color VARCHAR, width DOUBLE"
    ]
    for func, hits in func_count.items():
        calls_frac, total_time_frac, total_time = _frac_calculation(func, hits)
        col = settings["node_colour"](calls_frac, total_time_frac)
        color = ",".join([str(round(float(c) * 255)) for c in col.split()])
        ret.append(
            "%s,%s,%s,%s,%s,%s,'%s',%s"
            % (func, func, hits, calls_frac, total_time_frac, total_time, color, math.log(hits * 10))
        )
    ret.append("edgedef>node1 VARCHAR, node2 VARCHAR, color VARCHAR")
    for fr_key, fr_val in call_dict.items():
        if fr_key == "":
            continue
        for to_key, to_val in fr_val.items():
            calls_frac, total_time_frac, total_time = _frac_calculation(to_key, to_val)
            col = settings["edge_colour"](calls_frac, total_time_frac)
            color = ",".join([str(round(float(c) * 255)) for c in col.split()])
            ret.append("%s,%s,'%s'" % (fr_key, to_key, color))
    ret = "\n".join(ret)
    return ret
Example #18
0
File: line.py Project: gdos/pylygon
    def line_trace(self):
        """return integer coordinates, or pixels, crossed by self"""
        s = set()  # coordinates crossed by self
        delta_x, delta_y = self.delta
        p_x, p_y = self.p
        q_x, q_y = self.q
        m, b = self.m, self.b
        s.add((p_x, p_y))

        if (m) or (abs(m) >= 1):  # rise > run
            m = 1 / m  # rotate m by 90 degrees
            b = -(b * m)  # rotate b by 90 degrees
            # determine direction of p_y to q_y
            if delta_y < 0:
                delta_y = -1
            else:
                delta_y = 1
            # trace from p_y to q_y
            while p_y != q_y:
                p_y += delta_y
                s.add((round((m * p_y) + b), p_y))

        else:  # else rise < run
            # determine direction of p_x to q_x
            if delta_x < 0:
                delta_x = -1
            else:
                delta_x = 1
            # trace from p_x to q_x
            while p_x != q_x:
                p_x += delta_x
                s.add((p_x, round((m * p_x) + b)))

        return s
def tournament_fittest(sn):
    f_of = sn.fitness_of
    f = sn.fitness
    node_set = sn.node_set
    g = sn.g

    winners = []
    for i in range(round(sn.size * sn.X)):

        # avoid repetitions randomly select the participants
        tombola = random.sample(node_set, round(sn.size * sn.tourn))

        # search for the "winners" (or really "losers")
        max_fit = -1
        ties = []
        for t in tombola:
            cur_fit = f[g.node[t]["r_index"]]
            if cur_fit > max_fit:
                max_fit = cur_fit
                ties = [t]
            elif cur_fit == max_fit:
                ties.append(t)

        # in case of tie, select one randomly
        w = random.choice(ties)
        winners.append(w)
        # we already know this node won't exist,
        # so we can remove it forever
        f_of[g.node[w]["r_index"]] = -1
        node_set.discard(w)

    return winners
Example #20
0
def status_bar(score, full_score=1, size=100):
    fraction = float(score) / full_score
    if fraction > 1.0:
        fraction = 1.0
    if fraction < 0.0:
        fraction = 0.0
    return (
        (
            """
        <span style="display: block;
                     float: left;
                     margin-right: -%dpx;
                     position: relative;
                     top: 8px;">"""
            + """<span style="display: inline-block;
                            width: %dpx;
                            height: 2px;
                            background: #44AA00;"></span>"""
            + """<span style="display: inline-block;
                            width: %dpx;
                            height: 2px;
                            background: #AA4400;"></span>"""
            + """</span>"""
        )
        % (size, round(fraction * size), round((1 - fraction) * size))
    )
Example #21
0
def print_progress(iterations, total, prefix="", suffix="", decimals=2, barLength=80, colors=False):
    """
	Call in a loop to create terminal progress bar
	@params:
		iterations  - Required  : current iteration (Int)
		total       - Required  : total iterations (Int)
		prefix      - Optional  : prefix string (Str)
		suffix      - Optional  : suffix string (Str)
		decimals    - Optional  : Number of decimal places to display
		barLength   - Optional  : Number of characters that encompass bar length
		colors      - Optional  : Specifies whether to use ANSI terminal colors
	"""
    COLOR_RED = "\033[31m"
    COLOR_GREEN = "\033[32m"
    COLOR_YELLOW = "\033[33m"
    COLOR_ENDC = "\033[0m"
    filledLength = int(round(barLength * iterations / float(total)))
    percents = round(100.00 * (iterations / float(total)), decimals)
    bar = "#" * filledLength + "-" * (barLength - filledLength)

    color = ""
    if colors:
        if percents < 30:
            color = COLOR_RED
        elif percents < 70:
            color = COLOR_YELLOW
        else:
            color = COLOR_GREEN
    string = "%s%s [%s] %s%s %s\r" % (color, prefix, bar, percents, "%", suffix)
    sys.stderr.write(string)
    sys.stderr.write(COLOR_ENDC)
    sys.stderr.flush()
    if iterations == total:
        sys.stderr.write("\n")
        sys.stderr.flush()
Example #22
0
def maksimin():
    min_array = list()
    for i in range(0, N + 3):
        result1.append([])
        result2.append([])
        result3.append([])
        result4.append([])
        result5.append([])
        # for j in range(0, 9):
        # alt = random.randint(1, 9)
        maks1 = Q1[i] / QZ[i]
        maks2 = Q2[i] / QZ[i]
        maks3 = Q3[i] / QZ[i]
        maks4 = Q4[i] / QZ[i]
        maks5 = Q5[i] / QZ[i]
        result[i].append(round(maks1, 2))
        result[i].append(round(maks2, 2))
        result[i].append(round(maks3, 2))
        result[i].append(round(maks4, 2))
        result[i].append(round(maks5, 2))
    column = list()
    for i in range(0, 9):
        for j in range(0, 9):
            column.append(result[i])
        min_array.append(min(column))
        column = list()
    result.append(min_array)
    result.append(max(min_array))

    return result
Example #23
0
def gi_bill_stories():
    bounce_rates = strip_percentage(df_gb_bounce_rate["Bounce Rate"].tolist())
    bounce_rates = remove_zeroes(bounce_rates)  # [elem for elem in bounce_rates if elem != 0]
    inverse_bounce_rates = invert_percentage(bounce_rates)
    ave_users_finding_what_they_need = average(inverse_bounce_rates)
    new_sessions = strip_percentage(df_gb_new_sessions["% New Sessions"].tolist())
    new_sessions = remove_zeroes(new_sessions)
    ave_percentage_of_new_sessions = average(new_sessions)
    sessions = df_gb_sessions["Sessions"].tolist()
    sessions = remove_zeroes(sessions)
    total_new_sessions = process_sessions(new_sessions, sessions)
    ave_new_sessions_per_day = average(total_new_sessions)
    page_views = ["page views"] + df_gb_page_views["Pageviews"].tolist()
    page_views = remove_zeroes(page_views)
    total_users = df_vg_users["Users"].tolist()
    ave_users = average(total_users)
    ave_session_duration = average(to_seconds(df_gb_ave_session_duration["Avg. Session Duration"].tolist())) / float(60)
    ave_pages_per_session = average(calc_pages_per_session(strip_label(page_views), strip_label(sessions)))

    return render_template(
        "vets_dot_gov_stories.html",
        ave_users_finding_what_they_need=round(ave_users_finding_what_they_need, 2),
        ave_new_sessions_per_day=round(ave_new_sessions_per_day, 2),
        ave_percentage_of_new_sessions=round(ave_percentage_of_new_sessions, 2),
        ave_session_duration=round(ave_session_duration, 2),
        ave_pages_per_session=round(ave_pages_per_session, 2),
        gi_bill=True,
        vets_dot_gov=False
        # users_finding_what_they_need=json.dumps(bounce_rate),
        # new_sessions=json.dumps(new_sessions),
        # sessions=json.dumps(sessions),
        # page_views=json.dumps(page_views),
        # users=json.dumps(users)
    )
Example #24
0
    def render_debug_text(self, connections, state, elements, areas):
        text = "{}, {}".format(self.mouse.map_pos.x, self.mouse.map_pos.y)
        self.render_text(text, 4, 4)

        x = 4
        y = 46

        if state is not None:
            text = "floor z: {}, ceil z: {}, block line: {}, block thing: {}, special sector {}".format(
                round(state.floorz, 2), round(state.ceilz, 2), state.blockline, state.blockthing, state.special_sector
            )
            self.render_text(text, 4, 20)
            y += 18

        if elements is not None:
            for element in elements:
                self.render_text(str(element), x, y)
                y += 18

        if connections is not None:
            for connection in connections:
                self.render_text(str(connection), x, y)
                y += 18

        if areas is not None:
            for area in areas:
                self.render_text(str(area), x, y)
                y += 18
Example #25
0
def cyclistEnergyUse(parent, cyclistWeight, bikeWeight, velocity):
    # Calculate bike kJ/km and km/kJ
    # Invoked by cyclist data frame when any field changed
    # Converted from metric input to imperial for use with Irons formula
    cyclistWeight = cyclistWeight.get()
    bikeWeight = bikeWeight.get()
    velocity = velocity.get()
    # Check fields are not empty
    if cyclistWeight != "" and bikeWeight != "" and velocity != "":
        # Convert metric input to imperial for Irons formula
        cyclistWeight = float(cyclistWeight) * 2.2046  # kg -> lb
        bikeWeight = float(bikeWeight) * 2.2046  # kg -> lb
        velocity = float(velocity) * 0.6214  # km/hr -> mi/hr
        # Calculate energy use (output units = kcal/hr)
        energyUse = (0.0053 * velocity * (cyclistWeight + bikeWeight) + 0.0083 * velocity ** 3) * 7.2
        # Convert imperial to metric
        energyUse = energyUse * 4.1868  # kcal/hr -> kJ/hr
        # Divide through velocity to get kJ/km
        energyUse = energyUse / velocity  # kJ/hr -> kJ/km
        parent.comparisons.cyclistEnergyUse.set(round(energyUse))
        parent.comparisons.cyclistDistance.set(round((1 / energyUse) * 1000, 2))
    else:
        # Otherwise set to blank
        parent.comparisons.cyclistEnergyUse.set("-")
        parent.comparisons.cyclistDistance.set("-")
	def updateAmount(self, newAmount = 0):
		if newAmount < self.min: newAmount = self.min
		if newAmount > self.max: newAmount = self.max
		self.amount = newAmount

		# Figure out the new percent done, round to an integer
		diffFromMin = float(self.amount - self.min)
		percentDone = (diffFromMin / float(self.span)) * 100.0
		percentDone = round(percentDone)
		percentDone = int(percentDone)

		# Figure out how many hash bars the percentage should be
		allFull = self.width - 2
		numHashes = (percentDone / 100.0) * allFull
		numHashes = int(round(numHashes))

		# build a progress bar with hashes and spaces
		self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]"

		# figure out where to put the percentage, roughly centered
		percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) 
		percentString = str(percentDone) + "%"

		# slice the percentage into the bar
		self.progBar = self.progBar[0:percentPlace] + percentString + 
 def nextStep(self, newScene=False):
     if newScene == True:
         self.next_step = 0
     else:
         if self.current_scene["order"] == "random":
             step = randint(0, len(self.current_scene["steps"]) - 1)
             while step == self.next_step:
                 step = randint(0, len(self.current_scene["steps"]) - 1)
             self.next_step = step
         else:
             if self.next_step < (len(self.current_scene["steps"]) - 1):
                 self.next_step += 1
             elif self.current_scene["repeat"] == True:
                 self.next_step = 0
             else:
                 return
     self.scene_updated = False
     self.hold_frames = (
         int(round(self.current_scene["steps"][self.next_step]["hold"] / self.config["frame_duration"])) + 1
     )
     self.fade_frames = int(
         round(self.current_scene["steps"][self.next_step]["fade"] / self.config["frame_duration"])
     )
     print (
         "Playing scene: %-30s Step: %02d/%02d"
         % (self.current_scene["name"], self.next_step + 1, len(self.current_scene["steps"]))
     )
Example #28
0
    def get_level_progress(self, player):
        """ Get player progress inside its level """
        level_no = player.level_no
        points = player.points
        try:
            if level_no == 1:
                current_limit = 0
            else:
                current_limit = DefaultGod.LEVEL_LIMITS[level_no - 2]
        except:
            current_limit = 0
        try:
            next_limit = DefaultGod.LEVEL_LIMITS[level_no - 1]
        except:
            next_limit = 1000

        points_gained = points - current_limit
        if next_limit > current_limit:
            percent = round(100.0 * points_gained / (next_limit - current_limit))
        else:
            percent = round(100.0 * points_gained / next_limit)

        return dict(
            next_level=level_no + 1, points_gained=points_gained, points_left=next_limit - points, percent=percent
        )
Example #29
0
    def getPos(self):
        """ returns (x, y) """

        # get the analog axis position and map it to some
        # pixel distance in sage coordinates
        (dx, dy) = self.joy.GetPosition()
        (dx, dy) = self.toSAGECoords(dx, dy)

        dx = int(round(dx))
        dy = int(round(dy))

        # keep the pointer inside the display
        if self.x + dx < 0:
            dx = -self.x
        elif self.x + dx > self.dispSize[0]:
            dx = self.dispSize[0] - self.x
        if self.y + dy < 0:
            dy = -self.y
        elif self.y + dy > self.dispSize[1]:
            dy = self.dispSize[1] - self.y

        # accumulate the position
        self.x += dx
        self.y += dy

        return dx, dy
Example #30
0
    def add_period(self, timestamp, cpu_usage, mem_usage):
        cpu_usage = round(cpu_usage, 4)
        mem_usage = round(mem_usage, 4)

        if mongo.has_bulk:
            bulk = self.collection.initialize_unordered_bulk_op()
        else:
            bulk = None

        for period in ("1m", "5m", "30m", "2h", "1d"):
            spec = {
                "host_id": self.host_id,
                "period": period,
                "timestamp": usage_utils.get_period_timestamp(period, timestamp),
            }
            doc = {"$inc": {"count": 1, "cpu": cpu_usage, "mem": mem_usage}}
            rem_spec = {
                "host_id": self.host_id,
                "period": period,
                "timestamp": {"$lt": usage_utils.get_period_max_timestamp(period, timestamp)},
            }

            if bulk:
                bulk.find(spec).upsert().update(doc)
                bulk.find(rem_spec).remove()
            else:
                self.collection.update(spec, doc, upsert=True)
                self.collection.remove(rem_spec)

        if bulk:
            bulk.execute()