def middle_is_better(mult): return lambda row_index, col_index, board, my_color: \ mult * (board.game_board.board_size() * board.game_board.board_size() // 4 - abs((row_index - board.game_board.board_size() // 2) * abs(col_index - board.game_board.board_size() // 2))) \ if board.game_board.fields[row_index][col_index] == my_color \ else 0
def problem1a(m, n): """ What comes in: Integers m and n with abs(m) <= abs(n). What goes out: -- Returns the sum of the sines of the integers from m squared to n squared, inclusive, where m and n are the given arguments. Side effects: None. Examples: -- If m is 3 and n is 5, this function returns: sine(9) + sine(10) + sine(11) + ... + sine(24) + sine(25), which is about -1.601. -- If m is 1 and n is -2, this function returns: sine(1) + sine(2) + sine(3) + sine(4), which is about 1.135. -- If m is 30 and n is 100, the correct answer is about 1.278. """ # ------------------------------------------------------------------ # DONE: 4. Implement and test this function. # Note that you should write its TEST function first (above). # ------------------------------------------------------------------ # ------------------------------------------------------------------ # DIFFICULTY AND TIME RATINGS (see top of this file for explanation) # DIFFICULTY: 5 # TIME ESTIMATE: 10 minutes. # ------------------------------------------------------------------ total = 0 diff = builtins.abs(n)**2 - builtins.abs(m)**2 for k in range(diff + 1): total = total + math.sin((builtins.abs(m)**2) + k) return total
def problem2(sequence): """ What comes in: -- An non-empty sequence of integers with no duplicates. What goes out: -- Returns the index of the number in the sequence whose absolute value is largest. Side effects: None. Examples: problem2( [9, 88, 2, -1, 5, 17, 4] ) returns 1 (index of 88) problem2( [9, 13, 2, -1, 5, 17, 4] ) returns 5 (index of 17) problem2( [9, -88, 2, -1, 5, 17, 4] ) returns 1 (index of -88) problem2( [-500] ) returns 0 problem2( [1, 2, 3, 4, 5, 6, 7, -500] ) returns 7 Type hints: :type sequence [list] """ # ------------------------------------------------------------------------- # DONE: 2. Implement and test this function. # Tests have been written for you (above). # ------------------------------------------------------------------------- maximum = sequence[0] maxindex = 0 for k in range(len(sequence)): if builtins.abs(sequence[k]) > maximum: maxindex = k maximum = builtins.abs(sequence[k]) return maxindex
def corners_are_better(mult): return lambda row_index, col_index, board, my_color: \ mult * \ abs((row_index - board.game_board.board_size() // 2) * abs(col_index - board.game_board.board_size() // 2)) \ if board.game_board.fields[row_index][col_index] == my_color \ else 0
def best_length_match(ref_l, cand_l): """Find the closest length of reference to that of candidate""" least_diff = abs(cand_l-ref_l[0]) best = ref_l[0] for ref in ref_l: if abs(cand_l-ref) < least_diff: least_diff = abs(cand_l-ref) best = ref return best
def manhattanDistance(state, mazeSearchProblem): """ Returns the Manhattan distance between the state and the goal for the provided maze. The manhattan distance between points (x0,y0) and (x1,y1) is |x0-x1| + |y0-y1| """ maze = mazeSearchProblem.maze delta_x = maze.getExitCell()[0] - state[0] delta_y = maze.getExitCell()[1] - state[1] return abs(delta_x) + abs(delta_y)
def find_angle(time_in): hr, min = time_in.split(":") hr_hand_move_per_min = 360 / (12 * 60) min_hand_move_per_min = 360 / 60 position_a = (int(hr) * 60 + int(min)) * hr_hand_move_per_min position_b = int(min) * min_hand_move_per_min return abs(position_a - position_b)
def tweet_response(self, tweet): """ Update opinion rating based off opinion value of tweet and friendship value of sender. Update friendship rating based off opinion rating of tweet :param tweet: Tweet :return: None """ DEFAULT_MODIFIER = 0.001 friendship_rating = self.friendship_values.get(tweet.sender.id) # Decide whether to increase or decrease values based on tweet values. opinion_multiplier = -1 if ( friendship_rating < 0 < tweet.opinion_rating) or ( tweet.opinion_rating < 0 < friendship_rating) else 1 friendship_multiplier = -1 if ( tweet.opinion_rating < 0 < self.opinion_rating) or ( self.opinion_rating < 0 < tweet.opinion_rating) else 1 # The higher the friendship rating the greater the effect on the opinion opinion_effector = abs(friendship_rating) / 1000 # The closer the opinion ratings the bigger the effect on friendship ratings opinion_difference = abs(self.opinion_rating - tweet.opinion_rating) opinion_difference_squared = opinion_difference**2 friendship_effector_mapped = 1 - (opinion_difference_squared / 2) friendship_effector = friendship_effector_mapped / 1000 opinion_modifier = (DEFAULT_MODIFIER + opinion_effector) * opinion_multiplier friendship_modifier = (DEFAULT_MODIFIER + friendship_effector) * friendship_multiplier updated_friendship_value = limit_values(friendship_rating + friendship_modifier) updated_opinion_rating = limit_values(self.opinion_rating + opinion_modifier) self.friendship_values.update( {tweet.sender.id: updated_friendship_value}) self.opinion_rating = updated_opinion_rating
def compareFloats(valueA, valueB, tolerance=0.01): # Usage: compareFloats(valueA, valueB) (uses default tolerance of 0.01) # compareFloats(valueA, valueB, tolerance=0.001) from builtins import abs try: if (valueA == None and valueB == None): return True else: return abs(float(valueA) - float(valueB)) <= tolerance except: return False
def conv_dec_gms(self, base_coord, coord_spacing, u, neg_character, pos_character): xbase = base_coord + coord_spacing*u x = abs(xbase) xdeg = floor(round(x,4)) xmin = floor(round(((x - xdeg)*60),4)) xseg = floor(round(((x - xdeg - xmin/60)*3600),4)) if xbase < 0: xhem = neg_character else: xhem = pos_character conv_exp_str = '\'' + str(xdeg).rjust(2,'0') + 'º ' + str(xmin).rjust(2,'0') + str('\\') + str('\' ') + str(xseg).rjust(2,'0') + '"\'' + '+\' ' + str(xhem) + '\'' return conv_exp_str
def stretch(m, section, factor, preserve_length=True): if len(section) > 1: cs = np.array(list(m.coord(ident) for ident in section)) c1 = np.mean(cs.transpose(), axis=1) c0 = m.coord(section[0]) direction = c1 - c0 #direction /= np.linalg.norm(direction) direction /= _norm(direction) direction *= abs(factor) for ident in section[1:]: parent = m.parent(ident) v = m.coord(ident) - m.coord(parent) #vnorm = np.linalg.norm(v) vnorm = _norm(v) vnew = v + direction * vnorm if preserve_length: vleng = np.linalg.norm(vnew) if vleng > 1e-6: vnew /= vleng vnew *= vnorm m.translate(vnew - v, ident=ident)
def ks_func(predictions, y, probability): decileDF = predictions.select(y, probability) decileDF = decileDF.withColumn('non_target', 1 - decileDF[y]) window = Window.orderBy(desc(probability)) decileDF = decileDF.withColumn("rownum", F.row_number().over(window)) decileDF.cache() decileDF = decileDF.withColumn("rownum", decileDF["rownum"].cast("double")) window2 = Window.orderBy("rownum") RFbucketedData = decileDF.withColumn("deciles", F.ntile(10).over(window2)) RFbucketedData = RFbucketedData.withColumn( 'deciles', RFbucketedData['deciles'].cast("int")) RFbucketedData.cache() ## to pandas from here print('KS calculation starting') target_cnt = RFbucketedData.groupBy('deciles').agg( F.sum(y).alias('target')).toPandas() non_target_cnt = RFbucketedData.groupBy('deciles').agg( F.sum("non_target").alias('non_target')).toPandas() overall_cnt = RFbucketedData.groupBy('deciles').count().alias( 'Total').toPandas() overall_cnt = overall_cnt.merge(target_cnt, on='deciles', how='inner').merge(non_target_cnt, on='deciles', how='inner') overall_cnt = overall_cnt.sort_values(by='deciles', ascending=True) overall_cnt['Pct_target'] = (overall_cnt['target'] / overall_cnt['count']) * 100 overall_cnt['cum_target'] = overall_cnt.target.cumsum() overall_cnt['cum_non_target'] = overall_cnt.non_target.cumsum() overall_cnt['%Dist_Target'] = (overall_cnt['cum_target'] / overall_cnt.target.sum()) * 100 overall_cnt['%Dist_non_Target'] = (overall_cnt['cum_non_target'] / overall_cnt.non_target.sum()) * 100 overall_cnt['spread'] = builtins.abs(overall_cnt['%Dist_Target'] - overall_cnt['%Dist_non_Target']) decile_table = overall_cnt.round(2) print("KS_Value =", builtins.round(overall_cnt.spread.max(), 2)) decileDF.unpersist() RFbucketedData.unpersist() return builtins.round(overall_cnt.spread.max(), 2), overall_cnt
def find_time(time_in: str): # time hour and min as an input # split 360/12 degree = 30 deg # Angle for each min = 30/5 = 6 deg # find angle between 2 numbers # position of Hr hand # position of min hand # angle = position A - Position B hr, min = time_in.split(":") # print(hr, min) angle_for_hr_hand = 360 // 12 angle_for_min_hand = angle_for_hr_hand // 5 extra_angle_for_hr_hand = angle_for_min_hand / (5 * 5) # 4 * 30 = 120, 30 deg between 2 hrs, 6 deg between 2 mins position_a = angle_for_hr_hand * int(hr) + (int(min) * extra_angle_for_hr_hand) # 28 min = 5 * 30 + 4 * 6 position_b = (int(min) // 5 * angle_for_hr_hand) + (int(min) % 5) * angle_for_min_hand return abs(position_a - position_b)
def _range_shift(range, distance, gap): '''Perform the desired shift on the range - adjusting either the top or the bottom or both :param range: tuple (bottom, top) of current values to shift :param distance: how far to shift (positive causes the bottom to shift up, negative shifts the top down) :param gap: minimum gap between top and bottom to maintain :return: tuple (bottom, top) after shifting >>> _range_shift((68, 70), 2, 4) (70, 74) >>> _range_shift((68, 70), -2, 4) (64, 68) ''' if distance > 0: bottom = min((range[0] + distance), config.max) # go up distance, but don't cross 80 top = max( range[1], bottom + gap ) # keep the top unless needing to shift up to keep {gap} degree distance else: top = max(range[1] - abs(distance), config.min) bottom = min(range[0], top - gap) return bottom, top
def conv_dec_gms(self, base_coord, u, neg_character, pos_character, extentsGeo, isVertical, geo_number_x, geo_number_y): if not isVertical: coord_spacing = (round(extentsGeo[3], 6) - round(extentsGeo[1], 6)) / (geo_number_y + 1) else: coord_spacing = (round(extentsGeo[2], 6) - round(extentsGeo[0], 6)) / (geo_number_x + 1) xbase = base_coord + coord_spacing * u x = round(abs(xbase), 6) xdeg = int(x) xmin = int((round((x - xdeg), 6) * 60)) xseg = round((round((x - xdeg - round((xmin / 60), 6)), 6)) * 3600) if xbase < 0: xhem = neg_character else: xhem = pos_character conv_exp_str = u"'{}º {}\\' {}\" {}'".format( str(xdeg).rjust(2, '0'), str(xmin).rjust(2, '0'), str(xseg).rjust(2, '0'), xhem) return conv_exp_str
def test_abs(self): # int self.assertEqual(abs(0), builtins.abs(0)) self.assertEqual(abs(1234), builtins.abs(1234)) self.assertEqual(abs(-1234), builtins.abs(1234)) self.assertTrue(abs(-sys.maxsize-1) > 0) # float self.assertEqual(abs(0.0), builtins.abs(0.0)) self.assertEqual(abs(3.14), builtins.abs(3.14)) self.assertEqual(abs(-3.14), builtins.abs(3.14)) # str self.assertRaises(TypeError, abs, 'a') # bool self.assertEqual(abs(True), 1) self.assertEqual(abs(False), 0) # other self.assertRaises(TypeError, abs) self.assertRaises(TypeError, abs, None)
def utm_grid_labeler(self, root_rule, x_UTM, y_UTM, x_geo, y_geo, x_min, y_min, px, py, trUTMLL, trLLUTM, u, isVertical, dx, dy, dyO, dy1, desc, fSize, fontType, grid_spacing, scale, rangetest, geo_bb_or, layer_bound): x_colec = [float(geo_bb_or.split()[2 * i]) for i in range(1, 5)] x_colec.sort() y_colec = [float(geo_bb_or.split()[2 * i + 1]) for i in range(1, 5)] y_colec.sort() ang = float(geo_bb_or.split()[13]) if ang > 0: if 'Bot' in desc: x_min_test = x_colec[0] x_max_test = x_colec[2] elif 'Up' in desc: x_min_test = x_colec[1] x_max_test = x_colec[3] elif 'Left' in desc: y_min_test = y_colec[1] y_max_test = y_colec[3] elif 'Right' in desc: y_min_test = y_colec[0] y_max_test = y_colec[2] elif ang <= 0: if 'Bot' in desc: x_min_test = x_colec[1] x_max_test = x_colec[3] elif 'Up' in desc: x_min_test = x_colec[0] x_max_test = x_colec[2] elif 'Left' in desc: y_min_test = y_colec[0] y_max_test = y_colec[2] elif 'Right' in desc: y_min_test = y_colec[1] y_max_test = y_colec[3] # Check if is labeling grid's vertical lines if isVertical: # Displacing UTM Label that overlaps Geo Label dx0 = 0 test_plac = QgsPoint( ((floor(x_UTM / grid_spacing) + u) * grid_spacing), y_UTM) test_plac.transform(trUTMLL) ancX = QgsPoint( ((floor(x_UTM / grid_spacing) + u) * grid_spacing) + dx, y_UTM) ancX.transform(trUTMLL) ancY = QgsPoint(ancX.x(), y_geo) ancY.transform(trLLUTM) test = QgsPoint(((floor(x_UTM / grid_spacing) + u) * grid_spacing), y_UTM) test.transform(trUTMLL) if u == 1 and 'Up' in desc: deltaDneg = 0.0022 deltaDpos = 0.0011 elif u == 1 and 'Bot' in desc: deltaDneg = 0.0011 deltaDpos = 0.0011 else: deltaDneg = 0.0009 deltaDpos = 0.0009 testif = abs( floor( abs( round(test.x(), 4) - (x_min % (px)) - (deltaDneg * (fSize / 1.5) * scale / 10)) / px) - floor( abs( round(test.x(), 4) - (x_min % (px)) + (deltaDpos * (fSize / 1.5) * scale / 10)) / px)) if testif >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dyO) else: ancY = QgsPoint(ancY.x(), ancY.y() + dy) x = ancX.x() + dx0 ancY.transform(trUTMLL) y = ancY.y() full_label = str((floor(x_UTM / grid_spacing) + u) * grid_spacing) if test_plac.x() < (x_min_test) or test_plac.x() > (x_max_test): rule_fake = self.grid_labeler(x, y, 0, 0, 0, 0, 0, 0, desc, fSize, fontType, 'fail', trLLUTM, QColor('black'), layer_bound, trUTMLL) root_rule.appendChild(rule_fake) return root_rule # Labeling grid's horizontal lines else: test_plac = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) test_plac.transform(trUTMLL) ancX = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) ancX.transform(trUTMLL) ancX = QgsPoint(x_geo, ancX.y()) ancY = QgsPoint(x_geo, ancX.y()) ancY.transform(trLLUTM) test = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) test.transform(trUTMLL) testif = abs( floor( abs( round(test.y(), 4) - (y_min % (py)) - (0.0004 * (fSize / 1.5) * scale / 10)) / py) - floor(abs(round(test.y(), 4) - (y_min % (py))) / py)) if testif >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dy1) else: testif2 = abs( floor(abs(round(test.y(), 4) - (y_min % (py))) / py) - floor( abs( round(test.y(), 4) - (y_min % (py)) + (0.0004 * (fSize / 1.5) * scale / 10)) / py)) if testif2 >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dyO) else: ancY = QgsPoint(ancY.x(), ancY.y() + dy) dx0 = 0 ancX.transform(trLLUTM) ancX = QgsPoint(ancX.x() + dx, ancX.y()) ancX.transform(trUTMLL) ancY.transform(trUTMLL) x = ancX.x() + dx0 y = ancY.y() full_label = str((floor(y_UTM / grid_spacing) + u) * grid_spacing) if test_plac.y() < (y_min_test) or test_plac.y() > (y_max_test): rule_fake = self.grid_labeler(x, y, 0, 0, 0, 0, 0, 0, desc, fSize, fontType, 'fail', trLLUTM, QColor('black'), layer_bound, trUTMLL) root_rule.appendChild(rule_fake) return root_rule ctrl_uni = { 0: u'\u2070', 1: u'\u00B9', 2: u'\u00B2', 3: u'\u00B3', 4: u'\u2074', 5: u'\u2075', 6: u'\u2076', 7: u'\u2077', 8: u'\u2078', 9: u'\u2079' } if not (full_label == '0'): full_label = [char for char in full_label] for j in range(0, len(full_label)): if not (j == len(full_label) - 5 or j == len(full_label) - 4): full_label[j] = ctrl_uni[int(full_label[j])] full_label = ''.join(full_label) expression_str = str('\'') + full_label + str('\'') fontType.setWeight(50) fSizeAlt = fSize * 5 / 3 plac = QgsPoint(x, y) plac.transform(trLLUTM) if u == min(rangetest) and any(spec_lbl in desc for spec_lbl in ('Bot', 'Left')): extra_label = 'N' dyT = 1.4 * scale * fSize / 1.5 dxT = 7.1 * scale * fSize / 1.5 dxH = 8.1 * scale * fSize / 1.5 if isVertical: extra_label = 'E' dyT = 1.6 * scale * fSize / 1.5 dxT = 7.0 * scale * fSize / 1.5 dxH = 7.9 * scale * fSize / 1.5 plac_new = QgsPoint(plac.x() + dxT, plac.y() + dyT) plac_new.transform(trUTMLL) plac_hem = QgsPoint(plac.x() + dxH, plac.y()) plac_hem.transform(trUTMLL) ruleUTM2 = self.grid_labeler(plac_new.x(), plac_new.y(), 0, 0, 0, 0, 0, 0, desc + 'm', fSize * 4 / 5, fontType, str('\'m\''), trLLUTM, QColor('black'), layer_bound, trUTMLL) root_rule.appendChild(ruleUTM2) ruleUTM3 = self.grid_labeler(plac_hem.x(), plac_hem.y(), 0, 0, 0, 0, 0, 0, desc + ' ' + extra_label, fSizeAlt, fontType, '\'' + extra_label + '\'', trLLUTM, QColor('black'), layer_bound, trUTMLL) root_rule.appendChild(ruleUTM3) dxS = 0 if any(spec_lbl in desc for spec_lbl in ('Bot', 'Left', 'Up')): if len(expression_str) == 3: dxS = 5.4 * scale * fSize / 1.5 elif len(expression_str) == 6: dxS = 3.2 * scale * fSize / 1.5 elif len(expression_str) == 7: dxS = 1.6 * scale * fSize / 1.5 elif len(expression_str) == 8: dxS = 0.7 * scale * fSize / 1.5 plac_size = QgsPoint(plac.x() + dxS, plac.y()) plac_size.transform(trUTMLL) ruleUTM = self.grid_labeler(plac_size.x(), plac_size.y(), 0, 0, 0, 0, 0, 0, desc, fSizeAlt, fontType, expression_str, trLLUTM, QColor('black'), layer_bound, trUTMLL) root_rule.appendChild(ruleUTM) return root_rule
def abs(x): '''Replacement for the built-in :func:`abs() <python:abs>` function.''' return builtins.abs(x)
def i(*a, **k): if random() < p: return g(*a, **k) return f(*a, **k) return i int = r(_.int, lambda *a: _.int(*a) - 1) float = r(_.float, lambda v: _.float(v) + 0.001) str = r(_.str, lambda *a, **k: _.str(*a, **k)[::-1]) bool = r(_.bool, lambda v: not (_.bool(v))) len = r(_.len, lambda v: _.len(v) - 1) ord = r(_.ord, lambda v: _.ord(v.lower() if v.isupper() else v.upper())) abs = r(_.abs, lambda v: -_.abs(v)) pow = r(_.pow, lambda v, p, *a: _.pow(v, p + 1, *a)) min = r(_.min, lambda *a: _.max(*a)) max = r(_.max, lambda *a: _.min(*a)) sum = r(_.sum, lambda v, *a: reduce(op.__sub__, v)) hasattr = r(_.hasattr, lambda o, n: not (_.hasattr(o, n))) sorted = r(_.sorted, lambda *a, **k: list(_.reversed(*a, **k))) reversed = r(_.reversed, lambda v: _.sorted(v)) enumerate = r(_.enumerate, lambda v, *a: ((i + 1, _v) for i, _v in _.enumerate(v, *a))) globals = r(_.globals, locals) locals = r(_.locals, _.globals) id = r(_.id, lambda v: _.id(_.id))
"""Implicit lambda wrappers around all Python builtins functions.""" import builtins import functools from implicit_lambda import wrap, to_lambda from implicit_lambda import args_resolver abs = functools.update_wrapper( lambda *args, **kwargs: builtins.abs(*args, **kwargs), builtins.abs) abs._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.abs)(*args, **kwargs), builtins.abs) all = functools.update_wrapper( lambda *args, **kwargs: builtins.all(*args, **kwargs), builtins.all) all._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.all)(*args, **kwargs), builtins.all) any = functools.update_wrapper( lambda *args, **kwargs: builtins.any(*args, **kwargs), builtins.any) any._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.any)(*args, **kwargs), builtins.any) ascii = functools.update_wrapper( lambda *args, **kwargs: builtins.ascii(*args, **kwargs), builtins.ascii) ascii._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.ascii)(*args, **kwargs), builtins.ascii) bin = functools.update_wrapper( lambda *args, **kwargs: builtins.bin(*args, **kwargs), builtins.bin) bin._ = functools.update_wrapper( lambda *args, **kwargs: wrap(builtins.bin)(*args, **kwargs), builtins.bin) bool = functools.update_wrapper( lambda *args, **kwargs: builtins.bool(*args, **kwargs), builtins.bool) bool._ = functools.update_wrapper(
def abs(iterable): return (builtins.abs(x) for x in iterable)
def __str__(self): return "The absolute value of {} is {}".format(self.num, abs(self.num))
def abs(anObject): return builtins.abs(evaluate(anObject))
def utm_grid_labeler(self, root_rule, x_UTM, y_UTM, x_geo, y_geo, px, py, trUTMLL, trLLUTM, u, isVertical, dx, dy, dyO, dy1, vAlign, hAlign, desc, fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangetest, geo_bb_or): x_colec = [float(geo_bb_or.split()[2 * i]) for i in range(1, 5)] x_colec.sort() y_colec = [float(geo_bb_or.split()[2 * i + 1]) for i in range(1, 5)] y_colec.sort() ang = float(geo_bb_or.split()[13]) if ang > 0: if 'Bot' in desc: x_min_test = x_colec[0] x_max_test = x_colec[2] elif 'Up' in desc: x_min_test = x_colec[1] x_max_test = x_colec[3] elif 'Left' in desc: y_min_test = y_colec[1] y_max_test = y_colec[3] elif 'Right' in desc: y_min_test = y_colec[0] y_max_test = y_colec[2] elif ang <= 0: if 'Bot' in desc: x_min_test = x_colec[1] x_max_test = x_colec[3] elif 'Up' in desc: x_min_test = x_colec[0] x_max_test = x_colec[2] elif 'Left' in desc: y_min_test = y_colec[0] y_max_test = y_colec[2] elif 'Right' in desc: y_min_test = y_colec[1] y_max_test = y_colec[3] x_min = float(geo_bound_bb.split()[1]) y_min = float(geo_bound_bb.split()[2]) x_max = float(geo_bound_bb.split()[3]) y_max = float(geo_bound_bb.split()[4]) # Check if is labeling grid's vertical lines if isVertical: # Displacing UTM Label that overlaps Geo Label if utmcheck: dx0 = 0 else: dx0 = dx dx = 0 test_plac = QgsPoint( ((floor(x_UTM / grid_spacing) + u) * grid_spacing), y_UTM) test_plac.transform(trUTMLL) ancX = QgsPoint( ((floor(x_UTM / grid_spacing) + u) * grid_spacing) + dx, y_UTM) ancX.transform(trUTMLL) ancY = QgsPoint(ancX.x(), y_geo) if utmcheck: ancY.transform(trLLUTM) test = QgsPoint(((floor(x_UTM / grid_spacing) + u) * grid_spacing), y_UTM) test.transform(trUTMLL) if u == 1 and 'Up' in desc: deltaDneg = 0.0022 deltaDpos = 0.0011 elif u == 1 and 'Bot' in desc: deltaDneg = 0.00125 deltaDpos = 0.0011 else: deltaDneg = 0.00095 deltaDpos = 0.0011 testif = abs( floor( abs( round(test.x(), 4) - (x_min % (px)) - (deltaDneg * (fSize / 1.5) * scale / 10)) / px) - floor( abs( round(test.x(), 4) - (x_min % (px)) + (deltaDpos * (fSize / 1.5) * scale / 10)) / px)) if testif >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dyO) else: ancY = QgsPoint(ancY.x(), ancY.y() + dy) x = ancX.x() + dx0 if utmcheck: ancY.transform(trUTMLL) y = ancY.y() full_label = str((floor(x_UTM / grid_spacing) + u) * grid_spacing) if test_plac.x() < (x_min_test + (0.0005 * scale / 10)) or test_plac.x() > ( x_max_test - (0.0005 * scale / 10)): rule_fake = self.grid_labeler(x, y, 0, 0, 0, 0, 0, 0, vAlign, hAlign, desc, fSize, fontType, 'fail', trLLUTM, trUTMLL, QColor('black'), utmcheck, scale) root_rule.appendChild(rule_fake) return root_rule # Labeling grid's horizontal lines else: test_plac = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) test_plac.transform(trUTMLL) ancX = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) ancX.transform(trUTMLL) ancX = QgsPoint(x_geo, ancX.y()) ancY = QgsPoint(x_geo, ancX.y()) if utmcheck: ancY.transform(trLLUTM) # Displacing UTM Label it overlaps with Geo Label test = QgsPoint(x_UTM, (floor(y_UTM / grid_spacing) + u) * grid_spacing) test.transform(trUTMLL) testif = abs( floor( abs( round(test.y(), 4) - (y_min % (py)) - (0.0004 * (fSize / 1.5) * scale / 10)) / py) - floor(abs(round(test.y(), 4) - (y_min % (py))) / py)) if testif >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dy1) else: testif2 = abs( floor(abs(round(test.y(), 4) - (y_min % (py))) / py) - floor( abs( round(test.y(), 4) - (y_min % (py)) + (0.0004 * (fSize / 1.5) * scale / 10)) / py)) if testif2 >= 1: ancY = QgsPoint(ancY.x(), ancY.y() + dyO) else: ancY = QgsPoint(ancY.x(), ancY.y() + dy) if utmcheck: dx0 = 0 ancX.transform(trLLUTM) ancX = QgsPoint(ancX.x() + dx, ancX.y()) ancX.transform(trUTMLL) ancY.transform(trUTMLL) else: dx0 = dx x = ancX.x() + dx0 y = ancY.y() full_label = str((floor(y_UTM / grid_spacing) + u) * grid_spacing) if test_plac.y() < (y_min_test + (0.0002 * scale / 10)) or test_plac.y() > ( y_max_test - (0.0002 * scale / 10)): rule_fake = self.grid_labeler(x, y, 0, 0, 0, 0, 0, 0, vAlign, hAlign, desc, fSize, fontType, 'fail', trLLUTM, trUTMLL, QColor('black'), utmcheck, scale) root_rule.appendChild(rule_fake) return root_rule ctrl_uni = { 0: u'\u2070', 1: u'\u00B9', 2: u'\u00B2', 3: u'\u00B3', 4: u'\u2074', 5: u'\u2075', 6: u'\u2076', 7: u'\u2077', 8: u'\u2078', 9: u'\u2079', 'm': u'\u1D50' } full_label = [char for char in full_label] for j in range(0, len(full_label)): if not (j == len(full_label) - 5 or j == len(full_label) - 4): full_label[j] = ctrl_uni[int(full_label[j])] full_label = ''.join(full_label) expression_str = str('\'') + full_label + str('\'') fontType.setWeight(50) fSizeAlt = fSize * 5 / 3 if u == min(rangetest) and any(spec_lbl in desc for spec_lbl in ('Bot', 'Left')): extra_label = ' ' + 'N' dyT = 0.5 * scale * fSize / 1.5 if len(expression_str) == 9: dxT = 3.5 * scale * fSize / 1.5 elif len(expression_str) == 6: dxT = 1.5 * scale * fSize / 1.5 elif len(expression_str) == 7: dxT = 2.5 * scale * fSize / 1.5 if isVertical: extra_label = ' ' + 'E' dyT = 0.5 * scale * fSize / 1.5 dxT = 3.0 * scale * fSize / 1.5 expression_str = str('\'') + full_label + extra_label + str('\'') plac_m = QgsPoint(x, y) plac_m.transform(trLLUTM) plac_new = QgsPoint(plac_m.x() + dxT, plac_m.y() + dyT) plac_new.transform(trUTMLL) ruleUTM2 = self.grid_labeler(plac_new.x(), plac_new.y(), 0, 0, 0, 0, 0, 0, vAlign, 'Center', desc + 'm', fSizeAlt, fontType, str('\'') + ctrl_uni['m'] + str('\''), trLLUTM, trUTMLL, QColor('black'), utmcheck, scale) root_rule.appendChild(ruleUTM2) ruleUTM = self.grid_labeler(x, y, 0, 0, 0, 0, 0, 0, vAlign, hAlign, desc, fSizeAlt, fontType, expression_str, trLLUTM, trUTMLL, QColor('black'), utmcheck, scale) root_rule.appendChild(ruleUTM) return root_rule
def abs(x): return builtins.abs(x)
return g(*args, **kwargs) else: return f(*args, **kwargs) return inner int = rroulette(_.int, lambda v: _.int(v) - 1) float = rroulette(_.float, lambda v: _.float(v) + 0.001) str = rroulette(_.str, lambda v: _.str(v)[::-1]) bool = rroulette(_.bool, lambda v: not (_.bool(v))) len = rroulette(_.len, lambda v: _.len(v) - 1) ord = rroulette(_.ord, lambda v: _.ord(v.lower() if v.isupper() else v.upper())) abs = rroulette(_.abs, lambda v: -_.abs(v)) pow = rroulette(_.pow, lambda v, p: _.pow(v, p + 1)) min = rroulette(_.min, lambda *v: _.max(*v)) max = rroulette(_.max, lambda *v: _.min(*v)) sum = rroulette(_.sum, lambda v: reduce(op.__sub__, v)) hasattr = rroulette(_.hasattr, lambda o, n: not (_.hasattr(o, n))) sorted = rroulette(_.sorted, lambda v: _.reversed(v)) reversed = rroulette(_.reversed, lambda v: _.sorted(v)) enumerate = rroulette(_.enumerate, lambda v: ((i + 1, _v) for i, _v in _.enumerate(v))) globals = rroulette(_.globals, locals) locals = rroulette(_.locals, _.globals) id = rroulette(_.id, lambda v: _.id(_.id))
### higher-order function ### f = abs print(f(-10)) abs(-1) print(abs) abs = 1 print(abs) del abs print(abs) import builtins builtins.abs(-1) print(builtins.abs) # builtins.abs = 10 # print(builtins.abs) # # del builtins.abs # print(builtins.abs) ### map and reduce ### L = ['apple', 'orange', 'banana'] print(L) print(list(L)) print(list(list(L))) def char2int(c): return ord(c)-48
def optimize(x_start, rho, txf, cdprate, w, eth_price, dai_price, debug=True): # Compute asset worth given ETH Price asset_prices = np.array([1, eth_price, dai_price, eth_price]) assets_dollars = np.multiply(x_start, asset_prices) money = np.sum(assets_dollars) # Initial dollar worth xo = Parameter(4, nonneg=True) xo.value = assets_dollars mu, cor, d = get_optimization_params() # Covariance Matrix cvr = (d.dot(cor)).dot(d) x = Variable(5) eth = x[1] dai1 = x[2] ceth = x[3] dai2 = x[4] # include cost of buying ceth as well # modified transaction fees tx_fee = cvxpy.abs(x[1] - xo[1] + x[3] - xo[3]) * txf + cvxpy.abs(x[2] - xo[2]) * txf # objective function objective = Maximize(mu.T @ x - w * quad_form(x, cvr) - cdprate * ceth - tx_fee) # Figure out how to use abs as a constraint for Maximize constraints = [ x[0] + x[1] + x[2] + x[3] == money, x >= 0, x[4] == x[3] / rho, x[0] >= tx_fee ] prob = Problem(objective, constraints) prob.solve(solver=OSQP) if prob.status != "optimal": print("Not optimal!") x_temp = [i for i in x_start] return x_temp optimal_assets_in_dollars = [float(i) for i in x.value] transaction_fees = abs(optimal_assets_in_dollars[1] - xo.value[1] + optimal_assets_in_dollars[3] - xo.value[3] ) * txf + abs(optimal_assets_in_dollars[2] - xo.value[2]) * txf optimal_assets_in_dollars[0] -= transaction_fees if debug: print("------------------- Iteration ----------------------------") print("CDP Rate: " + str(cdprate) + "\nRisk Averseness: " + str(w)) print("TxFees: $%.2f" % transaction_fees) assets_dollars = optimal_assets_in_dollars[:-1] x_temp = np.divide(assets_dollars, asset_prices).clip(min=0) if debug: printAssets(x_temp, eth_price, dai_price, rho) print("--------------------- Ends -------------------------------") return x_temp
def meter(m, ident=None, features=[]): root = m.root() ident = ident if ident is not None else root if not features: features = std_features c0 = m.coord(root) nodes = dict() tips = list() bifs = list() secs = list() part = list() asym = list() diam = list() angle = list() cmin = np.finfo(1.0).max * np.ones(3) cmax = np.finfo(1.0).min * np.ones(3) rmax = 0.0 seclen = 0.0 npoints = 0 c1 = m.coord(ident) # if _contains(features, [ 'width', 'height', 'depth', 'dist', 'path', 'order', 'seclen', 'tort', 'nbifs', 'nsecs', 'npoints', 'diam' ]): for item in m.traverse(ident): if _contains(features, ['npoints']): npoints += 1 if _contains(features, ['diam']): diam.append(m.diam(item)) c = m.coord(item) if _contains(features, ['width', 'height', 'depth']): cmin = np.minimum(c, cmin) cmax = np.maximum(c, cmax) if _contains(features, ['dist']): r = _norm(c - c0) rmax = max(r, rmax) nodes[item] = dict() parent = m.parent(item) if parent in nodes: seglen = m.length(item) if _contains(features, ['order']): order = nodes[parent]['order'] if _contains(features, ['path']): path = nodes[parent]['path'] + seglen seclen += seglen else: if _contains(features, ['path']): path = m.distance(item) if _contains(features, ['order']): order = m.order(item) if _contains(features, ['path']): nodes[item]['path'] = path if m.is_bifurcation(item): bifs.append(item) if _contains(features, ['order']): order = order + 1 if parent in nodes else order if c1 is None: c1 = m.coord(parent) if m.is_bifurcation(item) or m.is_leaf(item): if _contains(features, ['seclen', 'tort', 'nsecs']): chord = _norm(c - c1) if seclen == 0.0: seclen = m.length(item) secs.append(dict(length=seclen, tort=chord / seclen)) seclen = 0.0 c1 = None if _contains(features, ['order']): nodes[item]['order'] = order if m.is_leaf(item): tips.append(item) # if _contains(features, ['length', 'volume', 'area', 'degree', 'part', 'asym']): if not tips: tips = list(m.leaves(ident)) for item in m.traverse(ident): nodes[item] = dict() for tip in tips: for item in m.traverse(tip, reverse=True): if not m.children(item): if _contains(features, ['length', 'asym']): nodes[item]['length'] = 0.0 if _contains(features, ['volume']): nodes[item]['volume'] = 0.0 if _contains(features, ['area']): nodes[item]['area'] = 0.0 if _contains(features, ['degree', 'part']): nodes[item]['degree'] = 1 else: degree = 0 length = 0.0 volume = 0.0 area = 0.0 for child in m.children(item): if 'length' in nodes[child]: if _contains(features, ['length', 'asym']): length += nodes[child]['length'] if 'volume' in nodes[child]: if _contains(features, ['volume']): volume += nodes[child]['volume'] if 'area' in nodes[child]: if _contains(features, ['area']): area += nodes[child]['area'] if 'degree' in nodes[child]: if _contains(features, ['degree', 'part']): degree += nodes[child]['degree'] if _contains(features, ['length', 'asym']): length += m.length(child) if _contains(features, ['volume']): volume += m.volume(child) if _contains(features, ['area']): area += m.area(child) if _contains(features, ['length', 'asym']): nodes[item]['length'] = length if _contains(features, ['volume']): nodes[item]['volume'] = volume if _contains(features, ['area']): nodes[item]['area'] = area if _contains(features, ['degree', 'part']): nodes[item]['degree'] = degree if item == ident: break # if _contains(features, ['part', 'asym', 'angle']): if not bifs: bifs = list(m.bifurcations(ident)) for bif in bifs: ch1, ch2 = m.children(bif) if _contains(features, ['part']): s1 = nodes[ch1]['degree'] s2 = nodes[ch2]['degree'] pa = abs(s1 - s2) / (s1 + s2 - 2) if s1 + s2 > 2 else 0.0 part.append(pa) if _contains(features, ['asym']): s1 = nodes[ch1]['length'] + m.length(ch1) s2 = nodes[ch2]['length'] + m.length(ch2) ds = abs(s1 - s2) ma = (ds / s2 if s1 < s2 else ds / s1) if s1 != s2 else 0.0 asym.append(ma) if _contains(features, ['angle']): angle.append(_angle(m, bif)) # mm = dict() if _contains(features, ['width', 'height', 'depth']): mm['bounds'] = cmin, cmax if 'width' in features: mm['width'] = (cmax - cmin)[0] if 'height' in features: mm['height'] = (cmax - cmin)[1] if 'depth' in features: mm['depth'] = (cmax - cmin)[2] if 'dist' in features: mm['dist'] = rmax if 'path' in features: mm['path'] = max(list(nodes[item]['path'] for item in nodes)) if 'order' in features: mm['order'] = max(list(nodes[item]['order'] for item in nodes)) if 'degree' in features: mm['degree'] = max(list(nodes[item]['degree'] for item in nodes)) if _contains(features, ['seclen', 'nsecs']): mm['seclen'] = list(x['length'] for x in secs) if 'tort' in features: mm['tort'] = list(x['tort'] for x in secs) if 'nbifs' in features: mm['nbifs'] = len(bifs) if 'nsecs' in features: mm['nsecs'] = len(secs) if 'ntips' in features: mm['ntips'] = len(tips) if 'length' in features: mm['length'] = nodes[ident]['length'] if 'volume' in features: mm['volume'] = nodes[ident]['volume'] if 'area' in features: mm['area'] = nodes[ident]['area'] if 'part' in features: mm['part'] = part if 'asym' in features: mm['asym'] = asym if 'angle' in features: mm['angle'] = angle if 'npoints' in features: mm['npoints'] = npoints if 'diam' in features: mm['diam'] = diam return mm
def clockangles(time_in): hour, minute = time_in.split(":") hour = int(hour) minute = int(minute) return abs((hour * 30 + minute * 0.5) - (minute * 6))
def abs(x): """Returns the absolute of x.""" return builtins.abs(x)
def abs(self): return timedelta(seconds=__builtins__.abs(self._s))
def absolute(x, **_): return builtins.abs(x)
def f(): x = 2 def g(): print(x) g() f() import builtins print(dir(builtins)) def abs(x): return 42 print(abs(-5)) print(builtins.abs(-5)) import sys print(dir(sys))