def __call__(self, field_data, all_data):
     data = str(field_data)
     try:
         float(data)
     except ValueError:
         raise ValidationError, gettext("Please enter a valid decimal number.")
     # Negative floats require more space to input.
     max_allowed_length = data.startswith("-") and (self.max_digits + 2) or (self.max_digits + 1)
     if len(data) > max_allowed_length:
         raise ValidationError, ngettext(
             "Please enter a valid decimal number with at most %s total digit.",
             "Please enter a valid decimal number with at most %s total digits.",
             self.max_digits,
         ) % self.max_digits
     if (not "." in data and len(data) > (max_allowed_length - self.decimal_places - 1)) or (
         "." in data and len(data) > (max_allowed_length - (self.decimal_places - len(data.split(".")[1])))
     ):
         raise ValidationError, ngettext(
             "Please enter a valid decimal number with a whole part of at most %s digit.",
             "Please enter a valid decimal number with a whole part of at most %s digits.",
             str(self.max_digits - self.decimal_places),
         ) % str(self.max_digits - self.decimal_places)
     if "." in data and len(data.split(".")[1]) > self.decimal_places:
         raise ValidationError, ngettext(
             "Please enter a valid decimal number with at most %s decimal place.",
             "Please enter a valid decimal number with at most %s decimal places.",
             self.decimal_places,
         ) % self.decimal_places
Example #2
1
def calc_pr(bigccmat, numnodes, pprloc=-99):
    """
    function calc_pr calculates PageRank based on the input transition matrix
    """
    # convert to transition matrix
    rowsum = bigccmat.sum(axis=1)
    for ii in range(numnodes):
        if rowsum[ii, 0] != 0:
            bigccmat[ii, :] = bigccmat[ii, :] / rowsum[ii, 0]
        else:
            # case with no outgoing links
            bigccmat[ii, ii] = 1.0

    # convert sparse matrix format
    sp_transmat_first = scisp.csr_matrix(bigccmat)
    oldprvec = np.matrix(np.ones((numnodes, 1))) / float(numnodes)
    convergevec = [1000]  # some large value
    if pprloc > 0:
        onevec = np.matrix(np.zeros((numnodes, 1)))
        onevec[pprloc, 0] = 0.15
    else:
        onevec = (0.15 / float(numnodes)) * np.matrix(np.ones((numnodes, 1)))
    ii = 0
    while convergevec[-1] > 1e-5:
        newprvec = 0.85 * (sp_transmat_first.T * oldprvec)
        newprvec = newprvec + onevec
        newnorm = np.linalg.norm(newprvec, 1)
        convergevec.append(sum(abs(newprvec - oldprvec))[0, 0])
        oldprvec = newprvec
        ii = ii + 1
    print "Norm of PR vector:", newnorm
    print "Number of iterations for convergence:", ii
    convergevec.remove(1000)
    return (newprvec, convergevec)
Example #3
1
    def __init__(self, verb, uri, regex, value, unit):
        """Initialize a new `Limit`.

        @param verb: HTTP verb (POST, PUT, etc.)
        @param uri: Human-readable URI
        @param regex: Regular expression format for this limit
        @param value: Integer number of requests which can be made
        @param unit: Unit of measure for the value parameter
        """
        self.verb = verb
        self.uri = uri
        self.regex = regex
        self.value = int(value)
        self.unit = unit
        self.unit_string = self.display_unit().lower()
        self.remaining = int(value)

        if value <= 0:
            raise ValueError("Limit value must be > 0")

        self.last_request = None
        self.next_request = None

        self.water_level = 0
        self.capacity = self.unit
        self.request_value = float(self.capacity) / float(self.value)
        msg = _("Only %(value)s %(verb)s request(s) can be " "made to %(uri)s every %(unit_string)s.") % {
            "value": self.value,
            "verb": self.verb,
            "uri": self.uri,
            "unit_string": self.unit_string,
        }
        self.error_message = msg
Example #4
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 #5
1
    def pct(self, so_far, total=None):
        percentage = str(int(self.percentage * 100)) + "%"
        if self.num_files_left > 1:
            message = _("Uploading %(number)d files to %(service)s") % {
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
            title = _("%(percentage)s of %(number)d files - Uploading to %(service)s") % {
                "percentage": percentage,
                "number": self.num_files_left,
                "service": '"' + service["name"] + '"',
            }
        else:
            message = _("Uploading 1 file to %(service)s") % {"service": '"' + service["name"] + '"'}
            title = _("%(percentage)s of 1 file - Uploading to %(service)s") % {
                "percentage": percentage,
                "service": '"' + service["name"] + '"',
            }

        self.percentage = float(self.size_so_far) / float(self.total_size)
        Gdk.threads_enter()
        try:
            self.progressbar.set_fraction(self.percentage)
            self.progressbar.set_text(str(int(self.percentage * 100)) + "%")
            self.builder.get_object("upload_label").set_text(message)
            self.builder.get_object("main_window").set_title(title)
        finally:
            Gdk.threads_leave()
        pass
Example #6
1
def colorbar(frame, width, height, zmin, zmax):
    """colorbar(frame,width,height,zmin,zmax - draw a horizontal colorbar
    with 256x10 pixels
	width - specify window width
	height - specify window height
	zmin - specify minimum value for colorbar
	zmax - specify maximum value for colorbar
    """
    W = 256
    clrbar = []
    for j in range(10):
        clrbar.append(range(W))
    clrbar = array(clrbar)
    imagebar = PNGImage1(frame, clrbar)
    xl, xr = 0.5 * (width - W), 0.5 * (width + W)
    imagebar.pack(side=LEFT, padx=xl, pady=2)
    np = 5
    dx = float(W) / (np - 1)
    dz = float(zmax - zmin) / (np - 1)
    y0 = height
    for k in range(np):
        xj = xl + k * dx
        xjj = zmin + k * dz
        frame.create_line(xj, y0 + 5, xj, y0 - 5, width=2)
        frame.create_text(xj, y0 - 10, text=("%s" % xjj)[0:5], anchor=S)
Example #7
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
def reccomend(data, p1):
    if len(data[p1].keys()) < 2:
        print("Error: Insufficient data")
        print("Try reviewing some of these: ")
        recc = reccomend(data, "1")
        for film in recc[0:5]:
            print(str(film[1]) + ": " + movies[film[1]])
        return []
    totals = {}
    simSums = {}
    for other in data:
        if other == p1:
            continue
        sim = pearson(data, p1, other)
        if sim <= 0:
            continue
        for item in data[other]:
            if item not in data[p1] or float(data[p1][item]) == 0:
                totals.setdefault(item, 0)
                totals[item] += float(data[other][item]) * sim

                simSums.setdefault(item, 0)
                simSums[item] += sim

        rankings = [(total / simSums[item], item) for item, total in totals.items()]

        rankings.sort()
        rankings.reverse()
        return rankings
Example #9
0
def get_5V_I(root, val, file_name):  # Currently not used
    # Try to open the csv file and set the value of val based on its contents
    try:
        file = open(file_name, "r", newline="")  # open in read mode
        reader = csv.reader(file, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL)

        for row in reader:
            type_val = row[0]
            if type_val == "Self 5V Current":
                min_5V_I = float(row[1])
                max_5V_I = float(row[2])
                ave_5V_I = float(row[3])
        try:
            val.set(
                "5V Current Min:\t\t%8.5fA\n5V Current Max:\t\t%8.5fA\n5V Current Average:\t%8.5fA"
                % (min_5V_I, max_5V_I, ave_5V_I)
            )
        except:
            val.set(
                "5V Current Min:\t\t%8dA\n5V Current Max:\t\t%8dA\n5V Current Average:\t%8dA"
                % (min_5V_I, max_5V_I, ave_5V_I)
            )
        file.close()  # Close CSV

    except IOError as e:
        print(e)
    else:
        # schedule the function to be run again after 1000 milliseconds
        root.after(INFINITE_WAIT, lambda: get_5V_I(root, val, file_name))
Example #10
0
def get_DUT_V(root, val, file_name):
    # Try to open the csv file and set the value of val based on its contents
    try:
        file = open(file_name, "r", newline="")  # open in read mode
        reader = csv.reader(file, delimiter=",", quotechar="|", quoting=csv.QUOTE_MINIMAL)

        for row in reader:
            type_val = row[0]
            if type_val == "DUT Voltage":
                min_DUT_V = float(row[1])
                max_DUT_V = float(row[2])
                ave_DUT_V = float(row[3])
        try:
            val.set(
                "DUT Voltage Min:\t\t%8.5fV\nDUT Voltage Max:\t\t%8.5fV\nDUT Voltage Average:\t%8.5fV"
                % (min_DUT_V, max_DUT_V, ave_DUT_V)
            )
        except:
            val.set(
                "DUT Voltage Min:\t\t%8dV\nDUT Voltage Max:\t\t%8dV\nDUT Voltage Average:\t%8dV"
                % (min_DUT_V, max_DUT_V, ave_DUT_V)
            )
        file.close()  # Close CSV

    except IOError as e:
        print(e)
    else:
        # schedule the function to be run again after 1000 milliseconds
        root.after(UPDATE_DATA_PERIOD, lambda: get_DUT_V(root, val, file_name))
Example #11
0
    def __init__(self):
        """
        :param one_user: 用户的id,即是猎头的id
        :return:
        """
        self.weibo_list = []
        self.time_list = []
        self.weibo = []
        self.writing_time = []
        self.base_page = []
        self.dictwt = {}
        self.no_repeat_list = []
        self.comment_dir = os.path.join(BASE_DIR, "documents", "comment/")  # 猎头微博的评论内容
        self.forward_path_dir = os.path.join(BASE_DIR, "documents", "forward_path/")  # 猎头的微博的转发路径
        self.header = {
            "User-Agent": "Mozilla/"
            + str(float(int(random.uniform(1, 6))))
            + "(X11; Ubuntu; Linux i686; rv:35.0) Gecko/20100101 Firefox/"
            + str(float(int(random.uniform(29, 36))))
        }

        self.blog_id = ""
        self.post_time = ""
        self.event_id = ""
        self.corpus_dir = ""
        self.link = ""
Example #12
0
    def analyze_results(self, tests, results):
        if results is None:
            return

        error = False
        for i, res in enumerate(results):
            print("IN", repr(tests["param_in"][i]))
            print("EXP", "\n    ".join([repr(r) for r in tests["return_possibilities"][i]]))
            print("OUT", repr(res))

            if tests["shall_round"][i]:
                if round(float(res), 5) not in [float(q) for q in tests["return_possibilities"][i]]:
                    error = True
                    print("ERROR return value wrong!")
            elif tests["set"][i]:
                if ";".split(res) not in [";".split(q) for q in tests["return_possibilities"][i]]:
                    error = True
                    print("ERROR return value wrong!")
            else:
                if res not in tests["return_possibilities"][i]:
                    error = True
                    print("ERROR return value wrong!")

        if error:
            raise Exception("eval-test failed!")
def main(ic, annotate=False):
    u_prev = Function(ic, name="Temperature")
    u_next = Function(ic, name="TemperatureNext")
    u_mid = Constant(0.5) * u_prev + Constant(0.5) * u_next

    dt = 0.001
    T = 0.003
    t = 0.0

    v = TestFunction(V)

    states = [Function(ic)]
    times = [float(t)]

    if annotate:
        adj_start_timestep(time=t)
    timestep = 0

    while t < T:
        print "Solving for t == %s" % (t + dt)
        F = inner((u_next - u_prev) / Constant(dt), v) * dx + inner(grad(u_mid), grad(v)) * dx
        solve(F == 0, u_next, J=derivative(F, u_next), annotate=annotate)
        u_prev.assign(u_next, annotate=annotate)

        t += dt
        timestep += 1
        states.append(Function(u_next, name="TemperatureT%s" % timestep, annotate=False))
        times.append(float(t))

        if annotate:
            adj_inc_timestep(time=t, finished=t >= T)

    return (times, states, u_prev)
def aggr_by_hour(time_of_90s, top_news):
    """Finds the percentage of inactive news at each time period.

  Calculates for both all news and top news.

  Keyword Arguments:
  time_of_90s -- The time at which 90% of tweets occured.
  top_news -- A set of urls representing the top news.

  Returns:
  aggregates -- A list of percentages of all news that is inactive.
  aggregates_top -- List of percentages of top news that is inactive.
  """
    log("Aggregating number dead stories by hours...")
    aggregates = []
    aggregates_top = []
    for aggregate_hour in _AGGREGATE_HOURS:
        num_dead_stories = 0
        num_dead_stories_top = 0
        for url, delta in time_of_90s:
            if delta < aggregate_hour:
                num_dead_stories += 1
                if url in top_news:
                    num_dead_stories_top += 1
        aggregates.append(num_dead_stories)
        aggregates_top.append(num_dead_stories_top)
    aggregates = [int((float(aggregate) / len(time_of_90s)) * 100) for aggregate in aggregates]
    aggregates_top = [int((float(aggregate) / len(top_news)) * 100) for aggregate in aggregates_top]
    return aggregates, aggregates_top
Example #15
0
    def _read_columns(self):

        self.raw_columns = self.lines[4:]

        kline = None
        for line in self.lines:
            if line[:7] == "SpringC":
                kline = line
                break

        kline = kline.split(":")

        self.k = float(kline[1])

        xext = []
        xret = []
        yext = []
        yret = []
        for line in self.raw_columns:
            spline = line.split()
            xext.append(float(spline[0]))
            yext.append(float(spline[1]))
            xret.append(float(spline[2]))
            yret.append(float(spline[3]))

        return [[xext, yext], [xret, yret]]
Example #16
0
def dcm_time_to_sec(time_str):
    """Convert a DICOM time value (value representation of 'TM') to the number 
    of seconds past midnight.
    
    Parameters
    ----------
    time_str : str
        The DICOM time value string
        
    Returns
    -------
    A floating point representing the number of seconds past midnight
    """
    # Allow ACR/NEMA style format by removing any colon chars
    time_str = time_str.replace(":", "")

    # Only the hours portion is required
    result = int(time_str[:2]) * 3600

    str_len = len(time_str)
    if str_len > 2:
        result += int(time_str[2:4]) * 60
    if str_len > 4:
        result += float(time_str[4:])

    return float(result)
Example #17
0
    def _image(self, node):
        import urllib
        from reportlab.lib.utils import ImageReader

        u = urllib.urlopen(str(node.getAttribute("file")))
        s = StringIO.StringIO()
        s.write(u.read())
        s.seek(0)
        img = ImageReader(s)
        (sx, sy) = img.getSize()

        args = {}
        for tag in ("width", "height", "x", "y"):
            if node.hasAttribute(tag):
                args[tag] = utils.unit_get(node.getAttribute(tag))
        if ("width" in args) and (not "height" in args):
            args["height"] = sy * args["width"] / sx
        elif ("height" in args) and (not "width" in args):
            args["width"] = sx * args["height"] / sy
        elif ("width" in args) and ("height" in args):
            if (float(args["width"]) / args["height"]) > (float(sx) > sy):
                args["width"] = sx * args["height"] / sy
            else:
                args["height"] = sy * args["width"] / sx
        self.canvas.drawImage(img, **args)
Example #18
0
    def fit(self):
        print("fit the model")
        train = np.array(self.model.data)
        X = train[:, 0:2]
        y = train[:, 2]

        C = float(self.complexity.get())
        gamma = float(self.gamma.get())
        coef0 = float(self.coef0.get())
        degree = int(self.degree.get())
        kernel_map = {0: "linear", 1: "rbf", 2: "poly"}
        if len(np.unique(y)) == 1:
            clf = svm.OneClassSVM(kernel=kernel_map[self.kernel.get()], gamma=gamma, coef0=coef0, degree=degree)
            clf.fit(X)
        else:
            clf = svm.SVC(kernel=kernel_map[self.kernel.get()], C=C, gamma=gamma, coef0=coef0, degree=degree)
            clf.fit(X, y)
        if hasattr(clf, "score"):
            print("Accuracy:", clf.score(X, y) * 100)
        X1, X2, Z = self.decision_surface(clf)
        self.model.clf = clf
        self.model.set_surface((X1, X2, Z))
        self.model.surface_type = self.surface_type.get()
        self.fitted = True
        self.model.changed("surface")
Example #19
0
 def subdivide_segments(s, maxlen):
     """Insert addtional points along the paths, so that
    no segment is longer than maxlen
 """
     if s.do_subdivide == False:
         return
     maxlen_sq = maxlen * maxlen
     for path_idx in range(len(s.paths)):
         path = s.paths[path_idx]
         new_path = []
         for pt in path:
             if len(new_path):
                 A = new_path[-1]
                 dist_a_pt_sq = dist_sq(s.points[A], s.points[pt])
                 if dist_a_pt_sq > maxlen_sq:
                     dist = math.sqrt(dist_a_pt_sq)
                     nsub = int(dist / maxlen)
                     seg_len = dist / float(nsub + 1)
                     dx = (s.points[pt].x - s.points[A].x) / float(nsub + 1)
                     dy = (s.points[pt].y - s.points[A].y) / float(nsub + 1)
                     if s.verbose > 1:
                         print >> sys.stderr, "pt%d -- pt%d: need nsub=%d, seg_len=%g" % (A, pt, nsub, seg_len)
                         print >> sys.stderr, "dxdy", dx, dy, "to", (s.points[pt].x, s.points[pt].y), "from", (
                             s.points[A].x,
                             s.points[A].y,
                         )
                     for subdiv in range(nsub):
                         sub_pt = s.pt2idx(s.points[A].x + dx + subdiv * dx, s.points[A].y + dy + subdiv * dy)
                         new_path.append(sub_pt)
                         s.points[sub_pt].sub = True
                         if s.verbose > 1:
                             print >> sys.stderr, "   sub", (s.points[sub_pt].x, s.points[sub_pt].y)
             new_path.append(pt)
         s.paths[path_idx] = new_path
Example #20
0
def addPointsFromSegment(pointBegin, pointEnd, points, radius, thresholdRatio=0.9):
    "Add point complexes between the endpoints of a segment."
    if radius <= 0.0:
        print("This should never happen, radius should never be zero or less in addPointsFromSegment in intercircle.")
    thresholdRadius = (
        radius * thresholdRatio
    )  # a higher number would be faster but would leave bigger dangling loops and extra dangling loops.
    thresholdDiameter = thresholdRadius + thresholdRadius
    segment = pointEnd - pointBegin
    segmentLength = abs(segment)
    extraCircles = int(math.floor(segmentLength / thresholdDiameter))
    if extraCircles < 1:
        return
    if segmentLength == 0.0:
        print("Warning, segmentLength = 0.0 in intercircle.")
        print("pointBegin")
        print(pointBegin)
        print(pointEnd)
        return
    if extraCircles < 2:
        lengthIncrement = segmentLength / (float(extraCircles) + 1.0)
        segment *= lengthIncrement / segmentLength
        pointBegin += segment
    else:
        pointBegin += segment * thresholdDiameter / segmentLength
        remainingLength = segmentLength - thresholdDiameter - thresholdDiameter
        lengthIncrement = remainingLength / (float(extraCircles) - 1.0)
        segment *= lengthIncrement / segmentLength
    for circleIndex in xrange(extraCircles):
        points.append(pointBegin)
        pointBegin += segment
Example #21
0
    def __init__(self, **argd):
        super(SimpleCube, self).__init__()

        self.size = argd.get("size", Vector(2, 2, 2))
        self.pos = argd.get("pos", Vector(0, 0, -15))
        self.rot = Vector(0.0, 0.0, 0.0)
        self.scaling = argd.get("scaling", Vector(1, 1, 1))
        self.transform = Transform()

        self.oldrot = Vector()
        self.oldpos = Vector()
        self.oldscaling = Vector()

        self.name = argd.get("name", "nameless")

        self.grabbed = 0

        # prepare vertices for intersection test
        x = float(self.size.x / 2)
        y = float(self.size.y / 2)
        z = float(self.size.z / 2)
        self.vertices = [Vector(x, 0.0, 0.0), Vector(0.0, y, 0.0), Vector(0.0, 0.0, z)]

        # similar to Pygame component registration
        self.disprequest = {
            "3DDISPLAYREQUEST": True,
            #                                          "callback" : (self,"callback"),
            "events": (self, "inbox"),
            #                                          "size": self.size,
            #                                          "pos": self.pos,
            "object": self,
        }
Example #22
0
def acc_against_hits(hit_data, control_data, assign_data, both=False):
    workers = {}
    accs = {}
    accs2 = {}
    for hit in hit_data:
        for assign in hit_data[hit]:
            worker = assign_data[assign]
            if not (worker in workers):
                workers[worker] = 0
            if not (worker in accs):
                accs[worker] = 0
                accs2[worker] = 0
            workers[worker] += 1
            tp = 0
            tp2 = 0
            t = 0
            for sent in hit_data[hit][assign]:
                t += 1
                fwd = formatworker(hit_data[hit][assign][sent])
                fcd = formatcontrol(control_data[hit][sent])
                p = grade_sent(fwd, fcd)
                tp += p
                if both:
                    p2 = grade_sent(fwd, fcd, grademode="i")
                    tp2 += p2
            accs[worker] += float(tp) / t
            if both:
                accs2[worker] += float(tp2) / t
    if both:
        return (
            [(workers[w], (accs[w] / workers[w])) for w in workers],
            [(workers[w], (accs2[w] / workers[w])) for w in workers],
        )
    return [(workers[w], (accs[w] / workers[w])) for w in workers]
def convert_to_rgb(minval, maxval, val, colors):
    max_index = len(colors) - 1
    v = float(val - minval) / float(maxval - minval) * max_index
    i1, i2 = int(v), min(int(v) + 1, max_index)
    (r1, g1, b1), (r2, g2, b2) = colors[i1], colors[i2]
    f = v - i1
    return int(r1 + f * (r2 - r1)), int(g1 + f * (g2 - g1)), int(b1 + f * (b2 - b1))
Example #24
0
def p_polyhedron_action(p):
    """polyhedron_action : polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA faces EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL
                      | polyhedron LPAREN points EQ OSQUARE points_list_3d ESQUARE COMMA triangles EQ OSQUARE points_list_3d ESQUARE COMMA keywordargument_list RPAREN SEMICOL"""
    if printverbose:
        print "Polyhedron Points"
    v = []
    for i in p[6]:
        if printverbose:
            print i
        v.append(FreeCAD.Vector(float(i[0]), float(i[1]), float(i[2])))
    if printverbose:
        print v
        print "Polyhedron triangles"
        print p[12]
    faces_list = []
    mypolyhed = doc.addObject("Part::Feature", p[1])
    for i in p[12]:
        if printverbose:
            print i
        f = make_face(v[int(i[0])], v[int(i[1])], v[int(i[2])])
        faces_list.append(f)
    shell = Part.makeShell(faces_list)
    solid = Part.Solid(shell).removeSplitter()
    if solid.Volume < 0:
        solid.reverse()
    mypolyhed.Shape = solid
    p[0] = [mypolyhed]
Example #25
0
def _dosave(request, viewName):
    profile = getProfile(request)
    # First find our View
    log.info("Saving view '%s' under profile '%s'" % (viewName, profile.user.username))
    try:
        view = profile.view_set.get(name=viewName)
    except ObjectDoesNotExist:
        view = View(profile=profile, name=viewName)
        view.save()
    # Now re-associate the view with the correct Windows
    view.window_set.all().delete()
    for windowName, encodedString in request.GET.items():
        try:
            if windowName in ("_", "commandInput"):
                continue
            paramString = urllib.unquote_plus(encodedString)
            queryParams = cgi.parse_qs(paramString)
            modelParams = {}
            for key, value in queryParams.items():  # Clean up the window params
                key = str(key)
                value = str(value[0])
                if key in ("top", "left"):
                    value = int(float(value.replace("px", "")))
                if key in ("width", "height", "interval"):
                    value = int(float(value))
                modelParams[key] = value
            if "interval" not in modelParams:
                modelParams["interval"] = None
            win = Window(view=view, name=windowName, **modelParams)
            win.save()
        except:
            log.exception("Failed to process parameters for window '%s'" % windowName)
    return stdout("Saved view %s" % viewName)
Example #26
0
 def get_content(self, url, params):
     response = requests.get(url, params=params)
     # print (url, params)
     if response.status_code == 200:
         content_json = response.content.decode()
         content_json1 = content_json.split(" ", 1)[1]
         content_json1 = content_json1[:-1]
         data = json.loads(content_json1)
         # print(data['series'])
         pre_close = 0.0
         pre_sum = 0.0
         for item in data["series"]:
             # print (item)
             # print (item['Timestamp'],item['high'],item['volume'])
             avg = (float(item["close"]) + float(item["high"]) + float(item["low"])) / 3
             if pre_close == 0.0:
                 next
             else:
                 if avg > pre_close:
                     self.up_sum += pre_sum
                     self.up += 1
                 else:
                     self.down_sum += pre_sum
                     self.down += 1
             pre_close = avg
             pre_sum = avg * float(item["volume"])
         self.sum = self.up_sum - self.down_sum
     else:
         data = 0
     return data
Example #27
0
 def __init__(self, x, y, id, value):
     self.x = self.ox = float(x)
     self.y = self.oy = float(y)
     self.id = id
     self.value = float(value)
     self.dx = 0
     self.dy = 0
Example #28
0
    def process_status_line(klass, video, line):
        error = klass._check_for_errors(line)
        if error:
            return {"finished": True, "error": error}

        match = klass.DURATION_RE.match(line)
        if match is not None:
            hours, minutes, seconds, centi = [int(m) for m in match.groups()[:4]]
            return {"duration": hms_to_seconds(hours, minutes, seconds + 0.01 * centi)}

        match = klass.FIRST_PASS.match(line)
        if match is not None:
            t = match.group(1)
            if ":" in t:
                hours, minutes, seconds = [float(m) for m in t.split(":")[:3]]
                return {"pass1": hms_to_seconds(hours, minutes, seconds)}
            else:
                return {"pass1": float(t)}

        match = klass.PROGRESS_RE.match(line)
        if match is not None:
            t = match.group(1)
            if ":" in t:
                hours, minutes, seconds = [float(m) for m in t.split(":")[:3]]
                return {"pass2": hms_to_seconds(hours, minutes, seconds)}
            else:
                return {"pass2": float(t)}

        match = klass.LAST_PROGRESS_RE.match(line)
        if match is not None:
            return {"finished": True}
Example #29
0
    def __parse_positions(self, var):
        listPattern = re.compile("\[[^\[]+?\]")
        tagPattern = re.compile("<.+?>")
        betweenTagPattern = re.compile(">(.+?)<")
        numberPattern = re.compile("-?\d+\.?\d*")
        stringPattern = re.compile('".*?[^\\\\]"')

        positions = []
        columns = ("pid", "date", "stock", "percentage", "shares", "notes")
        for text in listPattern.findall(var):
            data = stringPattern.findall(text[1:-1])
            stock = betweenTagPattern.findall(data[0])[0]
            if self.user == list_user:
                percentage = shares = "NULL"
                notes = tagPattern.sub(" ", data[-1][1:-1])
            else:
                comments = tagPattern.split(data[-1][1:-1])
                try:
                    percentage = float(numberPattern.findall(comments[0])[0])
                except:
                    percentage = 0
                try:
                    shares = float(numberPattern.findall(comments[1])[0])
                except:
                    shares = 0
                try:
                    notes = comments[2]
                except:
                    notes = ""
            positions.append(
                dict(zip(columns, (self.id, self.now, stock, percentage, shares, notes.encode("ascii", "ignore"))))
            )
        return positions
Example #30
0
 def intOrString(value):
     try:
         if int(value) == float(value):
             return int(float(value))
     except:
         pass
     return value