def _nearest_neighbour_interpolation(image, rows, cols, r, c, mode, cval): """Nearest neighbour interpolation at a given position in the image. Parameters ---------- image : numeric array Input image. rows, cols : int Shape of image. r, c : np_float Position at which to interpolate. mode : {'C', 'W', 'S', 'E', 'R'} Wrapping mode. Constant, Wrap, Symmetric, Edge or Reflect. cval : numeric Constant value to use for constant mode. Returns ------- value : np_float Interpolated value. References: 1. https://github.com/scikit-image/scikit-image/blob/bde5a9bc3106d68ab9a4ca3dfed4f866fdd6a129/skimage/_shared/interpolation.pxd#L40 """ return _get_pixel2d(image, rows, cols, math.round(r), math.round(c), mode, cval)
def PBCDistance(u, v, box): p = u - v p.x -= math.round(p.x / box.x) * box.x p.y -= math.round(p.y / box.y) * box.y p.z -= math.round(p.z / box.z) * box.z return p.Norm
def billOfMats(self,characterObj,ME,materialMultiplier=1,implantModifier=1): materials = {} final_materials = {} #Apply ME level for mats_dict in self.base_materials: itemID = mats_dict["itemID"] base_qty = mats_dict["quantity"] if ME<0: base_qty = math.round(base_qty * (self.wasteFactor/100) * (1/(ME+1))) else: base_qty = math.round(base_qty * (self.wasteFactor/100) * (1-ME)) materials[itemID] = base_qty #add extra materials for extra_dict in self.extra_materials: itemID = extra_dict["itemID"] extra_qty = mats_dict["quantity"] if itemID in materials: materials[itemID] += extra_qty else: materials[itemID] = extra_qty #figure skill/line/implant waste for itemID,qty in materials.iteritems(): final_materials[itemID] = math.round(((25-(5 * characterObj.Production_Efficiency)) * qty) * (materialMultiplier * implantModifier)) return final_materials
def PBCDistance(u,v,box): p = u-v; p.x -= math.round(p.x/box.x)*box.x p.y -= math.round(p.y/box.y)*box.y p.z -= math.round(p.z/box.z)*box.z return p.Norm
def round(self): self.x = math.round(self.x) self.y = math.round(self.y) self.z = math.round(self.z) self.w = math.round(self.w) return self
def coords_to_square(x, y, z=0): x = coord_normalize(int(math.round(x / 4, 0))) y = coord_normalize(int(math.round(y / 4, 0))) if y <= 1: return x else: grid_y = (y - 1) * 64 return grid_y + x
def scale_list(path, factor): paths, tls, sizes = load_list(path) for i in range(len(tls)): tls[i][0] = math.round(tls[i][0] * 1.0 / factor) tls[i][1] = math.round(tls[i][1] * 1.0 / factor) for j in range(len(sizes[0])): sizes[i][j] = math.round(sizes[i][0] * 1.0 / factor) sizes[i][j] = math.round(sizes[i][1] * 1.0 / factor) save_list(paths, tls, sizes)
def forwards(self, orm): "Write your forwards methods here." # Note: Don't use "from appname.models import ModelName". # Use orm.ModelName to refer to models in this application, # and orm['appname.ModelName'] for models in other applications. for p in orm.Post.objects.all(): chars = len(striptags(p.body)) lines = p.body.count("\n") # Average reading speed of 275 wpm, 6 letters per word plus a space. p.num_read_seconds = math.round(1.0 * chars / 6 / 250 * 60) p.num_read_minutes = math.round(p.num_read_seconds / 60.0) p.save()
def draw_bounding_boxes(image, bboxes, classes, scores, class_names, colors): """ Draw the bounding boxes and their corresponding label onto the image. Args: image: A numpy array of the image bboxes: A list of tuples containing bounding box coordinates (xmin, ymin, xmax, ymax) classes: A list of class ids (labels) to decide what color the bounding box is scores: A list of confidence scores for the predictions class_names: A list of classes, strings, that represent different objects colors: A list of rgb colors for bounding boxes Returns: image: An image containing the bounding boxes and associated labels """ height, width, _ = image.shape font_face = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1 font_thickness = 2 font_color = (0, 0, 0) for idx, bbox in enumerate(bboxes): label = classes[idx] score = scores[idx] text = class_names[label] + ' ' + score color = tuple(reversed(colors[label])) # cv2 uses bgr rather than rgb # correct predicted bounding box coordinate xmin = min(0, int(math.round(bbox[0]))) ymin = min(0, int(math.round(bbox[1]))) xmax = max(height, int(math.round(bbox[2]))) ymax = max(width, int(math.round(bbox[3]))) # add bounding box cv2.rectangle(image, (xmin, ymin), (xmax, ymax), color, 5) # add label and score to top of bounding box # NOTE: may break if ymin is at top of image or xmin is at right of image label_size, _ = cv2.getTextSize(text, font_face, font_scale, font_thickness) label_xmin = xmin label_ymin = ymin - label_size[0] - 6 label_xmax = xmin + label_size[0] + 6 label_ymax = ymin cv2.rectangle(image, (label_xmin, label_ymin), (label_xmax, label_ymax), color, cv2.CV_FILLED) cv2.putText(image, text, (xmin + 3, ymin - 3), font_face, font_scale, font_color, font_thickness, cv2.LINE_AA) return image
def hex_round(h): q = int(math.round(h['q'])) r = int(math.round(h['r'])) s = int(math.round(h['s'])) q_diff = math.abs(q - h['q']) r_diff = math.abs(r - h['r']) s_diff = math.abs(s - h['s']) if q_diff > r_diff and q_diff > s_diff: q = -r - s elif r_diff > s_diff: r = -q - s else: s = -q - r return Hex(q, r, s)
def temp_effect(self): self.temperature_range_min = self.size * (-2) self.temperature_range_max = 45 - self.size * 2 if environ.location(org.current_pos ).temperature < self.temperature_range_min: org.health -= math.round( self.temperature_range_min - environ.location(org.current_pos).temperature) elif environ.location( org.current_pos ).temperature < self.temperature_range_max: org.health -= math.round( self.temperature_range_max - environ.location(org.current_pos).temperature)
def random_point_triangle(triangle, use_int_coords=True): """ Selects a random point in interior of a triangle """ xs, ys = triangle.exterior.coords.xy A, B, C = zip(xs[:-1], ys[:-1]) r1, r2 = np.random.rand(), np.random.rand() rx, ry = (1 - math.sqrt(r1)) * np.asarray(A) \ + math.sqrt(r1) * (1 - r2) * np.asarray(B) \ + math.sqrt(r1) * r2 * np.asarray(C) if use_int_coords: rx, ry = math.round(rx), math.round(ry) return Point(int(rx), int(ry)) return Point(rx, ry)
def onMove(self, context): super.onMove(context) for iterator in draggableList: draggable = iterator.next() draggable.desiredX = context.desiredDraggableX - dropTargetOffsetX + draggable.relativeX draggable.desiredY = context.desiredDraggableY - dropTargetOffsetY + draggable.relativeY draggable.desiredX = math.max( 0, math.min(draggable.desiredX, dropTargetClientWidth - draggable.offsetWidth) ) draggable.desiredY = math.max( 0, math.min(draggable.desiredY, dropTargetClientHeight - draggable.offsetHeight) ) draggable.desiredX = math.round(float(draggable.desiredX) / gridX) * gridX draggable.desiredY = math.round(float(draggable.desiredY) / gridY) * gridY dropTarget.add(draggable.positioner, draggable.desiredX, draggable.desiredY)
def in_range(self, start, stop, step=None): """ Splice samples from second based times. Parameters ---------- start : int The start time in seconds to grab samples from stop : int The end time in seconds to grab samples from step : int, optional The amount to skip, as in normal array splicing. Returns ------- np.array The spliced array """ start = int(math.floor(start * self.sampling_rate)) stop = int(math.ceil(stop * self.sampling_rate)) if step is not None: step = int(math.round(self.step * self.sampling_rate)) return self.samples[start:stop:step] else: return self.samples[start:stop]
def average_price(i, n, price): for m in range(i-1, n+1): for p in range(n-i+2): for q in range(i): sum[p]+= price[m-q] average[p]= math.round(sum[p]/i, 2) return average
def updateMap(self, obst, pos): distances, obs = obst for d in distances: #todo for o in obs: x,y = o pos_obs = round(o)
def __init__(self, start, end, minimum_overlap=0.03, minimum_overlap_fraction=0.5): start = math.round(start, 3) end = math.round(end, 3) if end < start: raise ValueError('end must be greater than start') if start < 0 or end < 0: raise ValueError('start and end must be non-negative') self.start = start self.end = end self.minimum_overlap = minimum_overlap self.minimum_overlap_fraction = minimum_overlap_fraction self._length = self.end - self.start
def shuffle_duplicate(data_dir='C:/Users/c30557/Desktop/data ready to use/',source_dir='C:/Users/c30557/Desktop/done data with labels/'): #data_dir='C:/Users/c30557/Desktop/data with labels/' os.mkdir(data_dir+'data') os.mkdir(data_dir+'data/train') os.mkdir(data_dir+'data/train/other') for dir_test in ['data_t_p','data_t_n','data_t_y','data_t_o']: os.mkdir(data_dir+dir_test) os.mkdir(data_dir+dir_test+'/test') for dir_under in ['pos','neg','yellow','other']: os.mkdir(data_dir+dir_test+'/test/'+dir_under) shutil.copytree(source_dir+r'yellow',data_dir+'data/train/yellow') shutil.copytree(source_dir+r'pos',data_dir+'data/train/pos') shutil.copytree(source_dir+r'neg',data_dir+'data/train/neg') _,_,f_y = next(os.walk(data_dir+'data/train/yellow')) ynum=len(f_y) print (ynum) _,_,f_p = next(os.walk(data_dir+'data/train/pos')) pnum=len(f_p) print (pnum) _,_,f_n = next(os.walk(data_dir+'data/train/neg')) nnum=len(f_n) print (nnum) #other too much, get from "done/other" _,_,f_other = next(os.walk(source_dir+'other')) other_num_raw=len(f_other) print (other_num_raw) testidx=np.random.permutation(other_num_raw)[0:ynum] for idx in testidx: shutil.copy(source_dir+'other/'+f_other[idx], data_dir+'data/train/other/'+f_other[idx]) for cl in ['pos','neg','yellow', 'other']: path=data_dir+'data/train/'+cl+'/' outpath=data_dir+{'pos':'data_t_p','neg':'data_t_n','yellow':'data_t_y', 'other':'data_t_o'}[cl]+'/test/'+cl+'/' f = [f for _,_,f in os.walk(path)][0] print (len(f)) # for file in f: r=0.15 testidx=np.random.permutation(len(f))[0:int(len(f)*r)] for idx in testidx: shutil.move(path+f[idx], outpath+f[idx]) for j,cl in enumerate(['pos','neg']): path=data_dir+'data/train/'+cl+'/' outpath=data_dir+'data/train/'+cl+'/' f = [f for _,_,f in os.walk(path)][0] print (len(f)) for ff in f: for i in range(math.round(ynum/[pnum,nnum][j])-1): #for i in range(1): shutil.copy(path+ff, outpath+str(i)+re.findall(r'.+(?=.txt)',ff)[0]+'.txt') print('finished!')
def round_min(x): if type(x) is str: if "." in x: x = x.strip("0") if len(x) > 8: x = mpf(x) else: x = float(x) else: try: return int(x) except ValueError: return float(x) if type(x) is int: return x if type(x) is not complex: if isfinite(x): y = math.round(x) if x == y: return int(y) return x else: if x.imag == 0: return round_min(x.real) else: return round_min( complex(x).real) + round_min(complex(x).imag) * (1j)
def getWithDefault(self, attr , attrName: str): #print(attrName+"?",attr) if isinstance(attr, dict): attr = attr.get(attrName) if (attr is None): if (attrName in self): attr = self[attrName]; else: raise Exception("Erforderliches Attribut " + attrName + " fehlt."); else: attr = re.sub(r"@([A-Z0-9_]+)", lambda match: self[match.group(1)] if match.group(1) in self else str(match), ExpandSysPara(attr),) if (attr.endswith("%")): try: deff = float(self[attrName]) at = float(attr[:-1]) attr = str(math.round(deff * at / 100)) except ValueError: pass if (attr.startswith("+") or attr.startswith("-")): if (attr.startswith("+")): attr = attr[1:] try: deff = int(self[attrName]) at = int(attr) attr = str(deff + at) except ValueError: pass #print(attrName+"=",attr) return attr
def calculator(operation=ADD, output_format=float, *args): if not args: raise ValueError("At least one number must be entered.") result = args[0] for n in args[1:]: if operation == ADD: result += n elif operation == SUB: result -= n elif operation == MUL: result *= n elif operation == DIV: result /= n else: raise ValueError("Operation must be ADD, SUB, MUL or DIV.") if output_format == float: result = float(result) elif output_format == int: result = math.round(result) else: raise ValueError("Format must be float or int.") return result
def scoreCard(username, deckName, cardName, score, user): for deck in user.decks: if (unicode(deck.userId) == unicode(deckName)): for card in deck.cards: if card.uniqueId == cardName: if score < 3 : card.eFactor = 0 card.interval = 0 else: card.eFactor = float(card.eFactor) - 0.8 + (0.28*float(score)) - (0.02*float(score)*float(score)) if card.eFactor < 1.3: card.eFactor = 1.3 interval = 1 if card.eFactor < 3: card.repetition = 1 if card.repetition == 1: card.interval = 1 elif card.repetition == 2: card.interval = 6 elif card.repetition > 2: card.interval = math.round(card.interval*card.eFactor) card.lastDone = datetime.datetime.now() print card.eFactor print card.interval card.save() user.save()
def __init__(self, h=1000, min_points=10, init_points_option=1000, weight_threshold=0.01, lembda=0.25, epsilon=0.01, mu=1, beta=0.001, p_micro_cluster=None, o_micro_cluster=None, init_buffer=None, timestamp=0, current_timestamp=0): self.h = h # horizon : Range of the window. self.min_points = min_points # Minimal number of points cluster has to contain. self.init_points_option = init_points_option # Number of points to use for initialization." self.weight_threshold = weight_threshold self.lembda = lembda # lambda is a defined structure in python, i put 'e' instead of 'a' self.epsilon = epsilon self.mu = mu self.beta = beta self.p_micro_cluster = p_micro_cluster self.o_micro_cluster = o_micro_cluster self.init_buffer = init_buffer self.timestamp = timestamp self.current_timestamp = current_timestamp self.tp = math.round(1 / self.lembda * math.log( (self.beta * self.mu) / (self.beta * self.mu - 1))) + 1
def exclude_tax_price(self, item_price: int, tax_rate: int) -> int: exclude_tax_price = item_price / (tax_rate / 100 + 1) if (self.rounding_mode == CalcPrice.ROUNDING_MODE_FLOOR): return math.floor(exclude_tax_price) elif (self.rounding_mode == CalcPrice.ROUNDING_MODE_ROUND): return math.round(exclude_tax_price) else: return math.ceil(exclude_tax_price)
def center_of(cls, data): """ This function ... :param data: :return: """ # Get the shape ny, nx = data.shape # Get center x = int(math.round((nx - 1.) / 2.)) y = int(math.round((ny - 1.) / 2.)) # Create return cls(x, y)
def __init__(self, city_id, posting_time, title, price_usd, number_of_images, review_text, attributes): self._city_id = city_id self._posting_time = posting_time self._title = title self._price_usd_cents = math.round(price_usd * 100) self._number_of_images = number_of_images self._review_text = review_text self._attributes = attributes
def get_human_readable_size(self): size = os.path.getsize(self.abs_path) idx_suffix = 0 while size > 1024 and idx_suffix < len(self.FILE_SIZE_SUFFIX): size /= 1024 idx_suffix += 1 return str(math.round(size, 2)) + self.FILE_SIZE_SUFFIX[idx_suffix]
def wait(self, sentinel=False, sleeptime=5, reporttime=None, reportcallback=None): """ Blocks script execution until all queued work completes Parameters ---------- sentinel : bool If False, it relies on the queueing system reporting to determine the number of running jobs. If True, it relies on the filesystem, in particular on the existence of a sentinel file for job completion. sleeptime : float The number of seconds to sleep before re-checking for completed jobs. reporttime : float If set to a number it will report every `reporttime` seconds the number of non-completed jobs. If this argument is larger than `sleepttime`, the method will adjust it to the closest multiple of `sleepttime`. If it is shorter than `sleepttime` it will override the `sleepttime` value. reportcallback : method If not None, the reportcallback method will receive as it's first argument the number of non-completed jobs. Examples -------- >>> self.wait() """ from time import sleep import sys if reporttime is not None: if reporttime > sleeptime: from math import round reportfrequency = round(reporttime / sleeptime) else: reportfrequency = 1 sleeptime = reporttime i = 1 while True: inprog = self.inprogress() if not sentinel else self.notcompleted() if reporttime is not None: if i == reportfrequency: if reportcallback is not None: reportcallback(inprog) else: logger.info( "{} jobs are pending completion".format(inprog)) i = 1 else: i += 1 self.retrieve() if inprog == 0: break sys.stdout.flush() sleep(sleeptime)
def __round(val): """ Round a number to the number of decimal places in `PRECISION`. :param {Number} val: The number to round. :return {Number}: The rounded value. """ root = math.pow(10, PRECISION) return math.round(val * root) / root
def distance(lat1, lng1, lat2, lng2): earth_radius = 6378137 # unit: meter radLat1 = math.radians(lat1) radLat2 = math.radians(lat2) a = radLat1 - radLat2 b = rad(lng1) - rad(lng2) s = 2 * math.asin(math.sqrt(math.pow(math.sin(a / 2), 2) + math.cos(radLat1) * math.cos(radLat2) * math.pow(math.sin(b / 2), 2))) s = s * earth_radius s = math.round(s * 100) / 100 return s
def resample(in_path, out_path, ratio, size): lines_written = 0 with open(out_path, 'wt') as f: for lines_read, bytes_read, line in get_lines(in_path): if lines_written <= ratio * lines_read: f.write(line) if lines_read % 10000 == 0 and lines_read: print ' %d %d %f %d%%' % (lines_read, lines_written, lines_written/lines_read, int(math.round(bytes_read/size * 100.0))) return lines_read, lines_written
def rand3(): tosses = map(lambda x: rand2(), [0] * 3) heads = len(filter(lambda x: x == 1, tosses)) if (heads == 0) or (heads == 3): return rand3() elif (heads == 1): for i, x in enumerate(tosses): if x == 1: return i else: # two tails (0s) for i, x in enumerate(tosses): if x == 0: return i return int(math.round(random.random()))
def change_color(node, attribute): if attribute in node.keys() and ( self.from_color is None or parse_color(node.get(attribute)) == self.from_color): node.set(attribute, str(self.to_color)) opacity_attribute = attribute + "-opacity" if self.to_color.alpha is not None and (self.from_color is None or self.from_color.alpha is None or (opacity_attribute in node.keys() and math.round(255 * float(node.get(opacity_attribute))) == self.from_color.alpha)): node.set(opacity_attribute, "{0:.6f}".format(self.to_color.alpha / 255))
def rand3(): tosses = map(lambda x: rand2(), [0] * 3) heads = len(filter(lambda x: x == 1, tosses)) if (heads == 0) or (heads == 3): return rand3() elif (heads == 1): for i,x in enumerate(tosses): if x == 1: return i else: # two tails (0s) for i,x in enumerate(tosses): if x == 0: return i return int(math.round(random.random()))
def calculate(test_hist=None, train_hists=None, train_scores=None): scores = [] for i in xrange(0,len(train_hists)): distance = dist.euclidean(train_hists[i],test_hist) if distance > 0: scores.append((dist.euclidean(train_hists[i],test_hist), train_scores[i])); sorted_scores = np.sort(scores, axis=0) total = 0 for i in xrange(0,KNN): total += sorted_scores[i][1] total /= float32(KNN) return math.round(total)
def round(num, precision): is_negative = num < 0 d = int(precision or 0) m = math.pow(10, d) n = float("{:.8f}".format((abs(num) * m) if d else abs(num))) # Avoid rounding errors i = math.floor(n) f = n - i r = (i if i % 2 == 0 else i + 1) if not precision and f == 0.5 else math.round(n) r = r / m if d else r return -r if is_negative else r
def hypo(origin, scale, loops, k) -> list: result = [] stepSize = 0.025 upperLimit = loops * math.PI steps = math.round(upperLimit / stepSize) for i in range(0, steps): x = scale * math.cos(k * i * stepSize) * math.cos( i * stepSize) + origin.x y = scale * math.cos(k * i * stepSize) * math.sin( i * stepSize) + origin.y result.append((x, y)) return result
def round(input, decimales): """Aproximación a n decimales Redondear la entrada a cierta cantidad de decimales. Args: input(Number): valor real Returns: Number """ return math.round(input, decimales)
def hello(n1, n2, n3, n4, n5): n1 = int(math.round(math.sqrt(n1))) n2 = pow(n2, n1, n3) n3 = n3 % n2 n4 = int(math.round(math.sqrt(n3 * n4))) n5 = pow(n5, n4, n3) if (n1 < 100): if (n2 < 31): if (n3 == 12): if (n4 >= 32): if (n5 <= -81): if (n1 < 50): if (n2 > 15): if (n4 < 64): if (n5 < -100): print("hi") elif (n4 < 64): if (n5 <= -81): if (n1 < 25): if (n2 > 15): if (n4 == 60): if (n5 < -120): print ("hi3") elif (n2 > 63): if (n3 == 13): if (n4 >= 33): if (n5 <= -80): if (n1 < 25): if (n2 > 14): if (n4 < 63): if (n5 < -12): print("hi2") elif (n4 < 65): if (n5 <= -79): if (n1 < 22): if (n2 > 10): if (n4 == 50): if (n5 < -90): print ("hi4")
def wait(self, sentinel=False, sleeptime=5, reporttime=None, reportcallback=None): """ Blocks script execution until all queued work completes Parameters ---------- sentinel : bool If False, it relies on the queueing system reporting to determine the number of running jobs. If True, it relies on the filesystem, in particular on the existence of a sentinel file for job completion. sleeptime : float The number of seconds to sleep before re-checking for completed jobs. reporttime : float If set to a number it will report every `reporttime` seconds the number of non-completed jobs. If this argument is larger than `sleepttime`, the method will adjust it to the closest multiple of `sleepttime`. If it is shorter than `sleepttime` it will override the `sleepttime` value. reportcallback : method If not None, the reportcallback method will receive as it's first argument the number of non-completed jobs. Examples -------- >>> self.wait() """ from time import sleep import sys if reporttime is not None: if reporttime > sleeptime: from math import round reportfrequency = round(reporttime / sleeptime) else: reportfrequency = 1 sleeptime = reporttime i = 1 while True: inprog = self.inprogress() if not sentinel else self.notcompleted() if reporttime is not None: if i == reportfrequency: if reportcallback is not None: reportcallback(inprog) else: logger.info('{} jobs are pending completion'.format(inprog)) i = 1 else: i += 1 self.retrieve() if inprog == 0: break sys.stdout.flush() sleep(sleeptime)
def billOfMats(self, characterObj, ME, materialMultiplier=1, implantModifier=1): materials = {} final_materials = {} #Apply ME level for mats_dict in self.base_materials: itemID = mats_dict["itemID"] base_qty = mats_dict["quantity"] if ME < 0: base_qty = math.round(base_qty * (self.wasteFactor / 100) * (1 / (ME + 1))) else: base_qty = math.round(base_qty * (self.wasteFactor / 100) * (1 - ME)) materials[itemID] = base_qty #add extra materials for extra_dict in self.extra_materials: itemID = extra_dict["itemID"] extra_qty = mats_dict["quantity"] if itemID in materials: materials[itemID] += extra_qty else: materials[itemID] = extra_qty #figure skill/line/implant waste for itemID, qty in materials.iteritems(): final_materials[itemID] = math.round( ((25 - (5 * characterObj.Production_Efficiency)) * qty) * (materialMultiplier * implantModifier)) return final_materials
def merge_vertices(mesh, tolerance=0): """Merges equal vertices of the mesh. If tolerance is > 0, then vertices that are within distance tolerance of one another (on all axes) are merged""" tolerance = float(tolerance) newverts = defaultdict(list) for i, v in enumerate(mesh.points): if tolerance == 0: index = tuple(v) else: index = (math.round(v[0] / (2.0 * tolerance)), math.round(v[1] / (2.0 * tolerance)), math.round(v[2] / (2.0 * tolerance))) newverts[index].append(i) newmesh = TriMesh() vertmap = dict() for (index, vlist) in newverts.iteritems(): vavg = list(mesh.points[vlist[0]]) for v in vlist[1:]: vavg[0] += mesh.points[v][0] vavg[1] += mesh.points[v][1] vavg[2] += mesh.points[v][2] if len(vlist) > 1: vavg[0] = vavg[0] / len(vlist) vavg[1] = vavg[1] / len(vlist) vavg[2] = vavg[2] / len(vlist) for v in vlist: vertmap[v] = len(newmesh.points) newmesh.points.append(vavg) for t in mesh.triangles: newt = (vertmap[t[0]], vertmap[t[1]], vertmap[t[2]]) if newt[0] == newt[1] or newt[1] == newt[2] or newt[2] == newt[0]: continue newmesh.triangles.append(newt) print "Collapsed", len(mesh.points) - len(newmesh.points), "vertices" print "Collapsed", len(mesh.triangles) - len( newmesh.triangles), "triangles" mesh.points = newmesh.points mesh.triangles = newmesh.triangles
def wrappper(*args, **kargs): offspring = func(*args, **kargs) for child in offspring: fv = fvp[0] fvi= [fv[j] for j in child[2]] dji= [dj[j] for j in child[1]] dur= [math.ceil(int(d)/float(f)) for d,f in zip (dji,fvi)] rem= T - sum(dur) - 2 tw = sum(child[0]) if ( tw > rem ): for i in range(len(child[0])): child[0][i] = math.round(child[0][i]*rem/tw) return offspring
def _fix_start_end(rec): line = str(rec) parts = line.split("\t") start = int(parts[1]) info = dict(p.split("=") for p in parts[7].split(";")) if "SVLEN" in info and abs(int(math.round(info["SVLEN"]))) > 1e7: return "" end = int(info["END"]) if end < start: info["END"] = str(start) parts[7] = ";".join(["%s=%s" % (k, v) for (k, v) in info.items()]) parts[1] = str(end) return "\t".join(parts) else: return line
def merge_vertices(mesh,tolerance=0): """Merges equal vertices of the mesh. If tolerance is > 0, then vertices that are within distance tolerance of one another (on all axes) are merged""" tolerance = float(tolerance) newverts = defaultdict(list) for i,v in enumerate(mesh.points): if tolerance == 0: index = tuple(v) else: index = (math.round(v[0]/(2.0*tolerance)),math.round(v[1]/(2.0*tolerance)),math.round(v[2]/(2.0*tolerance))) newverts[index].append(i) newmesh = TriMesh() vertmap = dict() for (index,vlist) in newverts.iteritems(): vavg = list(mesh.points[vlist[0]]) for v in vlist[1:]: vavg[0] += mesh.points[v][0] vavg[1] += mesh.points[v][1] vavg[2] += mesh.points[v][2] if len(vlist) > 1: vavg[0] = vavg[0]/len(vlist) vavg[1] = vavg[1]/len(vlist) vavg[2] = vavg[2]/len(vlist) for v in vlist: vertmap[v] = len(newmesh.points) newmesh.points.append(vavg) for t in mesh.triangles: newt = (vertmap[t[0]],vertmap[t[1]],vertmap[t[2]]) if newt[0] == newt[1] or newt[1] == newt[2] or newt[2] == newt[0]: continue newmesh.triangles.append(newt) print "Collapsed",len(mesh.points)-len(newmesh.points),"vertices" print "Collapsed",len(mesh.triangles)-len(newmesh.triangles),"triangles" mesh.points = newmesh.points mesh.triangles = newmesh.triangles
def discreteTC(s, Q, lL, K, p, lbd, h, *args, **kwargs): ''' Calculates the total cost using the discrete model. As described in [FedergruenZheng1992]_ and [Zheng1992]_. :param s: reorder point :param Q: reorder quantity :param lL: demand distribution expected value :param K: order setup cost :param p: backorder penalty :param lbd: total demand :param h: holding cost :returns: total cost :rtype: float :example: >>> round(discreteTC(50, 7, 50, 1, 25, 50, 10), 2) 95.46 >>> round(discreteTC(56, 7, 50, 1, 100, 50, 10), 2) 142.81 >>> round(discreteTC(46, 6, 50, 1, 25, 50, 25), 2) 153.35 ''' if isinstance(s, float): sround = int(round(s)) warnings.warn("s is float, converting to integer. %.2f: %d" % (s,sround)) s = sround if isinstance(Q, float): qround = int(math.round(Q)) warnings.warn("Q is float, converting to integer. %.2f: %d" % (Q,qround)) Q = qround cdf = pdcdf if 'cdf' not in kwargs.keys() else kwargs['cdf'] log.debug("Poisson cdf is: %s" % (cdf,)) setup = K * lbd / Q try: hp = sum(G(i, lL, p, h, cdf) for i in xrange(s + 1, s + Q + 1)) / Q except OverflowError: return float('nan') log.debug("Setup cost: %.2f; Holding&Stockout cost: %.2f" % (setup, hp)) return setup + hp
def __triangular(self, low, high, mode): """Triangular distribution. Continuous distribution bounded by given lower and upper limits, and having a given mode value in-between. http://en.wikipedia.org/wiki/Triangular_distribution """ u = random.random() c = (mode - low) / (high - low) if u > c: u = 1 - u c = 1 - c low, high = high, low tri = low + (high - low) * (u * c) ** 0.5 if tri < mode: return int(tri) elif tri > mode: return int(math.ceil(tri)) return int(math.round(tri))
def getTimebySec(distance) : return math.round(3600 * distance / 4)
def drop(self, widget, left, top): left = math.max(0, math.min(left, dropTarget.getOffsetWidth() - widget.getOffsetWidth())) top = math.max(0, math.min(top, dropTarget.getOffsetHeight() - widget.getOffsetHeight())) left = math.round(float(left) / gridX) * gridX top = math.round(float(top) / gridY) * gridY dropTarget.add(widget, left, top)
def __round__(self, n): return imaginary(math.round(self.real, n), math.round(self.imag, n))
import thinkplot import math import numpy %matplotlib inline zeroHighCutoff = 510 zeroLowCuttoff = 490 wave = thinkdsp.read_wave('receivedfile.wav') wave.normalize() wave.make_audio() windowSize = 0.5 results = []; for i in range(0, math.round(wave.duration / windowSize)): segment = wave.segment(i * windowSize, windowSize) segmentSpectrum = segment.make_spectrum() segmentSpectrum.low_pass(510) segmentSpectrum.high_pass(490) segmentSpectrum.apodize() if segementSpectrum[500] > .1: results[i] = 1 print(results)
def rounded(num, bins): return math.round(num*bins)/bins
def do_turn(self,target,damage): chance = base.D20.roll() if chance > 18: target.statuses.append(s.Blind(math.round(math.pow(1.1,self.level)))) target.take_damage(damage)
def round(x): return math.round(float(x))
async def spawn_single_user(self, user, server_name='', options=None): # in case of error, include 'try again from /hub/home' message spawn_start_time = time.perf_counter() self.extra_error_html = self.spawn_home_error user_server_name = user.name if server_name: user_server_name = '%s:%s' % (user.name, server_name) if server_name in user.spawners and user.spawners[server_name].pending: pending = user.spawners[server_name].pending SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.already_pending ).observe(time.perf_counter() - spawn_start_time) raise RuntimeError("%s pending %s" % (user_server_name, pending)) # count active servers and pending spawns # we could do careful bookkeeping to avoid # but for 10k users this takes ~5ms # and saves us from bookkeeping errors active_counts = self.users.count_active_users() spawn_pending_count = active_counts['spawn_pending'] + active_counts['proxy_pending'] active_count = active_counts['active'] concurrent_spawn_limit = self.concurrent_spawn_limit active_server_limit = self.active_server_limit if concurrent_spawn_limit and spawn_pending_count >= concurrent_spawn_limit: SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.throttled ).observe(time.perf_counter() - spawn_start_time) # Suggest number of seconds client should wait before retrying # This helps prevent thundering herd problems, where users simply # immediately retry when we are overloaded. retry_range = self.settings['spawn_throttle_retry_range'] retry_time = int(random.uniform(*retry_range)) # round suggestion to nicer human value (nearest 10 seconds or minute) if retry_time <= 90: # round human seconds up to nearest 10 human_retry_time = "%i0 seconds" % math.ceil(retry_time / 10.) else: # round number of minutes human_retry_time = "%i minutes" % math.round(retry_time / 60.) self.log.warning( '%s pending spawns, throttling. Suggested retry in %s seconds.', spawn_pending_count, retry_time, ) err = web.HTTPError( 429, "Too many users trying to log in right now. Try again in {}.".format(human_retry_time) ) # can't call set_header directly here because it gets ignored # when errors are raised # we handle err.headers ourselves in Handler.write_error err.headers = {'Retry-After': retry_time} raise err if active_server_limit and active_count >= active_server_limit: self.log.info( '%s servers active, no space available', active_count, ) SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.too_many_users ).observe(time.perf_counter() - spawn_start_time) raise web.HTTPError(429, "Active user limit exceeded. Try again in a few minutes.") tic = IOLoop.current().time() self.log.debug("Initiating spawn for %s", user_server_name) spawn_future = user.spawn(server_name, options) self.log.debug("%i%s concurrent spawns", spawn_pending_count, '/%i' % concurrent_spawn_limit if concurrent_spawn_limit else '') self.log.debug("%i%s active servers", active_count, '/%i' % active_server_limit if active_server_limit else '') spawner = user.spawners[server_name] # set spawn_pending now, so there's no gap where _spawn_pending is False # while we are waiting for _proxy_pending to be set spawner._spawn_pending = True async def finish_user_spawn(): """Finish the user spawn by registering listeners and notifying the proxy. If the spawner is slow to start, this is passed as an async callback, otherwise it is called immediately. """ # wait for spawn Future await spawn_future toc = IOLoop.current().time() self.log.info("User %s took %.3f seconds to start", user_server_name, toc-tic) self.statsd.timing('spawner.success', (toc - tic) * 1000) SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.success ).observe(time.perf_counter() - spawn_start_time) proxy_add_start_time = time.perf_counter() spawner._proxy_pending = True try: await self.proxy.add_user(user, server_name) PROXY_ADD_DURATION_SECONDS.labels( status='success' ).observe( time.perf_counter() - proxy_add_start_time ) except Exception: self.log.exception("Failed to add %s to proxy!", user_server_name) self.log.error("Stopping %s to avoid inconsistent state", user_server_name) await user.stop() PROXY_ADD_DURATION_SECONDS.labels( status='failure' ).observe( time.perf_counter() - proxy_add_start_time ) else: spawner.add_poll_callback(self.user_stopped, user, server_name) finally: spawner._proxy_pending = False # hook up spawner._spawn_future so that other requests can await # this result finish_spawn_future = spawner._spawn_future = maybe_future(finish_user_spawn()) def _clear_spawn_future(f): # clear spawner._spawn_future when it's done # keep an exception around, though, to prevent repeated implicit spawns # if spawn is failing if f.exception() is None: spawner._spawn_future = None # Now we're all done. clear _spawn_pending flag spawner._spawn_pending = False finish_spawn_future.add_done_callback(_clear_spawn_future) # when spawn finishes (success or failure) # update failure count and abort if consecutive failure limit # is reached def _track_failure_count(f): if f.exception() is None: # spawn succeeded, reset failure count self.settings['failure_count'] = 0 return # spawn failed, increment count and abort if limit reached self.settings.setdefault('failure_count', 0) self.settings['failure_count'] += 1 failure_count = self.settings['failure_count'] failure_limit = spawner.consecutive_failure_limit if failure_limit and 1 < failure_count < failure_limit: self.log.warning( "%i consecutive spawns failed. " "Hub will exit if failure count reaches %i before succeeding", failure_count, failure_limit, ) if failure_limit and failure_count >= failure_limit: self.log.critical( "Aborting due to %i consecutive spawn failures", failure_count ) # abort in 2 seconds to allow pending handlers to resolve # mostly propagating errors for the current failures def abort(): raise SystemExit(1) IOLoop.current().call_later(2, abort) finish_spawn_future.add_done_callback(_track_failure_count) try: await gen.with_timeout( timedelta(seconds=self.slow_spawn_timeout), finish_spawn_future ) except gen.TimeoutError: # waiting_for_response indicates server process has started, # but is yet to become responsive. if spawner._spawn_pending and not spawner._waiting_for_response: # still in Spawner.start, which is taking a long time # we shouldn't poll while spawn is incomplete. self.log.warning("User %s is slow to start (timeout=%s)", user_server_name, self.slow_spawn_timeout) return # start has finished, but the server hasn't come up # check if the server died while we were waiting status = await spawner.poll() if status is not None: toc = IOLoop.current().time() self.statsd.timing('spawner.failure', (toc - tic) * 1000) SERVER_SPAWN_DURATION_SECONDS.labels( status=ServerSpawnStatus.failure ).observe(time.perf_counter() - spawn_start_time) raise web.HTTPError(500, "Spawner failed to start [status=%s]. The logs for %s may contain details." % ( status, spawner._log_name)) if spawner._waiting_for_response: # hit timeout waiting for response, but server's running. # Hope that it'll show up soon enough, # though it's possible that it started at the wrong URL self.log.warning("User %s is slow to become responsive (timeout=%s)", user_server_name, self.slow_spawn_timeout) self.log.debug("Expecting server for %s at: %s", user_server_name, spawner.server.url) if spawner._proxy_pending: # User.spawn finished, but it hasn't been added to the proxy # Could be due to load or a slow proxy self.log.warning("User %s is slow to be added to the proxy (timeout=%s)", user_server_name, self.slow_spawn_timeout)
for line in f: #The float function apparently can't handle the small e for scientific notation line = line.replace("e","E") #Strip newline character and split line by white space line = line.strip().split() #Add "chr" back to the chromosome element and correct for R changing the chromosome to a random number. line[0] = "chr" + chrom_correct[line[0]] #Create tuple from chromosome and stop position for comparison to the bin_correct dictionary tup = (line[0], str(line[2])) #Check if the tup is in the bin_correct dictionary if tup in bin_correct: line[2] = bin_correct[tup] #Convert start, stop, peak_ID of line to ints because R output is sometimes silly and will write chromosomal positions in scientific notation for i in line[1:4]: i_index = line.index(i) line[i_index] = int(float(i)) for i in line[4:]: i_index = line.index(i) line[i_index] = round(i[, 4]) #Print results print(*line[0:], sep="\t", file=output_file) output_file.close()
def longitude_to_zone(lon): zone = int(math.round(lon / 6.0 + 30.5)) return ((zone - 1) % 60) + 1
# Instructions # Given the meal price (base cost of a meal), # tip percent (the percentage of the meal price being added as tip), # and tax percent for a meal, # find and print the meal's total cost. # Enter your code here. Read input from STDIN. Print output to STDOUT import math mealCost = float(input()) tipPercent = int(input()) taxPercent = int(input()) tipPercent = mealCost * tipPercent / 100 taxPercent = mealCost * taxPercent / 100 totalCost = mealCost + tipPercent + taxPercent totalCost = math.round(totalCost) print "The total meal cost is %d dollars." % totalCost