def testBase(self): # Standard SI unit s = Scalar(2, 'mm^2') self.assertTupleEqual(s.base(), ([Unit('m^2')], 1e-6)) # Special case for "kg" s = Scalar(2, 'g^2') self.assertTupleEqual(s.base(), ([Unit('kg^2')], 1e-6)) # Derived unit s = Scalar(2, 'kN^2') self.assertTupleEqual( s.base(), ([Unit('kg^2'), Unit('m^2'), Unit('s^-4')], 1e6)) # Multiple units s = Scalar(2, 'kg*N^2/s^2') self.assertTupleEqual(s.base(), ([ Unit('kg'), Unit('kg^2'), Unit('m^2'), Unit('s^-4'), Unit('s^-2') ], 1e0))
def set_arrangement(self): _unit_list = [] for i in range(4): _unit_list.append(Unit(BishopMover())) _unit_list.append(Unit(RookMover())) _unit_list.append(Unit(BishopMover())) self.put_units(3, 3, _unit_list)
def init_db(User): from unit import Unit from sla import Sla db.create_all() needcommit = False #init users if User.query.count() == 0: u = User('admin', 'admin', True) # TODO : Think to change shinken_contact defaut u.shinken_contact = 'admin' db.session.add(u) needcommit = True if Unit.query.count() == 0: #init units un = Unit('None','',1000,['','k','M','G','T']) db.session.add(un) un = Unit('Bytes','B',1024,['','k','M','G','T']) db.session.add(un) un = Unit('bits','b',1000,['','k','M','G','T']) db.session.add(un) un = Unit('Percentage','%',0,False) db.session.add(un) needcommit = True #commit db if needcommit: db.session.commit()
def game_loop(t): #(turns) #this loop puts one unit against another until destroyed or out of turns. #need to change it so unit take turns to attack each other num_turns = t while num_turns > 0: # while win == false: player = Unit("") # name enemy = Unit("") # enemy print("Number of turns:", num_turns) player.name=input("Unit 1 name: ") enemy.name=input("Unit 2 name: ") while enemy.is_alive(): # ==True player.unit_status() enemy.unit_status() dice = dice_roll() #10 side die result = player.attack(dice, enemy) num_turns -=1 f= open("results.txt", "a+") f.write(f"attack result {result} \r\n") f.close() else: print(enemy.name, "Destroyed!") else: print("Game Over")
def test_pow(self): # test 0 self.assertEqual(Unit(), self.c**0) n = randint(1, 100) # test positive int res = Unit() for _ in range(n): res = res * self.c self.assertEqual(res, self.c**n) # test negative int res = Unit() for _ in range(n): res = res / self.c self.assertEqual(res, self.c**(-n)) # test float self.assertEqual( self.c**3.141592, Unit({ 'm': 1 * 3.141592, 's': 1 * 3.141592, 'j': 2 * 3.141592 })) self.assertEqual(self.m**(-3.141592), Unit('m', -3.141592))
def read_population_from_file(filename, popsize): try: with open(filename) as f: lines = [l.strip() for l in f.readlines()] return [Unit(line) for line in lines] except: return [Unit() for i in range(popsize)]
def base(self, units=None): """Reduces `units` to base SI units as specified in `factors.py` The base SI units are limited to: - kg (kilogram) - m (metre) - s (second) - A (ampere) - K (kelvin) - cd (candela) - mol (mole) All other derived units are then converted to these base units. The base unit representations are specified in `BASES` from `factors.py`. For example: - mm -> (m, 1e-3) - g -> (kg, 1e-3) - kN^2 -> (kg^2*m^2/s^4, 1e6) - N*s -> (kg*m/s, 1e0) Parameters ------------ units: (list) a list of `Unit` objects. Returns ------------ (tuple) a tuple with two elements. The first is a list of `Unit` objects, and the second is the multiplicative factor when converting to base units. """ if units is None: units = self._units factor = 1.0 based = list() for unit in units: # 'g' is special since it's usually in 'kg' if unit.base == 'g': factor *= self.conversionFactor(unit, Unit(f'kg^{unit.power}')) else: factor *= self.conversionFactor( unit, Unit(f'{unit.base}^{unit.power}')) # Apply scaling factor (if required) splitter = BASES[unit.base].split('*') if not splitter[0].isalpha(): factor *= float(splitter[0])**unit.power splitter = splitter[1:] parsed = self.parse('*'.join(splitter)) for index in range(len(parsed)): parsed[index].power *= unit.power based += parsed return based, factor
def make_random_locfile_test1(): b1 = Unit("b1",0,0,280,440) b2 = Unit("b2",0,440,600,600) b3 = Unit("b3",600,200,800,600) b4 = Unit("b4",280,0,800,200) b5 = Unit("b5",280,200,600,440) base = [b1, b2, b3, b4, b5] make_random_locfile(base, "designs/cells18.loc")
def set_arrangement(self): _unit_list = [] for i in range(4): _unit_list.append(Unit(KingMover())) _unit_list.append(Unit(PoliceManMover())) for i in range(4): _unit_list.append(Unit(KingMover())) self.put_units(3, 3, _unit_list)
def testParse(self): s = Scalar(2) self.assertEqual(s.parse(''), [Unit('')]) self.assertEqual(s.parse('kg^2'), [Unit('kg^2')]) self.assertEqual(s.parse('kg^2*m^3/s^4'), [Unit('kg^2'), Unit('m^3'), Unit('s^-4')])
def place_x_of_last_unit(self, board, unit_type, x): if board._last_unit is None: return False unit = Unit(board._last_unit_initial_location[0] + x, -1, unit_type) if board.add_unit(unit) == False: unit = Unit(board._last_unit_initial_location[0], -1, unit_type) board.add_unit(unit) return True
def test_eq(self): self.assertFalse(self.a == 5) self.assertNotEqual(self.a, 5) self.assertEqual(self.a, self.a) self.assertNotEqual(self.a, self.b) self.assertNotEqual(self.a, np.zeros((5, 5, 5))) self.assertEqual(self.arr1, ArrayUnit(self.arr1, Unit())) self.assertEqual(ArrayUnit(self.arr1, Unit()), ArrayUnit(self.arr1, None))
def test_div(self): self.a += 0.001 # avoid division by 0 self.b += 0.001 self.assertEqual(self.a / self.b, ArrayUnit(self.arr1 / self.arr2, self.m / self.s)) self.assertEqual(self.a // self.b, ArrayUnit(self.arr1 // self.arr2, self.m / self.s)) self.assertEqual(3 / self.a, ArrayUnit(3 / self.arr1, Unit('m', -1))) self.assertEqual(3 // self.a, ArrayUnit(3 // self.arr1, Unit('m', -1))) self.assertEqual(self.a, self.a / np.ones(self.a.shape))
def setUp(self): ArrayUnit.is_strict = True self.arr1 = np.linspace(1, 9, 9).reshape(3, 3) self.arr2 = self.arr1 - 5 self.m = Unit('m') self.s = Unit('s', -2) self.a = ArrayUnit(self.arr1, self.m) self.b = ArrayUnit(self.arr2, self.s)
def test_init(self): # Simplest case is dimensionless unit u = Unit('') self.assertEqual(u.prefix, '') self.assertEqual(u.base, '') self.assertEqual(u.power, 1) self.assertEqual(u.latex, '') self.assertEqual(u.parsed, ['', '', 1]) self.assertEqual(u.unparsed, '') # Unit with no prefix or power u = Unit('N') self.assertEqual(u.prefix, '') self.assertEqual(u.base, 'N') self.assertEqual(u.power, 1) self.assertEqual(u.latex, 'N') self.assertEqual(u.parsed, ['', 'N', 1]) self.assertEqual(u.unparsed, 'N') # Unit with prefix, no power u = Unit('mJ') self.assertEqual(u.prefix, 'm') self.assertEqual(u.base, 'J') self.assertEqual(u.power, 1) self.assertEqual(u.latex, 'mJ') self.assertEqual(u.parsed, ['m', 'J', 1]) self.assertEqual(u.unparsed, 'mJ') # Unit with power, no prefix u = Unit('C^2') self.assertEqual(u.prefix, '') self.assertEqual(u.base, 'C') self.assertEqual(u.power, 2) self.assertEqual(u.latex, 'C^{2}') self.assertEqual(u.parsed, ['', 'C', 2]) self.assertEqual(u.unparsed, 'C^2') # Unit with prefix and power u = Unit('kg^2') self.assertEqual(u.prefix, 'k') self.assertEqual(u.base, 'g') self.assertEqual(u.power, 2) self.assertEqual(u.latex, 'kg^{2}') self.assertEqual(u.parsed, ['k', 'g', 2]) self.assertEqual(u.unparsed, 'kg^2')
def set_arrangement(self): self._result.arrangement.append((Unit(CheckersKingMover()), 0, 0)) self._result.arrangement.append((Unit(PoliceManMover()), 0, 1)) self._result.arrangement.append((Unit(SwapMover()), 1, 0)) self._result.arrangement.append((Unit(SnakeMover()), 1, 1)) self._result.arrangement.append((Unit(RookMover()), 0, 2)) self._result.arrangement.append((Unit(BishopMover()), 0, 3)) self._result.arrangement.append((Unit(FlexMover()), 1, 2)) self._result.arrangement.append((Unit(UsualMover()), 2, 1)) self._result.arrangement.append((Unit(KingMover()), 2, 0)) self._result.arrangement.append((Unit(PawnMover()), 3, 0))
def ex1(): m = Unit('m') s = Unit('s', -2) arr = np.linspace(1,10,10, dtype=float) a = ArrayUnit(arr, m) b = ArrayUnit(arr**2, s) ArrayUnit.is_strict = True print(a, '\n+\n', 1, '\n=\n', a + 1) print('__________________________________________') print(a, '\n-\n', arr, '\n=\n', a - arr) print('__________________________________________') print(a, '\n*\n', b, '\n=\n', a * b) print('__________________________________________') print(b, '\n//\n', a, '\n=\n', b / a)
def test_operations(self): u = Unit('kg^2') v = Unit('kg^2') w = Unit('mJ') self.assertEqual(str(u), 'kg^2') self.assertTrue(u == v) self.assertFalse(u == w) self.assertFalse(v == w) self.assertFalse(u != v) self.assertTrue(u != w) self.assertTrue(v != w)
def test_truediv(self): # __truediv__ with Unit() self.assertEqual(self.m, self.m / 2) self.assertEqual(self.m / 2, self.m / [6, 9]) # __rtruediv__ with Unit() self.assertEqual(Unit() / self.m, 1 / self.m) self.assertEqual(1 / self.m, [6, 9] / self.m) # div between 2 Unit self.assertEqual(self.m / self.m, Unit()) self.assertEqual(self.m / self.s, Unit({'m': 1, 's': 1})) self.assertEqual(self.c / self.m / self.s, Unit({'s': 2, 'j': 2})) self.assertEqual(self.m / self.c, Unit({'s': -1, 'j': -2}))
def test_floordiv(self): # copy pasta of test_truediv with "//" instead of "/" # __floordiv__ with Unit() self.assertEqual(self.m, self.m // 2) self.assertEqual(self.m // 2, self.m // [6, 9]) # __rfloordiv__ with Unit() self.assertEqual(Unit() // self.m, 1 // self.m) self.assertEqual(1 // self.m, [6, 9] // self.m) # div between 2 Unit self.assertEqual(self.m // self.m, Unit()) self.assertEqual(self.m // self.s, Unit({'m': 1, 's': 1})) self.assertEqual(self.c // self.m // self.s, Unit({'s': 2, 'j': 2})) self.assertEqual(self.m // self.c, Unit({'s': -1, 'j': -2}))
def test_battle_animation(): display.initialize() import gettext import logging import resources gettext.install('ice-emblem', resources.LOCALE_PATH) logging.basicConfig(level=80) s.load_map('resources/maps/default.tmx') unit1 = Unit(name='Soldier', health=30, level=1, experience=99, strength=5, skill=500, speed=1, luck=2, defence=1, resistance=1, movement=1, constitution=1, aid=1, affinity=None, wrank=[]) unit2 = Unit(name='Skeleton', health=31, level=1, experience=0, strength=6, skill=30, speed=10, luck=1, defence=1, resistance=1, movement=1, constitution=1, aid=1, affinity=None, wrank=[]) unit1.coord = (1, 1) unit2.coord = (1, 2) team1 = Team('Ones', (255, 0, 0), 0, [unit1], unit1, {}) team2 = Team('Twos', (0, 0, 255), 0, [unit2], unit2, {}) s.units_manager.units = [unit1, unit2] display.window.fill(c.GREY) while unit1.health > 0 and unit2.health > 0: room.run_room(BattleAnimation(unit1, unit2)) unit1, unit2 = unit2, unit1 pygame.quit()
def init(): global game_map global hero global commander hero = Hero(10, 11.0, 11.0, math.pi / 2) commander = Commander() game_map = GameMap(20, 20, [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ], hero, commander, [Unit(10, 10.5, 7.5, 0)]) game_map.generate_hostiles(5) game_map.generate_friendlies(3)
def __init__(self, K=3, N=4, L=3, lrule=Hebbian): self.units = [] self.K = K self.N = N self.y = None for unit in range(K): self.units.append(Unit(N, L, lrule))
def parse(file_path): tree = ElementTree.parse(file_path) score = tree.getroot() lines = [] for line in score.findall('line'): bars = [] for bar in line.findall('bar'): units = [] time_signature = bar.get('time_signature') for unit in bar.findall('unit'): notes = [] for note in unit.findall('note'): pitch = note.get('pitch') hold_str = note.get('hold') hold = {'True': True, 'False': False}[hold_str] print(pitch) notes.append(Note(pitch, hold)) beats = unit.get('beats') units.append(Unit(notes, Fraction(beats))) key = bar.get('key') bars.append(Bar(key, time_signature, units)) lines.append(bars) title = score.get('title') author = score.get('author') return Score(lines, title, author)
def __init__(self, x=0, y=0, z=0, name="Vector"): self.x = x self.y = y self.z = z self.initial = (x, y) self.unit = Unit() self.name = name
def parse(self, units=''): """Parses `units` into a list of `Unit` objects. This method can parse multiple units separated by the multiplication symbol "*" or division symbol "/". For example: - A/s -> [Unit(A), Unit(s^-1)] - kg*m^2/s^2 -> [Unit(kg), Unit(m^2), Unit(s^-2)] Parameters ------------ units: (str) a string of units. Returns ------------ (list) a list of `Unit` objects. """ parsed = list() sign = 1 groups = units.split('/') # Remove empty numerator (if numerator is empty) if len(groups) > 1 and groups[0] == '': del groups[0] for group in groups: for unit in group.split('*'): u = Unit(unit) u.power *= sign parsed.append(u) sign *= -1 return parsed
def findBetterTrain(self, fuilfulledTrains, order, parts): part_orders = [] for part in parts: part_orders.append( Unit(order.id, order.getPriority(), order.getDueDate(), order.getMass(), order.getLength(), part[0], part[-1])) roads = [[x] for x in fuilfulledTrains[0]] fuilfulledTrains.pop(0) while len(fuilfulledTrains) != 0: x = roads.copy() y = fuilfulledTrains[0] fuilfulledTrains.pop(0) roads.clear() for i in x: for j in y: roads.append(i + [j]) best_cost = None best_road = [] for road in roads: if len(set(road)) != len(road): continue if self.canDeliver(road, order, parts): cost = self.calculateInsertionCost(road[-1], order) if best_cost is None: best_cost = cost best_road = road if best_cost > cost: best_cost = cost best_road = road return best_road, best_cost
def generate_one_unit(i, paper, problem_list): """ 随机生成一个个体 """ unit = Unit() unit.id = i + 1 each_type_count = paper.each_type_count while paper.total_score != unit.sum_score: unit.problem_list = [] for j in range(len(each_type_count)): one_type_problem = [ p for p in problem_list if p.type == j+1 and is_contain_points(p, paper)] for k in range(0, each_type_count[j]): length = len(one_type_problem) index = randint(0, length - k - 1) unit.problem_list.append(one_type_problem[index]) one_type_problem[index], one_type_problem[length-k-1] = \ one_type_problem[length-k-1], \ one_type_problem[index] return unit
def reduce_unit(self, guide_unit=None): """ Combine similar component units and scale, to form an equal Quantity in simpler units. Returns underlying value type if unit is dimensionless. """ key = (self.unit, guide_unit) if key in Quantity._reduce_cache: (unit, value_factor) = Quantity._reduce_cache[key] else: value_factor = 1.0 canonical_units = { } # dict of dimensionTuple: (Base/ScaledUnit, exponent) # Bias result toward guide units if guide_unit is not None: for u, exponent in guide_unit.iter_base_or_scaled_units(): d = u.get_dimension_tuple() if d not in canonical_units: canonical_units[d] = [u, 0] for u, exponent in self.unit.iter_base_or_scaled_units(): d = u.get_dimension_tuple() # Take first unit found in a dimension as canonical if d not in canonical_units: canonical_units[d] = [u, exponent] else: value_factor *= (u.conversion_factor_to( canonical_units[d][0])**exponent) canonical_units[d][1] += exponent new_base_units = {} for d in canonical_units: u, exponent = canonical_units[d] if exponent != 0: assert u not in new_base_units new_base_units[u] = exponent # Create new unit if len(new_base_units) == 0: unit = dimensionless else: unit = Unit(new_base_units) # There might be a factor due to unit conversion, even though unit is dimensionless # e.g. suppose unit is meter/centimeter if unit.is_dimensionless(): unit_factor = unit.conversion_factor_to(dimensionless) if unit_factor != 1.0: value_factor *= unit_factor # print "value_factor = %s" % value_factor unit = dimensionless Quantity._reduce_cache[key] = (unit, value_factor) # Create Quantity, then scale (in case value is a container) # That's why we don't just scale the value. result = Quantity(self._value, unit) if value_factor != 1.0: # __mul__ strips off dimensionless, if appropriate result = result * value_factor if unit.is_dimensionless(): assert unit is dimensionless # should have been set earlier in this method if is_quantity(result): result = result._value return result
def NewGame(self, img=None, stats=None, numUnits=None, name=None, equipmentTypes=None): if img: equipmentTypes = equipmentTypes or [] unit = self.AddUnit( Unit( self.screen, img=img, highlight=True, name=name, )) for equipType in equipmentTypes: equip = equipType(self.screen, unit) unit.Equip(equip) unit.angularVelocity += stats.get('spin', 0) * 10 self.player = unit unit.position = (unit.width, unit.height) for i in range(numUnits or int(self.surf.get_width() / 300) + 2): self.AddRandomUnit() self.AddGravity(self.surf.get_rect().center, random.randint(50, 100)) for i in range(random.randint(4, int(self.screen.get_width() / 100))): self.AddGravity( (random.randint(0, self.surf.get_width()), random.randint(0, self.surf.get_height())), random.randint(10, 25), ) self.AddRandomBooster()