def getFrameTrace(self): if not self.traceLine: return None t = np.copy(self.traceLine.getData()[1]) x1, y1, x2, y2 = self.getFrameRect() x1 = max(0, round(x1)) x2 = min(round(x2), len(t)) t = t[x1:x2 + 1] return (np.arange(0, x2+1 - x1), t)
def getRecording(self): recordingArray = np.array(self.recordingList) # Time elapsed seconds = self.endRecordingTime - self.startRecordingTime # Estimate frames per second fps = len(self.recordingList) / seconds # Add recording to new window message = 'Recording (duration: ' + str(round( seconds, 2)) + ' s, fps: ' + str(round(fps, 2)) + ')' Window(recordingArray, message) self.recordingList = [] return
def import_mat(mat): if len(mat) == 0: return g.mat = mat main, reject, r = create_main_data_struct(mat, g.m.MSLDMinSpin.value(), g.m.MSLDMaxSpin.value()) g.m.trackPlot.waitForUpdate = True g.m.minLengthSpin.setValue(4) g.m.maxLengthSpin.setValue(20) g.m.MSLDMinSpin.setValue(0) g.m.MSLDMaxSpin.setValue(round(max([tr['mean_dis_pixel_lag'] for tr in main]))) g.m.neighborDistanceSpin.setValue(round(max([max(track['dis_pixel_lag']) for track in main]))) g.m.trackPlot.waitForUpdate = False g.m.trackPlot.setTracks(main)
def test_prior_mean_valid(binomp): """ * binomial: test_prior_mean_valid -- get prior mean for valid parameter. """ # almost equal assert round(binomp.prior_mean('p') - 1/2) == 0
def scale_values(numbers, num_lines=1, minimum=None, maximum=None): "Scale input numbers to appropriate range." # find min/max values, ignoring Nones filtered = [n for n in numbers if n is not None] min_ = min(filtered) if minimum is None else minimum max_ = max(filtered) if maximum is None else maximum dv = max_ - min_ # clamp numbers = [max(min(n, max_), min_) if n is not None else None for n in numbers] if dv == 0: values = [4 * num_lines if x is not None else None for x in numbers] elif dv > 0: num_blocks = len(blocks) - 1 min_index = 1. max_index = num_lines * num_blocks values = [ ((max_index - min_index) * (x - min_)) / dv + min_index if not x is None else None for x in numbers ] values = [round(v) or 1 if not v is None else None for v in values] return values
def scale_values(numbers, num_lines=1, minimum=None, maximum=None): "Scale input numbers to appropriate range." # find min/max values, ignoring Nones filtered = [n for n in numbers if n is not None] min_ = min(filtered) if minimum is None else minimum max_ = max(filtered) if maximum is None else maximum dv = max_ - min_ # clamp numbers = [ max(min(n, max_), min_) if n is not None else None for n in numbers ] if dv == 0: values = [4 * num_lines if x is not None else None for x in numbers] elif dv > 0: num_blocks = len(blocks) - 1 min_index = 1. max_index = num_lines * num_blocks values = [((max_index - min_index) * (x - min_)) / dv + min_index if not x is None else None for x in numbers] values = [round(v) or 1 if not v is None else None for v in values] return values
def scale_values(numbers, num_lines=1): "Scale input numbers to appropriate range." # find min/max values, ignoring Nones filtered = [n for n in numbers if n is not None] min_ = min(filtered) max_ = max(filtered) dv = max_ - min_ if dv == 0: values = [4 * num_lines for x in numbers] elif dv > 0: num_blocks = len(blocks) - 1 values = [ (num_blocks - 1.) / dv * x + (max_ * 1. - min_ * num_blocks) / dv if not x is None else None for x in numbers ] if num_lines > 1: m = min([n for n in values if n is not None]) values = [ _rescale(m, m, max_, num_lines * max_, v) if not v is None else None for v in values ] values = [round(v) or 1 if not v is None else None for v in values] return values
def import_mat(mat): if len(mat) == 0: return g.mat = mat main, reject, r = create_main_data_struct(mat, g.m.MSLDMinSpin.value(), g.m.MSLDMaxSpin.value()) g.m.trackPlot.waitForUpdate = True g.m.minLengthSpin.setValue(4) g.m.maxLengthSpin.setValue(20) g.m.MSLDMinSpin.setValue(0) g.m.MSLDMaxSpin.setValue( round(max([tr['mean_dis_pixel_lag'] for tr in main]))) g.m.neighborDistanceSpin.setValue( round(max([max(track['dis_pixel_lag']) for track in main]))) g.m.trackPlot.waitForUpdate = False g.m.trackPlot.setTracks(main)
def my_round(x): """ The built-in round function behaves differently in Python 2.7 and Python 3.6. We hence use this little (useless) function as the code we want the CI to test on the two major python versions and make sure our code behaves the same (thanks to the future import). :param x: a numerical value :return: the rounded value """ return round(x)
def RefreshConnectors(self): scaling = self.Parent.GetScaling() position = self.Size[1] // 2 + 1 if scaling is not None: position = round( (self.Pos.y + position) / scaling[1]) * scaling[1] - self.Pos.y self.Input.SetPosition(wx.Point(0, position)) self.Output.SetPosition(wx.Point(self.Size[0], position)) self.RefreshConnected()
def obs_count(year): """ Returns the number of observations in a given year. """ start_time = time.time() obs = sc.textFile("/user/schiefjm/weather/gsod/" + str(year)) obs = obs.filter(lambda line: "STN" not in line) the_count = obs.count() end_time = time.time() - start_time return year, the_count, round(end_time, 3)
def RefreshConnectors(self): scaling = self.Parent.GetScaling() height = self.Size[1] - self.Extensions[0] - self.Extensions[1] interval = height / max(len(self.Connectors) - 1, 1) for i, connector in enumerate(self.Connectors): if self.RealConnectors: position = self.Extensions[0] + int( round(self.RealConnectors[i] * height)) else: position = self.Extensions[0] + int(round(i * interval)) if scaling is not None: position = round((self.Pos.y + position) / scaling[1]) * scaling[1] - self.Pos.y if self.Type == LEFTRAIL: connector.SetPosition(wx.Point(self.Size[0], position)) elif self.Type == RIGHTRAIL: connector.SetPosition(wx.Point(0, position)) self.RefreshConnected()
def test_posterior_mean_valid(binomp): """ * binomial: test_posterior_mean_valid -- get posterior mean for valid parameter. """ binomp.add_data({'n': 5, 'k': 2}) # almost equal assert round(binomp.posterior_mean('p') - (1+2)/(2+5)) == 0
def test_posterior_hdcr_valid(binomp): """ * binomial: test_posterior_hdcr_valid -- get hdcr for posterior. """ binomp.add_data({'n': 5, 'k': 2}) hdcr = binomp.posterior_high_density_credible_region('p') hdcr_true = [0.10482705290430133, 0.76128981963103848] assert all(round(x-y) == 0 for x, y in zip(hdcr, hdcr_true))
def test_posterior_ccr_valid(binomp): """ * binomial: test_posterior_ccr_valid -- get ccr for posterior. """ binomp.add_data({'n': 5, 'k': 2}) ccr = binomp.posterior_central_credible_region('p') ccr_true = [0.11811724875702526, 0.77722190449648787] assert all(round(x-y) == 0 for x, y in zip(ccr, ccr_true))
def failIfAlmostEqual(self, first, second, places=7, msg=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ if round(second-first, places) == 0: raise AssertionError(msg or '%r == %r within %r places' % (first, second, places))
def _try_to_round_number(parameter_string): value_as_number = None try: value_as_number = int(parameter_string) except ValueError: pass if value_as_number is None: try: value_as_number = round(float(parameter_string), 2) except ValueError: pass return value_as_number
def ProcessDragging(self, movex, movey, event, scaling): handle_type, handle = self.Handle # A connector has been handled if handle_type == HANDLE_CONNECTOR: movey = max(-self.BoundingBox.y, movey) if scaling is not None: position = handle.GetRelPosition() movey = round( (self.Pos.y + position.y + movey) / scaling[1]) * scaling[1] - self.Pos.y - position.y self.MoveConnector(handle, movey) return 0, movey elif self.Parent.GetDrawingMode() == FREEDRAWING_MODE: return Graphic_Element.ProcessDragging(self, movex, movey, event, scaling) return 0, 0
def smooth_func(f, t, window_len=None, window='flat'): """Smooth a function f at time samples t""" if window_len is None: f_ = f(t) else: dt = t[1] - t[0] if np.sum(np.abs(np.diff(t)-dt)) > 1e-5: msg = 'samples have to be evenly spaced' raise ValueError(msg) samples = int(round(window_len / dt)) N1 = (samples - 1) // 2 N2 = samples // 2 t_ = np.hstack((t[0] - N1 * dt + np.arange(N1) * dt, t, t[-1] + dt + np.arange(N2) * dt)) f_ = f(t_) f_ = smooth(f_, samples, method=None, window=window) return f_
def smooth_func(f, t, window_len=None, window='flat'): """Smooth a function f at time samples t""" if window_len is None: f_ = f(t) else: dt = t[1] - t[0] if np.sum(np.abs(np.diff(t) - dt)) > 1e-5: msg = 'samples have to be evenly spaced' raise ValueError(msg) samples = int(round(window_len / dt)) N1 = (samples - 1) // 2 N2 = samples // 2 t_ = np.hstack((t[0] - N1 * dt + np.arange(N1) * dt, t, t[-1] + dt + np.arange(N2) * dt)) f_ = f(t_) f_ = smooth(f_, samples, method=None, window=window) return f_
def DrawHighlightment(self, dc): scalex, scaley = dc.GetUserScale() dc.SetUserScale(1, 1) dc.SetPen(MiterPen(HIGHLIGHTCOLOR, (3 * scalex + 5), wx.SOLID)) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.SetLogicalFunction(wx.AND) # Draw a two circle arcs for representing the coil dc.DrawEllipticArc( round(self.Pos.x * scalex), round((self.Pos.y - int(self.Size[1] * (sqrt(2) - 1.) / 2.) + 1) * scaley), round(self.Size[0] * scalex), round((int(self.Size[1] * sqrt(2)) - 1) * scaley), 135, 225) dc.DrawEllipticArc( round(self.Pos.x * scalex), round((self.Pos.y - int(self.Size[1] * (sqrt(2) - 1.) / 2.) + 1) * scaley), round(self.Size[0] * scalex), round((int(self.Size[1] * sqrt(2)) - 1) * scaley), -45, 45) dc.SetLogicalFunction(wx.COPY) dc.SetUserScale(scalex, scaley)
def keywords_for(*args): """ Return a list of ``Keyword`` objects for the given model instance or a model class. In the case of a model class, retrieve all keywords for all instances of the model and apply a ``weight`` attribute that can be used to create a tag cloud. """ # Handle a model instance. if isinstance(args[0], Model): obj = args[0] if hasattr(obj, "get_content_model"): obj = obj.get_content_model() or obj keywords_name = obj.get_keywordsfield_name() keywords_queryset = getattr(obj, keywords_name).all() # Keywords may have been prefetched already. If not, we # need select_related for the actual keywords. prefetched = getattr(obj, "_prefetched_objects_cache", {}) if keywords_name not in prefetched: keywords_queryset = keywords_queryset.select_related("keyword") return [assigned.keyword for assigned in keywords_queryset] # Handle a model class. try: app_label, model = args[0].split(".", 1) except ValueError: return [] content_type = ContentType.objects.get(app_label=app_label, model=model) assigned = AssignedKeyword.objects.filter(content_type=content_type) keywords = Keyword.objects.filter(assignments__in=assigned) keywords = keywords.annotate(item_count=Count("assignments")) if not keywords: return [] settings.use_editable() counts = [keyword.item_count for keyword in keywords] min_count, max_count = min(counts), max(counts) factor = (settings.TAG_CLOUD_SIZES - 1.) if min_count != max_count: factor /= (max_count - min_count) for kywd in keywords: kywd.weight = int(round((kywd.item_count - min_count) * factor)) + 1 return keywords
def main(): """ Runs the script as a stand alone application. """ global sc sc = get_sc() print(header.create_header(sc)) power = 5.6 attempts = 1 str_1 = string.digits * int(10**power) str_2 = str_1[::-1] print(len(str_1)) print("{:>10}{:>8}{:>13}{:>11}"\ .format("Attempt", "Result", "Size", "Run Time")) print(" " + "=" * 39) for i in range(attempts): start = time.time() result, size = is_anagram(str_1, str_2) print("{:>9}{:>9}{:>13}{:>11}"\ .format("{:02}".format(i + 1), "True" if result else "False", "{:,}".format(size), (str(round(time.time() - start, 2))) + "s"))
def assert_almost_equal(lval, rval, digits, message=None): """Assert that lval and rval, when rounded to the specified number of digits, are the same.""" real_message = message or "%r !~= %r" % (lval, rval) assert round(lval, digits) == round(rval, digits), real_message
def progbar(self, i, elapsed): bar = self.bar(self.percentage(i)) return "[%s] %i of %i complete in %.1f sec" % (bar, i, self.iterations, round(elapsed, 1))