def __init__(self, axis, **kwargs): Container.__init__(self, **kwargs) self._axis = axis self.padding = (kwargs.get("hpadding", 5), kwargs.get("vpadding", 5)) self.expandable[self._axis] = True
def _allocate(self, width, height): Container._allocate(self, width, height) style = self._style p = style.padding content_size = [self._size_allocation[0]-p[2]-p[3], self._size_allocation[1]-p[0]-p[1]] x, y = self.x + p[2], self.y - p[0] children = [child for child in self._children if not child._deleted] children_nx = [child for child in children if not child._expand[0]] children_x = [child for child in children if child._expand[0]] free = content_size[0] - self._spacing*(len(children)-1) free -= reduce(add,[child._minimum_size[0] for child in children_nx] or [0]) extra = free - reduce(add,[child.size_request[0] for child in children_x] or [0]) child_extra = extra/float(len(children_x)) if len(children_x): common_size = free / float(len(children_x)) for child in children: if not self._homogeneous or not child._expand[0]: size = child.size_request[0] if child._expand[0]: size += child_extra else: size = common_size child._position=[x,y] child._allocate(size,content_size[1]) x += size + self._spacing
def _config(self, **kwargs): """ widgets: ``list`` Contains widgets to pack into box. The order of widgets in the list denotes order they are packed. border: ``int`` Number of pixels to space around edges when ``surf`` is not given. col: ``tuple`` (r,g,b) Colour for background, 0 is transparent. spacing: ``int`` Number of pixels to space between widgets. """ if "spacing" in kwargs: self._settings["spacing"] = kwargs["spacing"] if "widgets" in kwargs: pos = 0 # Shift widget positions so all labels are displayed. height = 0 for w in kwargs["widgets"]: if w._label is not None and w._label.side == "top": height = max(height, w._label.rect.h) for w in kwargs["widgets"]: offset = 0 if w._label is not None: if w._label.side == "left": offset = w._label.rect.w r = w.rect.union(w._label.rect) else: r = w.rect w.pos = (pos + offset, height) pos += r.w + self._settings["spacing"] Container._config(self, **kwargs)
def __init__(self): """Class initialiser""" self.terminator = Terminator() self.terminator.register_window(self) Container.__init__(self) gtk.Window.__init__(self) gobject.type_register(Window) self.register_signals(Window) self.set_property("allow-shrink", True) self.apply_icon() self.register_callbacks() self.apply_config() self.title = WindowTitle(self) self.title.update() options = self.config.options_get() if options: if options.forcedtitle is not None: self.title.force_title(options.forcedtitle) if options.role is not None: self.set_role(options.role) if options.geometry is not None: if not self.parse_geometry(options.geometry): err("Window::__init__: Unable to parse geometry: %s" % options.geometry) self.pending_set_rough_geometry_hint = False
def __init__(self, util, meter_type, ui_refresh_period, data_source): """ Initializer :param util: utility class :param meter_type: the type of the meter - linear or circular :param ui_refresh_period: refresh interval for animation :param data_source: audio data source """ self.util = util self.meter_config = util.meter_config if getattr(util, "config", None): self.config = util.config self.rect = self.config[SCREEN_RECT] else: self.rect = self.util.meter_config[SCREEN_RECT] self.meter_type = meter_type self.ui_refresh_period = ui_refresh_period self.data_source = data_source Container.__init__(self, util, self.rect, (0, 0, 0)) self.max_volume = 100.0 self.total_steps = 100 self.origin_x = self.origin_y = 0 self.meter_bounding_box = None self.bgr = None self.fgr = None self.left_sprites = None self.right_sprites = None self.needle_sprites = None self.mono_needle_rects = None self.left_needle_rects = None self.right_needle_rects = None self.masks = None self.channels = 1
def __init__(self, window): """Class initialiser""" if isinstance(window.get_child(), gtk.Notebook): err('There is already a Notebook at the top of this window') raise(ValueError) Container.__init__(self) gtk.Notebook.__init__(self) self.terminator = Terminator() self.window = window gobject.type_register(Notebook) self.register_signals(Notebook) self.connect('switch-page', self.deferred_on_tab_switch) self.configure() child = window.get_child() window.remove(child) window.add(self) window_last_active_term = window.last_active_term self.newtab(widget=child) if window_last_active_term: self.set_last_active_term(window_last_active_term) window.last_active_term = None self.show_all()
def __init__(self): """Class initialiser""" self.terminator = Terminator() self.maker = Factory() Container.__init__(self) self.signals.append({'name': 'resize-term', 'flags': gobject.SIGNAL_RUN_LAST, 'return_type': gobject.TYPE_NONE, 'param_types': (gobject.TYPE_STRING,)})
def cmd_toggle_decorations(self): self.decor = not self.decor if self.decor: self.borders_remove() else: self.borders_add() Container.manage_focus(self.monitor.get_active())
def update_layout(self): Container.update_layout(self) total = self.padding for c in self.children[::-1]: c.y = total total += c.h + self.padding self._h = total
def __init__(self, x, y, w, h, **kwargs): '''Create a vertical layout Keyword arguments: name -- unique widget identifier padding -- vertical space between child items ''' self.padding = kwargs.get('padding', 5) Container.__init__(self, x, y, w, h, **kwargs)
def end_timer(my, name="top"): end = time.time() from container import Container start = Container.get("Base:start:%s" % name) diff = end - start total = Container.get("Base:total:%s" % name) total += diff Container.put("Base:total:%s" % name, total) Base.__timing += diff return total
def __init__(self, theme, **kwargs): """Create a frame Keyword arguments: children -- list of child elements to be added to this container """ Container.__init__(self, **kwargs) self.names = {} self.focus = [] self.theme = theme
def __init__(self,caption=""): Container.__init__(self) self.mMoved=False self.mDragOffsetX=-1 self.mDragOffsetY=-1 self.setCaption(caption) self.setFrameSize(1) self.setPadding(2) self.setTitleBarHeight(16) self.setAlignment(Graphics.CENTER) self.addMouseListener(self) self.setMovable(True) self.setOpaque(True)
def __init__(self, children=[], homogeneous=True, spacing=1): ''' Create horizontal box :Parameters: children : [glydget.Widget, ...] Initial list of children homogeneous : bool If true all children are given equal space allocations. spacing : int The horizontal space between children in pixels. ''' self._spacing = spacing self._homogeneous = homogeneous Container.__init__(self, children) self.style = theme.Container
def new_container(): try: service = request.form['service'] except KeyError: return Response("service field should be providen", status=422) try: image = request.form['image'] except KeyError: return Response("image field should be providen", status=422) try: port = int(request.form['port']) return json.dumps(Container.create(service=service, port=port, image=image)) except KeyError: return json.dumps(Container.create(service=service, image=image), cls=ContainerJSONEncoder)
def __init__(self, children=[], homogeneous=False, spacing=1): """ :Parameters: `children` : [glydget.widget.Widget, ...] Initial list of children `homogeneous` : bool If true all children are given equal space allocations. `spacing` : int The horizontal space between children in pixels. """ self._spacing = spacing self._homogeneous = homogeneous Container.__init__(self, children) self.style = theme.Container
def update_NET_ACTIVE_WINDOW(): global properties active = ptxcb.XROOT.get_active_window() if not active: return set_active(active) properties["_NET_ACTIVE_WINDOW"] = get_active() active = get_active() if active and active.monitor: active.monitor.active = active Container.manage_focus(active)
def node_status(): status = { "cpus": sysinfo.cpus_usage(), "free_memory": sysinfo.free_memory(), "memory": sysinfo.memory(), "net": sysinfo.net_interfaces_usage(), "nb_containers": Container.count() } return json.dumps(status)
def __init__(self, window): """Class initialiser""" if isinstance(window.get_child(), gtk.Notebook): err('There is already a Notebook at the top of this window') raise(ValueError) Container.__init__(self) gtk.Notebook.__init__(self) self.terminator = Terminator() self.window = window gobject.type_register(Notebook) self.register_signals(Notebook) self.configure() child = window.get_child() window.remove(child) window.add(self) self.newtab(widget=child) self.show_all()
def __init__(self): """Class initialiser""" self.terminator = Terminator() self.terminator.register_window(self) Container.__init__(self) GObject.GObject.__init__(self) GObject.type_register(Window) self.register_signals(Window) self.get_style_context().add_class("terminator-terminal-window") # self.set_property('allow-shrink', True) # FIXME FOR GTK3, or do we need this actually? icon_to_apply='' self.register_callbacks() self.apply_config() self.title = WindowTitle(self) self.title.update() self.preventHide = False options = self.config.options_get() if options: if options.forcedtitle: self.title.force_title(options.forcedtitle) if options.role: self.set_role(options.role) if options.forcedicon is not None: icon_to_apply = options.forcedicon if options.geometry: if not self.parse_geometry(options.geometry): err('Window::__init__: Unable to parse geometry: %s' % options.geometry) self.apply_icon(icon_to_apply) self.pending_set_rough_geometry_hint = False
def _evaluate(my, xpath): cache = Container.get("XML:xpath_cache") if cache == None: cache = {} Container.put("XML:xpath_cache", cache) #key = "%s|%s" % (str(my.doc), xpath) num = random.randint(0, 500000) key = "%s_%s|%s" % (str(my.doc), num, xpath) result = cache.get(key) if result == None: result = Evaluate(xpath, my.doc) cache[key] = result #print xpath else: #print "reuse" pass return result '''
def _allocate(self, width, height): ''' Set size allocation. **Parameters** `width` : int Width in pixels `height` : int Height in pixels ''' Container._allocate(self, width, height) style = self._style p = style.padding content_size = [self._size_allocation[0]-p[2]-p[3], self._size_allocation[1]-p[0]-p[1]] x, y = self.x + p[2], self.y - p[0] children = [child for child in self._children if not child._deleted] children_nx = [child for child in children if not child._expand[1]] children_x = [child for child in children if child._expand[1]] free = content_size[1] - self._spacing*(len(children)-1) free -= reduce(add,[child._minimum_size[1] for child in children_nx] or [0]) extra = free - reduce(add,[child.size_request[1] for child in children_x] or [0]) extra = extra/float(len(children_x)) if len(children_x): common_size = free / float(len(children_x)) for child in children: if not self._homogeneous or not child._expand[1]: size = child.size_request[1] if child._expand[1]: size += extra else: size = common_size child._position=[x,y] child._allocate(content_size[0], size) y -= size + self._spacing
def __init__(self, **kwargs): Container.__init__(self) self.window_class = kwargs['window_class'] self.window_title = kwargs.get('window_title', None)
def cleanup_monster(self, monster): # drop monster self.events.append({ 'type': 'dropmonster', 'name': monster.name, 'title': monster.title, 'zone': monster.zone }) # award exp to killer monster.target.exp += (monster.level / monster.target.level) * (10 * monster.level) # check if this death satisfies quests for quest in monster.target.quests.values(): quest.check_goal(monster.name) # create container object holding monster treasure container_name = "container-%s" % self.container_index self.container_index += 1 title = "Remains of %s" % monster.title x = monster.x y = monster.y zone = monster.zone # award random amount of gold gold = random.randint(self.loot[monster.loot].gold_min, self.loot[monster.loot].gold_max) create_container = False # 50% chance of common for i in self.loot[monster.loot].items_common: if random.random() < .50: item = Item(i, None, container_name, False, self) # 10% chance of uncommon for i in self.loot[monster.loot].items_uncommon: if random.random() < .10: item = Item(i, None, container_name, False, self) # 5% chance of rare for i in self.loot[monster.loot].items_rare: if random.random() < .05: item = Item(i, None, container_name, False, self) self.containers[container_name] = Container(title, container_name, x, y, zone, gold, monster.target.name) self.events.append({ 'type': 'addcontainer', 'name': container_name, 'title': title, 'x': x, 'y': y, 'zone': zone }) # clean up container after 60 sec reactor.callLater(60.0, self.cleanup_container, container_name) # Really delete monster monster.spawn.spawn_count -= 1 del self.monsters[monster.name]
def __init__(self): Container.init(None)
def closeterm(self, widget): """Handle a terminal closing""" Container.closeterm(self, widget) self.hoover()
import signal from communication.IncommingTextStreamCommunicationThread import IncommingTextStreamCommunicationThread from container import Container from ifttt.IftttRulesThread import IftttRulesThread from tools.AsyncJobsThread import AsyncJobsThread from tools.HomeDefenceThread import HomeDefenceThread container = Container() root_logger = container.root_logger() async_actuator_commands = container.async_actuator_commands() sensors_repo = container.sensors_repository() change_actuator_listener = container.change_actuator_listener() fingerprint_door_unlock_listener = container.fingerprint_door_unlock_listener() intruder_alert_listener = container.intruder_alert_listener() async_actuator_commands.connect() device_lifetime_manager = container.device_lifetime_manager() serial = container.serial() bluetooth = container.bluetooth_serial() device_lifetime_manager\ .add_device('serial', serial)\ .add_device('bluetooth', bluetooth) \ .add_device('zwave', container.zwave_device()) \ .add_device('wemo', container.wemo_switch()) \ .connect() def main():
def __init__(self, component, **traits): self.component = component Container.__init__(self, **traits) self._viewport_component_changed() return
def container_is_started(context, pname="java"): container = Container(context.config.userdata['IMAGE'], name=context.scenario.name) container.start() context.containers.append(container) wait_for_process(context, pname)
myHealth = 95 visitedRooms = [] # ********************************* SET UP THE ROOMS ********************************* # Kitchen # # Room descriptions should include interactive containers like CABINET, BIN, DESK, SHELF, SHOEBOX that contain/hide other interactive items Gym = Room( "Gym", "A big, empty, dark room with a bunch of boxes everywhere. On the floor there is a KNIFE and a FIRST AID" ) # The kitchen has a CUPBOARD object that contains/hides 3 interactive items, a sponge, a plate, a can of soup # Once this container is open, the interactive items will no longer be hidden in the container Gym.box = Container("box right next to you", ["basketball", "shoe", "tennis ball"]) # The kitchen has a CABINET object that contains/hides 2 interactive items, a knife and a twinkie # Once this container is open, the interactive items will no longer be hidden in the container Gym.box2 = Container("a closed, shiny box near the gym door", ["diary of a wimpy kid book", "baseball helmet"]) # Create an interactive item that's show in a room (not hidden in a container) with create_room_item() Gym.create_room_item("knife") Gym.create_room_item("first aid") # Classroom # classroom = Room( "Classroom", "A dark room with rows of desks and posters on the walls. There are items on some of the desks and a BOX in the corner of the room. You can READ a poster. You can Take at the items on the DESKS. There is a red flashlight near the door." )
def load(self, player_name, zone_source, players, monsters, npcs, containers, zone_data): # unload monsters for m in self.monsters.values(): m.unload() for p in self.players.values(): p.unload() for n in self.npcs.values(): n.unload() for s in self.spells: s.unload() # Load zone and save to cache if not self.zones.has_key(zone_source): # write zone_data to zone_source with open('client_data/zones/' + zone_source, 'w') as tmxfile: tmxfile.write(zone_data) self.zones[zone_source] = load_pyglet('client_data/zones/' + zone_source) self.zone = self.zones[zone_source] for layer in self.zone.layers: if layer.name == 'character' or layer.name == 'blocked' or layer.name == 'block' or layer.name == 'spawns': pass else: layer.batch = pyglet.graphics.Batch() layer.sprites = [] for x, y, image in layer.tiles(): y = self.zone.height - y - 1 sprite = pyglet.sprite.Sprite(image, x * self.zone.tilewidth, y * self.zone.tileheight, batch=layer.batch) layer.sprites.append(sprite) else: # Set zone from cache self.zone = self.zones[zone_source] self.player_name = player_name self.players = {} self.monsters = {} self.npcs = {} self.containers = {} self.offset = [] for name, player in players.items(): self.players[name] = Player(player['title'], player['gender'], player['body'], player['hairstyle'], player['haircolor'], player['armor'], player['head'], player['weapon'], player['x'], player['y']) for name, npc in npcs.items(): self.npcs[name] = Npc(npc['title'], npc['gender'], npc['body'], npc['hairstyle'], npc['haircolor'], npc['armor'], npc['head'], npc['weapon'], npc['x'], npc['y'], npc['villan']) for name, monster in monsters.items(): self.monsters[name] = Monster(monster['title'], monster['source'], monster['x'], monster['y']) for name, container in containers.items(): self.containers[name] = Container( container['title'], container['x'], container['y'], container['source'], container['source_w'], container['source_h'], container['source_x'], container['source_y']) # Set our label to green :) self.players[player_name].label.color = (0, 255, 0, 255)
myHealth = 53 visitedRooms = [] # ********************************* SET UP THE ROOMS ********************************* # Kitchen # # Room descriptions should include interactive containers like CABINET, BIN, DESK, SHELF, SHOEBOX that contain/hide other interactive items kitchen = Room( "Kitchen", "A dark and dirty room with flies buzzing around. There are dirty beakers, graduated cylinders, and pipettes in the sink. There is a CUPBOARD above the sink and a CABINET under the sink." ) # The kitchen has a CUPBOARD object that contains/hides 3 interactive items, a sponge, a plate, a can of soup # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cupboard = Container("cupboard above the sink", ["sponge", "plate", "can of soup"]) # The kitchen has a CABINET object that contains/hides 2 interactive items, a knife and a twinkie # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cabinet = Container("cabinet under the sink", ["knife", "twinkie"]) # Create an interactive item that's show in a room (not hidden in a container) with create_room_item() kitchen.create_room_item("spoon") kitchen.create_room_item("rat") # Small Office # smalloffice = Room( "Small Office", "A dark room with a mess of books and papers covering the desk. There is some mail and an ozon.ru PACKAGE. You can READ a book. You can look in the DESK." ) smalloffice.desk = Container("desk", ["battery", "envelope"])
def on_mouse_drag(self, x, y, dx, dy, button, modifiers): if len(self.focus) > 0: return self.focus[-1].on_mouse_drag(x, y, dx, dy, button, modifiers) return Container.on_mouse_drag(self, x, y, dx, dy, button, modifiers)
def remove(self, child): Container.remove(self, child) self.update_batch(pyglet.graphics.Batch(), self._group)
def testConstructor(self): container = Container() self.assertEqual(container.containerType, "Medium Box")
def clear_xpath_cache(my): my.cache_xpath = {} Container.put("XML:xpath_cache", {})
async def _get_container(self, **filters): contr = await self.__contr_col.find_one(filters) if not contr: return 404, None, "Container matching '%s' is not found" % filters return Container.parse(contr, False)
options.parse_config_file("config.py") options.parse_command_line() if options.sentrydsn: sentry_sdk.init(dsn=options.sentrydsn, integrations=[TornadoIntegration()]) else: logging.warn("Sentry dsn is not set") mongodb = None while not mongodb: try: mongodb = pymongo.MongoClient(options.mongouri) except: logging.error("Cannot not connect to MongoDB") masterdb = mongodb[options.masterdb] services = init_messaging_agents(masterdb) SYSTEM_DATA = ( ("mongodburi", options.mongouri, None), ("mongodbconn", mongodb, None), ("services", services, None), ("serveroptions", options, None), ("dao", Dao, ("mongodbconn", "serveroptions")), ) container = Container(SYSTEM_DATA) WebApplication(container).main()
def build(self): Builder.load_file('dialogcontent.kv') Builder.load_file('carditem.kv') Builder.load_file('paycarditem.kv') return Container()
myHealth = 53 visitedRooms = [] # ********************************* SET UP THE ROOMS ********************************* # Kitchen # # Room descriptions should include interactive containers like CABINET, BIN, DESK, SHELF, SHOEBOX that contain/hide other interactive items kitchen = Room( "Kitchen", "A dark and dirty room with flies buzzing around. There are dirty beakers, graduated cylinders, and pipettes in the sink. There is a CUPBOARD above the sink and a CABINET under the sink." ) # The kitchen has a CUPBOARD object that contains/hides 3 interactive items, a sponge, a plate, a can of soup # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cupboard = Container("cupboard above the sink", ["sponge", "plate", "can of bOPW soup"]) # The kitchen has a CABINET object that contains/hides 2 interactive items, a knife and a twinkie # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cabinet = Container("cabinet under the sink", ["knife", "twinkie"]) # Create an interactive item that's show in a room (not hidden in a container) with create_room_item() kitchen.create_room_item("spoon") kitchen.create_room_item("rat") #Bathroom bathroom = Room( "Bathroom", "An old bathroom that had been trashed a long time ago and it looks like nobody had been in there for a long time. There is a shelf and a cabinet next to the shelf." ) bathroom.shelf = Container("shelf", ["rat", "empty bag of food"]) bathroom.cabinet = Container("cabinet", ["dead Spider", "ammo"])
def __init__(self, position, size, children=[], format=GL_RGB8, *args, **kwargs): Container.__init__(self, sort_key=lambda x: x.__zorder, children=children) FBOWidget.__init__(self, position, size, *args, format=format, **kwargs)
def create_new_window_from_active(): new_window_id = system_calls.get_active_window_id() new_woof_id = tree_manager.get_new_woof_id() return Container(new_window_id, new_woof_id)
def add(self, widget, zorder=0): widget.__zorder = copy(zorder) Container.add(self, widget)
def cleanup_npc(self, npc): # drop npc self.events.append({ 'type': 'dropnpc', 'name': npc.name, 'title': npc.title, 'zone': npc.zone }) # award exp to killer npc.target.exp += (npc.level / npc.target.level) * (10 * npc.level) # create container object holding npc treasure #container_name = "container-%s" % self.container_index container_name = str(uuid.uuid4()) self.container_index += 1 title = "Remains of %s" % npc.title x = npc.x y = npc.y zone = npc.zone # award random amount of gold gold += random.randint(self.loot[npc.loot].gold_min, self.loot[npc.loot].gold_max) create_container = False # 50% chance of common for i in self.loot[npc.loot].items_common: if random.random() < 0.5: item = Item(i, None, container_name, False, self) # 10% chance of uncommon for i in self.loot[npc.loot].items_uncommon: if random.random() < 0.1: item = Item(i, None, container_name, False, self) # 5% chance of rare for i in self.loot[npc.loot].items_rare: if random.random() < 0.05: item = Item(i, None, container_name, False, self) self.containers[container_name] = Container(title, container_name, x, y, zone, npc.target.name) self.events.append({ 'type': 'addcontainer', 'name': container_name, 'title': title, 'x': x, 'y': y, 'zone': zone, 'source': source, 'source_w': 32, 'source_h': 32, 'source_x': 0, 'source_y': 0 }) # clean up container after 60 sec reactor.callLater(60.0, self.cleanup_container, container_name) npc.spawn.spawn_count -= 1 del self.npcs[npc.name]
from computer import Computer heldItems = [] myHealth = 53 visitedRooms = [] # ********************************* SET UP THE ROOMS ********************************* # Kitchen # # Room descriptions should include interactive containers like CABINET, BIN, DESK, SHELF, SHOEBOX that contain/hide other interactive items kitchen = Room("Kitchen","A dark and dirty room with flies buzzing around. There are dirty beakers, graduated cylinders, and pipettes in the sink. There is a CUPBOARD above the sink and a CABINET under the sink.") # The kitchen has a CUPBOARD object that contains/hides 3 interactive items, a sponge, a plate, a can of soup # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cupboard = Container("cupboard above the sink",["sponge","plate","can of bOPW soup"]) # The kitchen has a CABINET object that contains/hides 2 interactive items, a knife and a twinkie # Once this container is open, the interactive items will no longer be hidden in the container kitchen.cabinet = Container("cabinet under the sink",["knife","twinkie"]) # Create an interactive item that's show in a room (not hidden in a container) with create_room_item() kitchen.create_room_item("spoon") kitchen.create_room_item("rat") # Small Office # smalloffice = Room("Small Office","A dark room with a mess of books and papers covering the desk. There is some mail and an ozon.ru PACKAGE. You can READ a book. You can look in the DESK.") smalloffice.desk = Container("desk",["battery","envelope"]) smalloffice.package = Container("ozon.ru package",["sheet of bubble wrap","porcelain figurine of a bear","red flashlight"]) smalloffice.create_room_item("guinea pig") redFlashlight = Flashlight("red",0,False)
from chainsaw import Chainsaw heldItems = [] myHealth = 50 visitedRooms = [] # ********************************* SET UP THE ROOMS ******************************************** # # Shop # # Room descriptions should include interactive containers like CABINET, CARDBOARD BOX, SHOEBOX, and LOCKED CONTAINER shop = Room("Shop","A dark crypt, skulls surround you and give you an eerie feeling. Growls echo along the walls, as you search for things. There is a CABINET above a dirty sink, A CARDBOARD BOX in the corner, and A SHOEBOX under the sink.") # The Shop has a CABINET object that contains/hides 2 interactive items: a fork and a health potion # Once this container is open, the interactive items will no longer be hidden in the container shop.cabinet = Container("cabinet above the sink",["a fork","health potion"]) # The Shop has a CARDBOARD BOX object that contains/hides 1 interactive item, a bitten cookie # Once this container is open, the interactive items will no longer be hidden in the container shop.cardboardbox = Container("a cardboard box in the corner",["cookie"]) # The Shop has a SHOEBOX object that contains/hides 2 interactive items: a kinfe and soap # Once this container is open, the interactive items will no longer be hidden in the container shop.shoebox = Container("shoebox under the sink",["a knife","soap"]) # Create an interactive item that's show in a room (not hidden in a container) with create_room_item() newPotion = HealthPotion(0,0) #Armory Room # armory = Room("Armory Room","A dark open room that has a stinky stench. A glimmer catches your eye and you find a PISTOL. you find some other weapons but they are all broken.") armory.create_room_item("gun") newGun = Gun("New","Pistol",0)
def __setitem__(self, key, value): if isinstance(value, pd.Series): self.data_df.__setitem__(Container(key), map(Container, value)) else: self.data_df.__setitem__(Container(key), Container(value))
def parse(cls, data, from_user=True): def validate_dependencies(contrs): contrs = {c.id: c for c in contrs} parents = {} for c in contrs.values(): nonexist = list(filter(lambda c: c not in contrs, c.dependencies)) if nonexist: return 422, None, "Dependencies '%s' do not exist in this appliance" % nonexist parents.setdefault(c.id, set()).update(c.dependencies) for c, p in parents.items(): cycles = ['%s<->%s' % (c, pp) for pp in filter(lambda x: c in parents.get(x, set()), p)] if cycles: return 422, None, "Cycle(s) found: %s" % cycles return 200, 'Dependencies are valid', None if not isinstance(data, dict): return 422, None, "Failed to parse appliance request format: %s"%type(data) missing = Appliance.REQUIRED - data.keys() if missing: return 400, None, "Missing required field(s) of appliance: %s"%missing fields = {} # instantiate container objects containers, contr_ids = [], set() for c in data.pop('containers', []): if c['id'] in contr_ids: return 400, None, "Duplicate container id: %s"%c['id'] if from_user: for unwanted_f in ('appliance', ): c.pop(unwanted_f, None) status, contr, err = Container.parse(dict(**c, appliance=data['id']), from_user) if status != 200: return status, None, err containers.append(contr) contr_ids.add(contr.id) addresses = set() for c in containers: if c.cmd: addresses.update(get_short_ids(c.cmd)) for arg in c.args: addresses.update(get_short_ids(arg)) for v in c.env.values(): addresses.update(get_short_ids(v)) undefined = list(addresses - contr_ids) if undefined: return 400, None, "Undefined container(s): %s"%undefined status, msg, err = validate_dependencies(containers) if status != 200: return status, None, err fields.update(containers=containers) # instantiate data persistence object if 'data_persistence' in data: status, dp, err = DataPersistence.parse(dict(**data.pop('data_persistence', {}), appliance=data['id']), from_user) if status != 200: return status, None, err fields.update(data_persistence=dp) # instantiate scheduler object if 'scheduler' in data: status, scheduler, err = Scheduler.parse(data.pop('scheduler', {}), from_user) if status != 200: return status, None, err fields.update(scheduler=scheduler) return 200, Appliance(**fields, **data), None
def to_excel(self, excel_writer='output.xlsx', sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=False, index_label=None, startrow=0, startcol=0, merge_cells=True, encoding=None, inf_rep='inf', allow_protection=False, right_to_left=False, columns_to_hide=None, row_to_add_filters=None, columns_and_rows_to_freeze=None): """Saves the dataframe to excel and applies the styles. :param right_to_left: sets the sheet to be right to left. :param columns_to_hide: single column, list or tuple of columns to hide, may be column index (starts from 1) column name or column letter. :param allow_protection: allow to protect the sheet and the cells that specified as protected. :param row_to_add_filters: add filters to the given row, starts from zero (zero is to add filters to columns). :param columns_and_rows_to_freeze: column and row string to freeze for example: C3 will freeze columns: A,B and rows: 1,2. See Pandas' to_excel documentation about the other parameters """ def get_values(x): if isinstance(x, Container): return x.value else: try: if np.isnan(x): return na_rep else: return x except TypeError: return x def get_column_as_letter(column_to_convert): if not isinstance(column_to_convert, (int, basestring if PY2 else str, Container)): raise TypeError( "column must be an index, column letter or column name") column_as_letter = None if column_to_convert in self.data_df.columns: # column name column_index = self.data_df.columns.get_loc( column_to_convert ) + startcol + 1 # worksheet columns index start from 1 column_as_letter = cell.get_column_letter(column_index) elif isinstance(column_to_convert, int) and column_to_convert >= 1: # column index column_as_letter = cell.get_column_letter(startcol + column_to_convert) elif column_to_convert in sheet.column_dimensions: # column letter column_as_letter = column_to_convert if column_as_letter is None or column_as_letter not in sheet.column_dimensions: raise IndexError("column: %s is out of columns range." % column_to_convert) return column_as_letter def get_range_of_cells_for_specific_row(row_index): start_letter = get_column_as_letter( column_to_convert=self.data_df.columns[0]) end_letter = get_column_as_letter( column_to_convert=self.data_df.columns[-1]) return '{start_letter}{start_index}:{end_letter}{end_index}'.format( start_letter=start_letter, start_index=startrow + row_index + 1, end_letter=end_letter, end_index=startrow + row_index + 1) if len(self.data_df) > 0: export_df = self.data_df.applymap(get_values) else: export_df = deepcopy(self.data_df) export_df.columns = [col.value for col in export_df.columns] # noinspection PyTypeChecker export_df.index = [row_index.value for row_index in export_df.index] if isinstance(excel_writer, basestring if PY2 else str): excel_writer = self.ExcelWriter(excel_writer) export_df.to_excel(excel_writer, sheet_name=sheet_name, na_rep=na_rep, float_format=float_format, index=index, columns=columns, header=header, index_label=index_label, startrow=startrow, startcol=startcol, engine='openpyxl', merge_cells=merge_cells, encoding=encoding, inf_rep=inf_rep) sheet = excel_writer.book.get_sheet_by_name(sheet_name) sheet.sheet_view.rightToLeft = right_to_left self.data_df.fillna(Container('NaN'), inplace=True) if index: for row_index, index in enumerate(self.data_df.index): sheet.cell(row=startrow + row_index + 2, column=startcol + 1).style = index.style startcol += 1 if header and not self._custom_headers_style: self.apply_headers_style(Styler.default_header_style()) # Iterating over the dataframe's elements and applying their styles # openpyxl's rows and cols start from 1,1 while the dataframe is 0,0 for col_index, column in enumerate(self.data_df.columns): sheet.cell(row=startrow + 1, column=col_index + startcol + 1).style = column.style for row_index, index in enumerate(self.data_df.index): current_cell = sheet.cell(row=row_index + startrow + 2, column=col_index + startcol + 1) try: if PY2: if '=HYPERLINK' in unicode(current_cell.value): current_bg_color = current_cell.style.fill.fgColor.rgb current_font_size = current_cell.style.font.size current_cell.style = Styler( bg_color=current_bg_color, font_color=utils.colors.blue, font_size=current_font_size, number_format=utils.number_formats.general, underline=utils.underline.single).create_style( ) else: current_cell.style = self.data_df.loc[index, column].style else: if '=HYPERLINK' in str(current_cell.value): current_bg_color = current_cell.style.fill.fgColor.rgb current_font_size = current_cell.style.font.size current_cell.style = Styler( bg_color=current_bg_color, font_color=utils.colors.blue, font_size=current_font_size, number_format=utils.number_formats.general, underline='single').create_style() else: current_cell.style = self.data_df.loc[index, column].style except AttributeError: # if the element in the dataframe is not Container creating a default style current_cell.style = Styler().create_style() for column in self._columns_width: column_letter = get_column_as_letter(column_to_convert=column) sheet.column_dimensions[column_letter].width = self._columns_width[ column] for row in self._rows_height: if row + startrow in sheet.row_dimensions: sheet.row_dimensions[startrow + row].height = self._rows_height[row] else: raise IndexError('row: {} is out of range'.format(row)) if row_to_add_filters is not None: try: row_to_add_filters = int(row_to_add_filters) if (row_to_add_filters + startrow + 1) not in sheet.row_dimensions: raise IndexError('row: {} is out of rows range'.format( row_to_add_filters)) sheet.auto_filter.ref = get_range_of_cells_for_specific_row( row_index=row_to_add_filters) except (TypeError, ValueError): raise TypeError("row must be an index and not {}".format( type(row_to_add_filters))) if columns_and_rows_to_freeze is not None: if not isinstance(columns_and_rows_to_freeze, basestring if PY2 else str) or len(columns_and_rows_to_freeze) < 2: raise TypeError( "columns_and_rows_to_freeze must be a str for example: 'C3'" ) if columns_and_rows_to_freeze[0] not in sheet.column_dimensions: raise IndexError("column: %s is out of columns range." % columns_and_rows_to_freeze[0]) if int(columns_and_rows_to_freeze[1]) not in sheet.row_dimensions: raise IndexError("row: %s is out of rows range." % columns_and_rows_to_freeze[1]) sheet.freeze_panes = sheet[columns_and_rows_to_freeze] if allow_protection: sheet.protection.autoFilter = False sheet.protection.enable() # Iterating over the columns_to_hide and check if the format is columns name, column index as number or letter if columns_to_hide: if not isinstance(columns_to_hide, (list, tuple)): columns_to_hide = [columns_to_hide] for column in columns_to_hide: column_letter = get_column_as_letter(column_to_convert=column) sheet.column_dimensions[column_letter].hidden = True return excel_writer
def test_check_if_layer_not_filled(): container = Container(10, 10) container.floor.extend([(x, 0) for x in range(5)]) container.check_if_layer_filled() assert container.floor == [(x, 0) for x in range(10)] + [(x, 0) for x in range(5)]
# encoding: utf-8 from selenium import webdriver from selenium.webdriver.common.keys import Keys from nose.tools import * from readability import * from container import Container from activities import Activities from pymongo import MongoClient Browser = webdriver.Chrome Browser.find = Browser.find_element_by_css_selector page = Container({ 'root': 'http://localhost:5000/', 'experiment': 'http://localhost:5000/experiment.html', 'steuerung': 'http://localhost:5000/steuerung.html', 'restart': 'http://localhost:5000/restart.html', 'end': 'http://localhost:5000/end.html', }) browser = None S = lambda x: None def setup(): global browser, S browser = Browser() S = browser.find def teardown():
def setup_items(self, game): # --------------- Common effects of commands def update_score(game, points): game.score += points def update_health(player, points): player.health += points def make_creature_hostile(creature): creature.become_hostile() def instant_death(player): player.health = 0 def lose_item(player, item): player.inventory.remove_item(item) def end_section(name, game, player, points): update_score(game, points) result = Result( "Congratulations! You have finished {}. ".format(name)) status = game.status() result.append(status.get_message()) return result # ---------------- Create basic locations and objects player = game.player crumbly_room = Location( game, name='Crumbly Room', description='A small storage room with crumbling plaster walls') paneled_room = Location( game, name='Wood Paneled Room', description='A large, warm room with wood-paneled walls') north_tower = Location( game, name='North Tower', description='A tower with a high ceiling and red-stained windows') balcony = Location( game, name='Balcony', description= 'A breezy, open balcony with a beautiful view of the landscape below', traits=Traits(precarious=True)) east_tower = Location( game, name='East Tower', description='The tall tower at the eastern side of the house') roof = Location( game, name='Roof', description='You are on the roof of the eastern tower. ' + 'There is a ladder leading back downwards, and to the west is an open window.', traits=Traits(precarious=True)) west_tower = Location( game, name='West Tower', description='The tall tower at the western side of the house.') master_bedroom = Location( game, 'Master Bedroom', description= 'This appears to be a former bedroom, but the bed itself is missing. ' + 'A window to the east is open.') basement = Location(game, 'Basement', description='An empty room, very drafty') garden = Location(game, 'garden', description='a lush blooming garden') patio = Location(game, 'patio', description='an empty stone patio') front_porch = Location( game, 'porch', description= 'The front porch of the house. A metal gate prevents you from leaving' ) front_porch.add_modifier('front') metal_gate = Surface( game, name='gate', description= 'An impassable metal gate with two locks: one golden and one bronze, ' + 'blocking your exit!') metal_gate.traits.closed = True metal_gate.add_modifier('metal') front_porch.add_item(metal_gate) golden_lock = Door(game, name='lock', description='a golden lock') golden_lock.add_modifier('golden') metal_gate.add_item(golden_lock, force=True) bronze_lock = Door(game, name='lock', description='a bronze lock') bronze_lock.add_modifier('bronze') metal_gate.add_item(bronze_lock, force=True) street = Location(game, 'street', description='an empty street') fancy_painting = Item( game, name='painting', description='An ornate painting of the house\'s previous owner', aliases=['portrait', 'picture'], size=15, value=100) fancy_painting.add_modifier('fancy') west_tower.add_item(fancy_painting) east_tower.add_exit(direction.west, paneled_room) crumbly_room.add_exit(direction.north, paneled_room) paneled_room.add_exit(direction.south, crumbly_room) paneled_room.add_exit(direction.north, north_tower) paneled_room.add_exit(direction.east, east_tower) paneled_room.add_exit(direction.west, west_tower) west_tower.add_exit(direction.east, paneled_room) roof.add_exit(direction.west, master_bedroom) master_bedroom.add_exit(direction.down, basement) master_bedroom.add_exit(direction.east, roof) basement.add_exit(direction.up, master_bedroom) basement.add_exit(direction.west, garden) garden.add_exit(direction.east, basement) garden.add_exit(direction.south, patio) patio.add_exit(direction.north, garden) patio.add_exit(direction.south, front_porch) front_porch.add_exit(direction.north, patio) front_porch.add_exit( direction.south, street, condition=lambda g, p: not metal_gate.traits.closed, after=lambda g, p, l, d: end_section("section one", g, p, 50), fail_result=Failure("The metal gate blocks your way")) def too_small_check(g, p): return p.inventory.used_capacity() <= 25 too_small_result = Failure( "Your load is too large to fit through the small hole") east_tower.add_exit( direction.up, roof, description='A ladder leads up to a hole in the ceiling far above', condition=too_small_check, fail_result=too_small_result) roof.add_exit( direction.down, east_tower, description="There is a hole here leading down to the tower below", condition=too_small_check, fail_result=too_small_result) sturdy_door = Door( game, name='door', description= 'A sturdy door leading out to the balcony above the tower') sturdy_door.add_modifier('sturdy') silver_key = Key(game, name='key', description='A brilliant silver key') silver_key.add_modifier('silver') steel_key = Key(game, name='key', description='A small steel key') steel_key.add_modifier('steel') steel_key.set_lockable(sturdy_door) roof.add_item(steel_key) north_tower.add_item(sturdy_door) north_tower.add_exit(direction.south, paneled_room) north_tower.add_exit( direction.up, balcony, description="Stairs lead up to a door high above", condition=lambda g, p: not sturdy_door.traits.closed, fail_result=Failure("A sturdy door blocks the way")) balcony.add_exit(direction.down, north_tower) light_thing = Item( game, name='thing', description='An easily carried thing, light as a feather', size=0) light_thing.add_modifier('light') fragile_thing = Item(game, name='thing', description='An easily breakable, delicate thing', traits=Traits(fragile=True), size=15) fragile_thing.add_modifier('fragile') heavy_thing = Item( game, name='thing', description='A heavy block of some unknown material', size=45) heavy_thing.add_modifier('heavy') trunk = Container(game, name='trunk', description='An old wooden trunk', aliases=['chest', 'box'], size=75, value=5, capacity=90) trunk.add_modifier('wooden') sword = Weapon(game, name='sword', description='A serviceable iron sword', size=15, value=15, damage=50, defense=10, accuracy=80) sword.add_modifier('iron') trunk.add_item(sword, force=True) diamond = Item(game, name='diamond', aliases=['gem', 'jewel'], size=5, value=100, description='A brilliant diamond') apple = Edible(game, name='apple', description='A delicious, juicy red apple', size=15, value=5) small_table = Surface(game, name='table', description='A small table', size=20, capacity=15) small_table.add_modifier('small') small_table.add_item(apple, force=True) large_table = Surface(game, name='table', description='A large table', size=75, capacity=100) large_table.add_modifier('large') large_table.add_item(heavy_thing, force=True) large_table.add_item(light_thing, force=True) large_table.add_item(fragile_thing, force=True) bread = Edible(game, name='bread', description='A loaf of crusty brown bread', size=20, value=5, healing=10) puddle = Drinkable(game, name='puddle', aliases=['water'], description='A puddle of refreshing water', size=25, value=5, healing=15) mouse = Item( game, name='mouse', description='A small mouse scampers back and forth across the ' + 'room here, searching for food. It is carrying something ' 'shiny in its mouth.', traits=Traits(compelling=True), size=0, value=0) mouse.add_modifier('brown') west_tower.add_item(mouse) core = Item(game, name='core', description='The core of an eaten apple', size=5, value=0) core.add_modifier('apple') apple.add_consumed(core) crumbs = Edible(game, name='crumbs', description='A small pile of leftover bread crumbs', aliases=['pile'], traits=Traits(composite=True, plural=True), size=5, value=0, healing=0) bread.add_consumed(crumbs) mud = Item(game, name='mud', description='A clump of soggy wet mud', traits=Traits(composite=True), size=15, value=1) puddle.add_consumed(mud) vase = Container(game, name='flowerpot', description='a patterned flowerpot', aliases=['flowerpot', 'pot', 'vase'], traits=Traits(closed=False, fragile=True), size=5, value=10, capacity=3) flower = Item(game, name='flower', description='a beautiful, fragrant sunflower', size=3, value=5) crumbly_room.add_item(small_table) crumbly_room.add_item(large_table) paneled_room.add_item(trunk) paneled_room.add_item(puddle) vase.add_item(flower) balcony.add_item(vase) villager = Creature( game, name='villager', traits=Traits(mobile=True), aliases=['farmer'], description="A stout but simple villager in farming garb", health=75, strength=25, dexterity=65, location=paneled_room) villager.add_wanted_item(apple) villager.add_item(diamond) golden_key = Key(game, name='key', description='A fashionable golden key') golden_key.add_modifier('golden') golden_key.set_lockable(golden_lock) red_fox = Creature(game, name='fox', traits=Traits(hostile=True, mobile=False), description="a bloodthirsty red fox", health=65, strength=15, dexterity=50, location=front_porch) red_fox.add_modifier('red') red_fox.add_item(golden_key) bronze_key = Key(game, name='key', description='A dull bronze key') bronze_key.add_modifier('bronze') bronze_key.set_lockable(bronze_lock) brown_fox = Creature(game, name='fox', traits=Traits(hostile=True, mobile=False), description="a vicious brown fox", health=65, strength=25, dexterity=50, location=front_porch) brown_fox.add_modifier('brown') red_fox.add_item(bronze_key) townsfolk = Creature( game, name='townsfolk', traits=Traits(mobile=True), description='A short, well-dressed man with a stubbly beard', aliases=['folk', 'man'], health=75, strength=30, dexterity=65, location=north_tower) townsfolk.add_wanted_item(diamond) townsfolk.add_item(bread) def shadow_action(game, player): player.health -= 5 return Result("A dark shadow looms ominously in the corner") shadow = Creature( game, name='shadow', traits=Traits(hostile=False, mobile=True, evident=False), description= 'You attempt to examine the shadow, but your vision blurs as you try to focus ' 'on its constantly shifting shape, preventing you from forming ' 'any clear impression', health=9001, strength=20, dexterity=90, location=east_tower) shadow.add_modifier('dark') shadow.entry_action = lambda g, p: Result( "A dark shadow enters. The temperature in the room drops " "several degrees, as does your blood") shadow.exit_action = lambda g, p: Result( "The shadow leaves the room, and you once again find " "you can breathe freely") shadow.present_action = shadow_action # -------- Consequences: game milestones and achievements, and special results vocabulary = game.vocabulary open = vocabulary.lookup_verb_by_name('open') get = vocabulary.lookup_verb_by_name('get') ask = vocabulary.lookup_verb_by_name('ask') smell = vocabulary.lookup_verb_by_name('smell') jump = vocabulary.lookup_verb_by_name('jump') drop = vocabulary.lookup_verb_by_name('drop') throw = vocabulary.lookup_verb_by_name('throw') kill = vocabulary.lookup_verb_by_name('kill') unlock = vocabulary.lookup_verb_by_name('unlock') # Trying to pick up creatures turns them hostile for creature in vocabulary.get_objects_of_class(Creature): get.add_consequence(schema=Schema(roles={ Role.AGENT: player, Role.THEME: creature }), necessary_result=result.GENERIC_FAILURE, effect=lambda schema: make_creature_hostile( schema[Role.THEME])) # Be careful in precarious places! for room in vocabulary.get_objects_of_class(Location): if room.traits.precarious: jump.add_consequence( schema=Schema(roles={Role.AGENT: player}), necessary_result=result.GENERIC_SUCCESS, necessary_location=room, effect=lambda schema: instant_death(player), consequent_result=Success( "In your excitement, you slip and fall to the hard ground far below!\n" + "You should probably be more careful where you do your jumping." )) # TODO: Some kind of pattern-matching logic here. This configures for _no_ theme, not _any_ theme ... throw.add_consequence( schema=Schema(roles={Role.AGENT: player}), necessary_result=result.GENERIC_FAILURE, necessary_location=room, effect=lambda schema: lose_item(player, schema[Role.THEME] ), consequent_result=Failure( "You toss it carelessly, and it sails over the edge and out of sight" )) # The mouse is too fast to catch or kill, but it's hungry def fed_mouse(crumbs): west_tower.remove_item(mouse) west_tower.remove_item(crumbs) west_tower.add_item(silver_key) get.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.THEME: mouse }), necessary_result=result.GENERIC_SUCCESS, necessary_location=west_tower, effect=lambda schema: player.drop(mouse), consequent_result=Failure( "You try, but the mouse is far too small and fast for you to catch!" )) drop.add_consequence(schema=Schema(roles={ Role.AGENT: player, Role.THEME: crumbs }), necessary_result=result.GENERIC_SUCCESS, necessary_location=west_tower, effect=lambda schema: update_score(game, 20)) drop.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.THEME: crumbs }), necessary_result=result.GENERIC_SUCCESS, necessary_location=west_tower, effect=lambda schema: fed_mouse(crumbs), consequent_result=Success( "The mouse devours the crumbs, dropping something shiny to the floor in the " "process. It then returns to its hole, well-fed and content")) # Foxes work cooperatively! def killed_fox(dead_fox, other_fox, key): dead_fox.remove_item(key) if other_fox.is_alive: other_fox.add_item(key) return result.GENERIC_SUCCESS else: return result.GENERIC_FAILURE kill.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.THEME: red_fox }), necessary_result=result.GENERIC_SUCCESS, effect=killed_fox(red_fox, brown_fox, golden_key), consequent_result=Success( "As the red fox falls dead to the ground, its brother retrieves " "the golden key from its lifeless form")) kill.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.THEME: brown_fox }), necessary_result=result.GENERIC_SUCCESS, effect=killed_fox(brown_fox, red_fox, bronze_key), consequent_result=Success( "As the brown fox falls dead to the ground, its brother retrieves " "the bronze key from its lifeless form")) # Achievement: unlock and open the sturdy door open.add_consequence(schema=Schema(roles={ Role.AGENT: player, Role.PATIENT: sturdy_door }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: update_score(game, 10)) # Achievement: get the diamond from the villager ask.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.PATIENT: villager, Role.THEME: diamond }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: update_score(game, 20)) get.add_consequence(schema=Schema(roles={ Role.AGENT: player, Role.THEME: diamond }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: update_score(game, 20)) get.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.PATIENT: villager, Role.THEME: diamond }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: update_score(game, 20)) # Health bonus: smell the sunflower smell.add_consequence( schema=Schema(roles={ Role.AGENT: player, Role.THEME: flower }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: update_health(player, 10), consequent_result=Success( "You feel revived by the bloom's invigorating fragrance")) def unlock_gate(this_lock, other_lock): this_lock.traits.locked = False if other_lock.traits.locked: return result.GENERIC_FAILURE else: update_score(game, 50) metal_gate.traits.closed = False return result.GENERIC_SUCCESS unlock.add_consequence( schema=Schema( roles={ Role.AGENT: player, Role.THEME: golden_lock, Role.INSTRUMENT: golden_key }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: unlock_gate(golden_lock, bronze_lock), consequent_result=WON_GAME) unlock.add_consequence( schema=Schema( roles={ Role.AGENT: player, Role.THEME: golden_lock, Role.INSTRUMENT: golden_key }), necessary_result=result.GENERIC_SUCCESS, effect=lambda schema: unlock_gate(golden_lock, bronze_lock), consequent_result=WON_GAME) # Start game in crumbly room return crumbly_room
def list_all_containers( user_list='ALL', container_opts={}, ): """ Returns a list of all running containers, as `Container` objects. A running container is defined as a process subtree with the `pid` namespace different to the `init` process `pid` namespace. """ all_docker_containers = list_docker_containers(container_opts) if user_list in ['ALL', 'all', 'All']: init_ns = namespace.get_pid_namespace(1) visited_ns = set() # visited PID namespaces # Start with all docker containers for container in all_docker_containers: curr_ns = namespace.get_pid_namespace(container.pid) if not curr_ns: continue if curr_ns not in visited_ns and curr_ns != init_ns: visited_ns.add(curr_ns) try: yield container except ContainerInvalidEnvironment as e: logger.exception(e) # Continue with all other containers not known to docker for p in psutil.process_iter(): pid = (p.pid() if hasattr(p.pid, '__call__') else p.pid) if pid == 1 or pid == '1': # don't confuse the init process as a container continue if misc.process_is_crawler(pid): # don't confuse the crawler process with a container continue curr_ns = namespace.get_pid_namespace(pid) if not curr_ns: # invalid container continue if curr_ns not in visited_ns and curr_ns != init_ns: visited_ns.add(curr_ns) yield Container(pid) else: # User provided a list of containers user_containers = user_list.split(',') for container in all_docker_containers: short_id_match = container.short_id in user_containers long_id_match = container.long_id in user_containers if short_id_match or long_id_match: yield container
def container_init(): global container container = Container()
def initContainer(self): self.animalContainer = Container()
def testInsertContainerSmoke(self): c = Container("101010") return self.dao.insertContainer(c)
async def get_containers(self, **filters): return [ Container.parse(c, False)[1] async for c in self.__contr_col.find(filters) ]
def __init__(self, brick_weight, max_container_weight): self._container = Container(max_container_weight) self._brick_weight = brick_weight self._max_container_weight = max_container_weight