signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def __init__(self, agent_interface_format=None, map_size=None):
if not agent_interface_format:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._agent_interface_format = agent_interface_format<EOL>aif = self._agent_interface_format<EOL>if (aif.use_feature_units<EOL>or aif.use_camera_position<EOL>or aif.use_raw_units):<EOL><INDENT>self.init_camera(<EOL>aif.feature_dimensions,<EOL>map_size,<EOL>aif.camera_width_world_units)<EOL><DEDENT>self._valid_functions = _init_valid_functions(<EOL>aif.action_dimensions)<EOL>
Initialize a Features instance matching the specified interface format. Args: agent_interface_format: See the documentation for `AgentInterfaceFormat`. map_size: The size of the map in world units, needed for feature_units. Raises: ValueError: if agent_interface_format isn't specified. ValueError: if map_size isn't specified when use_feature_units or use_camera_position is.
f1614:c18:m0
def init_camera(<EOL>self, feature_dimensions, map_size, camera_width_world_units):
if not map_size or not camera_width_world_units:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>map_size = point.Point.build(map_size)<EOL>self._world_to_world_tl = transform.Linear(point.Point(<NUM_LIT:1>, -<NUM_LIT:1>),<EOL>point.Point(<NUM_LIT:0>, map_size.y))<EOL>self._world_tl_to_world_camera_rel = transform.Linear(offset=-map_size / <NUM_LIT:4>)<EOL>world_camera_rel_to_feature_screen = transform.Linear(<EOL>feature_dimensions.screen / camera_width_world_units,<EOL>feature_dimensions.screen / <NUM_LIT:2>)<EOL>self._world_to_feature_screen_px = transform.Chain(<EOL>self._world_to_world_tl,<EOL>self._world_tl_to_world_camera_rel,<EOL>world_camera_rel_to_feature_screen,<EOL>transform.PixelToCoord())<EOL>
Initialize the camera (especially for feature_units). This is called in the constructor and may be called repeatedly after `Features` is constructed, since it deals with rescaling coordinates and not changing environment/action specs. Args: feature_dimensions: See the documentation in `AgentInterfaceFormat`. map_size: The size of the map in world units. camera_width_world_units: See the documentation in `AgentInterfaceFormat`. Raises: ValueError: If map_size or camera_width_world_units are falsey (which should mainly happen if called by the constructor).
f1614:c18:m1
def _update_camera(self, camera_center):
self._world_tl_to_world_camera_rel.offset = (<EOL>-self._world_to_world_tl.fwd_pt(camera_center) *<EOL>self._world_tl_to_world_camera_rel.scale)<EOL>
Update the camera transform based on the new camera center.
f1614:c18:m2
def observation_spec(self):
obs_spec = named_array.NamedDict({<EOL>"<STR_LIT>": (<NUM_LIT:0>,), <EOL>"<STR_LIT>": (<NUM_LIT:0>,), <EOL>"<STR_LIT>": (<NUM_LIT:0>,),<EOL>"<STR_LIT>": (<NUM_LIT:0>, len(UnitLayer)), <EOL>"<STR_LIT>": (<NUM_LIT:0>, len(UnitLayer)), <EOL>"<STR_LIT>": (<NUM_LIT:1>,),<EOL>"<STR_LIT>": (<NUM_LIT:10>, <NUM_LIT:2>),<EOL>"<STR_LIT>": (<NUM_LIT:1>,),<EOL>"<STR_LIT>": (<NUM_LIT:0>,),<EOL>"<STR_LIT>": (<NUM_LIT:0>, len(UnitLayer)), <EOL>"<STR_LIT>": (len(Player),), <EOL>"<STR_LIT>": (len(ScoreCumulative),), <EOL>"<STR_LIT>": (len(ScoreByCategory), len(ScoreCategories)), <EOL>"<STR_LIT>": (len(ScoreByVital), len(ScoreVitals)), <EOL>"<STR_LIT>": (<NUM_LIT:0>, len(UnitLayer)), <EOL>})<EOL>aif = self._agent_interface_format<EOL>if aif.feature_dimensions:<EOL><INDENT>obs_spec["<STR_LIT>"] = (len(SCREEN_FEATURES),<EOL>aif.feature_dimensions.screen.y,<EOL>aif.feature_dimensions.screen.x)<EOL>obs_spec["<STR_LIT>"] = (len(MINIMAP_FEATURES),<EOL>aif.feature_dimensions.minimap.y,<EOL>aif.feature_dimensions.minimap.x)<EOL><DEDENT>if aif.rgb_dimensions:<EOL><INDENT>obs_spec["<STR_LIT>"] = (aif.rgb_dimensions.screen.y,<EOL>aif.rgb_dimensions.screen.x,<EOL><NUM_LIT:3>)<EOL>obs_spec["<STR_LIT>"] = (aif.rgb_dimensions.minimap.y,<EOL>aif.rgb_dimensions.minimap.x,<EOL><NUM_LIT:3>)<EOL><DEDENT>if aif.use_feature_units:<EOL><INDENT>obs_spec["<STR_LIT>"] = (<NUM_LIT:0>, len(FeatureUnit)) <EOL><DEDENT>if aif.use_raw_units:<EOL><INDENT>obs_spec["<STR_LIT>"] = (<NUM_LIT:0>, len(FeatureUnit))<EOL><DEDENT>if aif.use_unit_counts:<EOL><INDENT>obs_spec["<STR_LIT>"] = (<NUM_LIT:0>, len(UnitCounts))<EOL><DEDENT>if aif.use_camera_position:<EOL><INDENT>obs_spec["<STR_LIT>"] = (<NUM_LIT:2>,)<EOL><DEDENT>return obs_spec<EOL>
The observation spec for the SC2 environment. It's worth noting that the image-like observations are in y,x/row,column order which is different than the actions which are in x,y order. This is due to conflicting conventions, and to facilitate printing of the images. Returns: The dict of observation names to their tensor shapes. Shapes with a 0 can vary in length, for example the number of valid actions depends on which units you have selected.
f1614:c18:m3
def action_spec(self):
return self._valid_functions<EOL>
The action space pretty complicated and fills the ValidFunctions.
f1614:c18:m4
@sw.decorate<EOL><INDENT>def transform_obs(self, obs):<DEDENT>
empty = np.array([], dtype=np.int32).reshape((<NUM_LIT:0>, <NUM_LIT:7>))<EOL>out = named_array.NamedDict({ <EOL>"<STR_LIT>": empty,<EOL>"<STR_LIT>": empty,<EOL>"<STR_LIT>": empty,<EOL>"<STR_LIT>": empty,<EOL>"<STR_LIT>": np.array([<NUM_LIT:0>], dtype=np.int32),<EOL>})<EOL>def or_zeros(layer, size):<EOL><INDENT>if layer is not None:<EOL><INDENT>return layer.astype(np.int32, copy=False)<EOL><DEDENT>else:<EOL><INDENT>return np.zeros((size.y, size.x), dtype=np.int32)<EOL><DEDENT><DEDENT>aif = self._agent_interface_format<EOL>if aif.feature_dimensions:<EOL><INDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>np.stack(or_zeros(f.unpack(obs.observation),<EOL>aif.feature_dimensions.screen)<EOL>for f in SCREEN_FEATURES),<EOL>names=[ScreenFeatures, None, None])<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>np.stack(or_zeros(f.unpack(obs.observation),<EOL>aif.feature_dimensions.minimap)<EOL>for f in MINIMAP_FEATURES),<EOL>names=[MinimapFeatures, None, None])<EOL><DEDENT>if aif.rgb_dimensions:<EOL><INDENT>out["<STR_LIT>"] = Feature.unpack_rgb_image(<EOL>obs.observation.render_data.map).astype(np.int32)<EOL>out["<STR_LIT>"] = Feature.unpack_rgb_image(<EOL>obs.observation.render_data.minimap).astype(np.int32)<EOL><DEDENT>out["<STR_LIT>"] = np.array(<EOL>[self.reverse_action(a).function for a in obs.actions],<EOL>dtype=np.int32)<EOL>out["<STR_LIT>"] = np.array([o.result for o in obs.action_errors],<EOL>dtype=np.int32)<EOL>out["<STR_LIT>"] = np.array(obs.observation.alerts, dtype=np.int32)<EOL>out["<STR_LIT>"] = np.array([obs.observation.game_loop], dtype=np.int32)<EOL>score_details = obs.observation.score.score_details<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray([<EOL>obs.observation.score.score,<EOL>score_details.idle_production_time,<EOL>score_details.idle_worker_time,<EOL>score_details.total_value_units,<EOL>score_details.total_value_structures,<EOL>score_details.killed_value_units,<EOL>score_details.killed_value_structures,<EOL>score_details.collected_minerals,<EOL>score_details.collected_vespene,<EOL>score_details.collection_rate_minerals,<EOL>score_details.collection_rate_vespene,<EOL>score_details.spent_minerals,<EOL>score_details.spent_vespene,<EOL>], names=ScoreCumulative, dtype=np.int32)<EOL>def get_score_details(key, details, categories):<EOL><INDENT>row = getattr(details, key.name)<EOL>return [getattr(row, category.name) for category in categories]<EOL><DEDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray([<EOL>get_score_details(key, score_details, ScoreCategories)<EOL>for key in ScoreByCategory<EOL>], names=[ScoreByCategory, ScoreCategories], dtype=np.int32)<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray([<EOL>get_score_details(key, score_details, ScoreVitals)<EOL>for key in ScoreByVital<EOL>], names=[ScoreByVital, ScoreVitals], dtype=np.int32)<EOL>player = obs.observation.player_common<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray([<EOL>player.player_id,<EOL>player.minerals,<EOL>player.vespene,<EOL>player.food_used,<EOL>player.food_cap,<EOL>player.food_army,<EOL>player.food_workers,<EOL>player.idle_worker_count,<EOL>player.army_count,<EOL>player.warp_gate_count,<EOL>player.larva_count,<EOL>], names=Player, dtype=np.int32)<EOL>def unit_vec(u):<EOL><INDENT>return np.array((<EOL>u.unit_type,<EOL>u.player_relative,<EOL>u.health,<EOL>u.shields,<EOL>u.energy,<EOL>u.transport_slots_taken,<EOL>int(u.build_progress * <NUM_LIT:100>), <EOL>), dtype=np.int32)<EOL><DEDENT>ui = obs.observation.ui_data<EOL>with sw("<STR_LIT>"):<EOL><INDENT>groups = np.zeros((<NUM_LIT:10>, <NUM_LIT:2>), dtype=np.int32)<EOL>for g in ui.groups:<EOL><INDENT>groups[g.control_group_index, :] = (g.leader_unit_type, g.count)<EOL><DEDENT>out["<STR_LIT>"] = groups<EOL>if ui.single:<EOL><INDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(ui.single.unit)], [None, UnitLayer])<EOL><DEDENT>if ui.multi and ui.multi.units:<EOL><INDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(u) for u in ui.multi.units], [None, UnitLayer])<EOL><DEDENT>if ui.cargo and ui.cargo.passengers:<EOL><INDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(ui.single.unit)], [None, UnitLayer])<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(u) for u in ui.cargo.passengers], [None, UnitLayer])<EOL>out["<STR_LIT>"] = np.array([ui.cargo.slots_available],<EOL>dtype=np.int32)<EOL><DEDENT>if ui.production and ui.production.build_queue:<EOL><INDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(ui.production.unit)], [None, UnitLayer])<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>[unit_vec(u) for u in ui.production.build_queue],<EOL>[None, UnitLayer])<EOL><DEDENT><DEDENT>def full_unit_vec(u, pos_transform, is_raw=False):<EOL><INDENT>screen_pos = pos_transform.fwd_pt(<EOL>point.Point.build(u.pos))<EOL>screen_radius = pos_transform.fwd_dist(u.radius)<EOL>return np.array((<EOL>u.unit_type,<EOL>u.alliance, <EOL>u.health,<EOL>u.shield,<EOL>u.energy,<EOL>u.cargo_space_taken,<EOL>int(u.build_progress * <NUM_LIT:100>), <EOL>int(u.health / u.health_max * <NUM_LIT:255>) if u.health_max > <NUM_LIT:0> else <NUM_LIT:0>,<EOL>int(u.shield / u.shield_max * <NUM_LIT:255>) if u.shield_max > <NUM_LIT:0> else <NUM_LIT:0>,<EOL>int(u.energy / u.energy_max * <NUM_LIT:255>) if u.energy_max > <NUM_LIT:0> else <NUM_LIT:0>,<EOL>u.display_type, <EOL>u.owner, <EOL>screen_pos.x,<EOL>screen_pos.y,<EOL>u.facing,<EOL>screen_radius,<EOL>u.cloak, <EOL>u.is_selected,<EOL>u.is_blip,<EOL>u.is_powered,<EOL>u.mineral_contents,<EOL>u.vespene_contents,<EOL>u.cargo_space_max,<EOL>u.assigned_harvesters,<EOL>u.ideal_harvesters,<EOL>u.weapon_cooldown,<EOL>len(u.orders),<EOL>u.tag if is_raw else <NUM_LIT:0><EOL>), dtype=np.int32)<EOL><DEDENT>raw = obs.observation.raw_data<EOL>if aif.use_feature_units:<EOL><INDENT>with sw("<STR_LIT>"):<EOL><INDENT>self._update_camera(point.Point.build(raw.player.camera))<EOL>feature_units = []<EOL>for u in raw.units:<EOL><INDENT>if u.is_on_screen and u.display_type != sc_raw.Hidden:<EOL><INDENT>feature_units.append(<EOL>full_unit_vec(u, self._world_to_feature_screen_px))<EOL><DEDENT><DEDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>feature_units, [None, FeatureUnit], dtype=np.int32)<EOL><DEDENT><DEDENT>if aif.use_raw_units:<EOL><INDENT>with sw("<STR_LIT>"):<EOL><INDENT>raw_units = [full_unit_vec(u, self._world_to_world_tl, is_raw=True)<EOL>for u in raw.units]<EOL>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>raw_units, [None, FeatureUnit], dtype=np.int32)<EOL><DEDENT><DEDENT>if aif.use_unit_counts:<EOL><INDENT>with sw("<STR_LIT>"):<EOL><INDENT>unit_counts = collections.defaultdict(int)<EOL>for u in raw.units:<EOL><INDENT>if u.alliance == sc_raw.Self:<EOL><INDENT>unit_counts[u.unit_type] += <NUM_LIT:1><EOL><DEDENT><DEDENT>out["<STR_LIT>"] = named_array.NamedNumpyArray(<EOL>sorted(unit_counts.items()), [None, UnitCounts], dtype=np.int32)<EOL><DEDENT><DEDENT>if aif.use_camera_position:<EOL><INDENT>camera_position = self._world_to_world_tl.fwd_pt(<EOL>point.Point.build(raw.player.camera))<EOL>out["<STR_LIT>"] = np.array((camera_position.x, camera_position.y),<EOL>dtype=np.int32)<EOL><DEDENT>out["<STR_LIT>"] = np.array(self.available_actions(obs.observation),<EOL>dtype=np.int32)<EOL>return out<EOL>
Render some SC2 observations into something an agent can handle.
f1614:c18:m5
@sw.decorate<EOL><INDENT>def available_actions(self, obs):<DEDENT>
available_actions = set()<EOL>hide_specific_actions = self._agent_interface_format.hide_specific_actions<EOL>for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE):<EOL><INDENT>if func.avail_fn(obs):<EOL><INDENT>available_actions.add(i)<EOL><DEDENT><DEDENT>for a in obs.abilities:<EOL><INDENT>if a.ability_id not in actions.ABILITY_IDS:<EOL><INDENT>logging.warning("<STR_LIT>", a.ability_id)<EOL>continue<EOL><DEDENT>for func in actions.ABILITY_IDS[a.ability_id]:<EOL><INDENT>if func.function_type in actions.POINT_REQUIRED_FUNCS[a.requires_point]:<EOL><INDENT>if func.general_id == <NUM_LIT:0> or not hide_specific_actions:<EOL><INDENT>available_actions.add(func.id)<EOL><DEDENT>if func.general_id != <NUM_LIT:0>: <EOL><INDENT>for general_func in actions.ABILITY_IDS[func.general_id]:<EOL><INDENT>if general_func.function_type is func.function_type:<EOL><INDENT>available_actions.add(general_func.id)<EOL>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return list(available_actions)<EOL>
Return the list of available action ids.
f1614:c18:m6
@sw.decorate<EOL><INDENT>def transform_action(self, obs, func_call, skip_available=False):<DEDENT>
func_id = func_call.function<EOL>try:<EOL><INDENT>func = actions.FUNCTIONS[func_id]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError("<STR_LIT>" % func_id)<EOL><DEDENT>if not (skip_available or func_id in self.available_actions(obs)):<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>func_id, func.name))<EOL><DEDENT>if len(func_call.arguments) != len(func.args):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>func, func_call.arguments))<EOL><DEDENT>aif = self._agent_interface_format<EOL>for t, arg in zip(func.args, func_call.arguments):<EOL><INDENT>if t.name in ("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>sizes = aif.action_dimensions.screen<EOL><DEDENT>elif t.name == "<STR_LIT>":<EOL><INDENT>sizes = aif.action_dimensions.minimap<EOL><DEDENT>else:<EOL><INDENT>sizes = t.sizes<EOL><DEDENT>if len(sizes) != len(arg):<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>" % (<EOL>func, func_call.arguments))<EOL><DEDENT>for s, a in zip(sizes, arg):<EOL><INDENT>if not <NUM_LIT:0> <= a < s:<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>func, func_call.arguments))<EOL><DEDENT><DEDENT><DEDENT>kwargs = {type_.name: type_.fn(a)<EOL>for type_, a in zip(func.args, func_call.arguments)}<EOL>sc2_action = sc_pb.Action()<EOL>kwargs["<STR_LIT:action>"] = sc2_action<EOL>kwargs["<STR_LIT>"] = aif.action_space<EOL>if func.ability_id:<EOL><INDENT>kwargs["<STR_LIT>"] = func.ability_id<EOL><DEDENT>actions.FUNCTIONS[func_id].function_type(**kwargs)<EOL>return sc2_action<EOL>
Tranform an agent-style action to one that SC2 can consume. Args: obs: a `sc_pb.Observation` from the previous frame. func_call: a `FunctionCall` to be turned into a `sc_pb.Action`. skip_available: If True, assume the action is available. This should only be used for testing or if you expect to make actions that weren't valid at the last observation. Returns: a corresponding `sc_pb.Action`. Raises: ValueError: if the action doesn't pass validation.
f1614:c18:m7
@sw.decorate<EOL><INDENT>def reverse_action(self, action):<DEDENT>
FUNCTIONS = actions.FUNCTIONS <EOL>aif = self._agent_interface_format<EOL>def func_call_ability(ability_id, cmd_type, *args):<EOL><INDENT>"""<STR_LIT>"""<EOL>if ability_id not in actions.ABILITY_IDS:<EOL><INDENT>logging.warning("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>", ability_id)<EOL>return FUNCTIONS.no_op()<EOL><DEDENT>if aif.hide_specific_actions:<EOL><INDENT>general_id = next(iter(actions.ABILITY_IDS[ability_id])).general_id<EOL>if general_id:<EOL><INDENT>ability_id = general_id<EOL><DEDENT><DEDENT>for func in actions.ABILITY_IDS[ability_id]:<EOL><INDENT>if func.function_type is cmd_type:<EOL><INDENT>return FUNCTIONS[func.id](*args)<EOL><DEDENT><DEDENT>raise ValueError("<STR_LIT>" % (<EOL>ability_id, cmd_type.__name__))<EOL><DEDENT>if action.HasField("<STR_LIT>"):<EOL><INDENT>act_ui = action.action_ui<EOL>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_unit(act_ui.multi_panel.type - <NUM_LIT:1>,<EOL>act_ui.multi_panel.unit_index)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_control_group(<EOL>act_ui.control_group.action - <NUM_LIT:1>,<EOL>act_ui.control_group.control_group_index)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_idle_worker(act_ui.select_idle_worker.type - <NUM_LIT:1>)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_army(act_ui.select_army.selection_add)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_warp_gates(<EOL>act_ui.select_warp_gates.selection_add)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.select_larva()<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.unload(act_ui.cargo_panel.unit_index)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return FUNCTIONS.build_queue(act_ui.production_panel.unit_index)<EOL><DEDENT>if act_ui.HasField("<STR_LIT>"):<EOL><INDENT>return func_call_ability(act_ui.toggle_autocast.ability_id,<EOL>actions.autocast)<EOL><DEDENT><DEDENT>if (action.HasField("<STR_LIT>") or<EOL>action.HasField("<STR_LIT>")):<EOL><INDENT>act_sp = actions.spatial(action, aif.action_space)<EOL>if act_sp.HasField("<STR_LIT>"):<EOL><INDENT>coord = point.Point.build(act_sp.camera_move.center_minimap)<EOL>return FUNCTIONS.move_camera(coord)<EOL><DEDENT>if act_sp.HasField("<STR_LIT>"):<EOL><INDENT>select_point = act_sp.unit_selection_point<EOL>coord = point.Point.build(select_point.selection_screen_coord)<EOL>return FUNCTIONS.select_point(select_point.type - <NUM_LIT:1>, coord)<EOL><DEDENT>if act_sp.HasField("<STR_LIT>"):<EOL><INDENT>select_rect = act_sp.unit_selection_rect<EOL>tl = point.Point.build(select_rect.selection_screen_coord[<NUM_LIT:0>].p0)<EOL>br = point.Point.build(select_rect.selection_screen_coord[<NUM_LIT:0>].p1)<EOL>return FUNCTIONS.select_rect(select_rect.selection_add, tl, br)<EOL><DEDENT>if act_sp.HasField("<STR_LIT>"):<EOL><INDENT>cmd = act_sp.unit_command<EOL>queue = int(cmd.queue_command)<EOL>if cmd.HasField("<STR_LIT>"):<EOL><INDENT>coord = point.Point.build(cmd.target_screen_coord)<EOL>return func_call_ability(cmd.ability_id, actions.cmd_screen,<EOL>queue, coord)<EOL><DEDENT>elif cmd.HasField("<STR_LIT>"):<EOL><INDENT>coord = point.Point.build(cmd.target_minimap_coord)<EOL>return func_call_ability(cmd.ability_id, actions.cmd_minimap,<EOL>queue, coord)<EOL><DEDENT>else:<EOL><INDENT>return func_call_ability(cmd.ability_id, actions.cmd_quick, queue)<EOL><DEDENT><DEDENT><DEDENT>if action.HasField("<STR_LIT>") or action.HasField("<STR_LIT>"):<EOL><INDENT>raise ValueError("<STR_LIT>" % action)<EOL><DEDENT>return FUNCTIONS.no_op()<EOL>
Transform an SC2-style action into an agent-style action. This should be the inverse of `transform_action`. Args: action: a `sc_pb.Action` to be transformed. Returns: A corresponding `actions.FunctionCall`. Raises: ValueError: if it doesn't know how to transform this action.
f1614:c18:m8
def run(self, funcs):
funcs = [f if callable(f) else functools.partial(*f) for f in funcs]<EOL>if len(funcs) == <NUM_LIT:1>: <EOL><INDENT>return [funcs[<NUM_LIT:0>]()]<EOL><DEDENT>if len(funcs) > self._workers: <EOL><INDENT>self.shutdown()<EOL>self._workers = len(funcs)<EOL>self._executor = futures.ThreadPoolExecutor(self._workers)<EOL><DEDENT>futs = [self._executor.submit(f) for f in funcs]<EOL>done, not_done = futures.wait(futs, self._timeout, futures.FIRST_EXCEPTION)<EOL>for f in done:<EOL><INDENT>if not f.cancelled() and f.exception() is not None:<EOL><INDENT>if not_done:<EOL><INDENT>for nd in not_done:<EOL><INDENT>nd.cancel()<EOL><DEDENT>self.shutdown(False) <EOL><DEDENT>raise f.exception()<EOL><DEDENT><DEDENT>return [f.result(timeout=<NUM_LIT:0>) for f in futs]<EOL>
Run a set of functions in parallel, returning their results. Make sure any function you pass exits with a reasonable timeout. If it doesn't return within the timeout or the result is ignored due an exception in a separate thread it will continue to stick around until it finishes, including blocking process exit. Args: funcs: An iterable of functions or iterable of args to functools.partial. Returns: A list of return values with the values matching the order in funcs. Raises: Propagates the first exception encountered in one of the functions.
f1615:c0:m1
def DEFINE_point(name, default, help):
flags.DEFINE(PointParser(), name, default, help)<EOL>
Registers a flag whose value parses as a point.
f1616:m0
def clean():
for build_dir in list(BUILD_DIRS) + [DOC_OUTPUT, DEV_DB_DIR]:<EOL><INDENT>local("<STR_LIT>" % build_dir)<EOL><DEDENT>
Clean build files.
f1620:m0
@contextmanager<EOL>def _dist_wrapper():
try:<EOL><INDENT>for rst_file, txt_file in zip(SDIST_RST_FILES, SDIST_TXT_FILES):<EOL><INDENT>local("<STR_LIT>" % (rst_file, txt_file))<EOL><DEDENT>yield<EOL><DEDENT>finally:<EOL><INDENT>for rst_file in SDIST_TXT_FILES:<EOL><INDENT>local("<STR_LIT>" % rst_file, capture=False)<EOL><DEDENT><DEDENT>
Add temporary distribution build files (and then clean up).
f1620:m1
def sdist():
with _dist_wrapper():<EOL><INDENT>local("<STR_LIT>", capture=False)<EOL><DEDENT>
Package into distribution.
f1620:m2
def register():
with _dist_wrapper():<EOL><INDENT>local("<STR_LIT>", capture=False)<EOL><DEDENT>
Register and prep user for PyPi upload. .. note:: May need to tweak ~/.pypirc file per issue: http://stackoverflow.com/questions/1569315
f1620:m3
def upload():
with _dist_wrapper():<EOL><INDENT>local("<STR_LIT>", capture=False)<EOL><DEDENT>
Upload package.
f1620:m4
def pylint(rcfile=PYLINT_CFG):
<EOL>local("<STR_LIT>" %<EOL>(rcfile, "<STR_LIT:U+0020>".join(CHECK_INCLUDES)), capture=False)<EOL>
Run pylint style checker. :param rcfile: PyLint configuration file.
f1620:m5
def check():
<EOL>pylint()<EOL>
Run all checkers.
f1620:m6
def _parse_bool(value):
if isinstance(value, bool):<EOL><INDENT>return value<EOL><DEDENT>elif isinstance(value, str):<EOL><INDENT>if value == '<STR_LIT:True>':<EOL><INDENT>return True<EOL><DEDENT>elif value == '<STR_LIT:False>':<EOL><INDENT>return False<EOL><DEDENT><DEDENT>raise Exception("<STR_LIT>" % value)<EOL>
Convert ``string`` or ``bool`` to ``bool``.
f1620:m7
def docs(output=DOC_OUTPUT, proj_settings=PROJ_SETTINGS, github=False):
local("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" % (proj_settings, DOC_INPUT, output),<EOL>capture=False)<EOL>if _parse_bool(github):<EOL><INDENT>local("<STR_LIT>" % output, capture=False)<EOL><DEDENT>
Generate API documentation (using Sphinx). :param output: Output directory. :param proj_settings: Django project settings to use. :param github: Convert to GitHub-friendly format?
f1620:m8
def _manage(target, extra='<STR_LIT>', proj_settings=PROJ_SETTINGS):
local("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" %<EOL>(proj_settings, target, extra),<EOL>capture=False)<EOL>
Generic wrapper for ``django-admin.py``.
f1620:m9
def syncdb(proj_settings=PROJ_SETTINGS):
local("<STR_LIT>" % DEV_DB_DIR)<EOL>_manage("<STR_LIT>", proj_settings=proj_settings)<EOL>
Run syncdb.
f1620:m10
def run_server(addr="<STR_LIT>", proj_settings=PROJ_SETTINGS):
_manage("<STR_LIT>", addr, proj_settings)<EOL>
Run Django dev. server.
f1620:m11
@classmethod<EOL><INDENT>def from_settings(cls):<DEDENT>
from cloud_browser.app_settings import settings<EOL>from django.core.exceptions import ImproperlyConfigured<EOL>conn_cls = conn_fn = None<EOL>datastore = settings.CLOUD_BROWSER_DATASTORE<EOL>if datastore == '<STR_LIT>':<EOL><INDENT>from cloud_browser.cloud.aws import AwsConnection<EOL>account = settings.CLOUD_BROWSER_AWS_ACCOUNT<EOL>secret_key = settings.CLOUD_BROWSER_AWS_SECRET_KEY<EOL>if account and secret_key:<EOL><INDENT>conn_cls = AwsConnection<EOL>conn_fn = lambda: AwsConnection(account, secret_key)<EOL><DEDENT><DEDENT>if datastore == '<STR_LIT>':<EOL><INDENT>from cloud_browser.cloud.google import GsConnection<EOL>account = settings.CLOUD_BROWSER_GS_ACCOUNT<EOL>secret_key = settings.CLOUD_BROWSER_GS_SECRET_KEY<EOL>if account and secret_key:<EOL><INDENT>conn_cls = GsConnection<EOL>conn_fn = lambda: GsConnection(account, secret_key)<EOL><DEDENT><DEDENT>elif datastore == '<STR_LIT>':<EOL><INDENT>account = settings.CLOUD_BROWSER_RACKSPACE_ACCOUNT<EOL>secret_key = settings.CLOUD_BROWSER_RACKSPACE_SECRET_KEY<EOL>servicenet = settings.CLOUD_BROWSER_RACKSPACE_SERVICENET<EOL>authurl = settings.CLOUD_BROWSER_RACKSPACE_AUTHURL<EOL>if account and secret_key:<EOL><INDENT>from cloud_browser.cloud.rackspace import RackspaceConnection<EOL>conn_cls = RackspaceConnection<EOL>conn_fn = lambda: RackspaceConnection(<EOL>account,<EOL>secret_key,<EOL>servicenet=servicenet,<EOL>authurl=authurl)<EOL><DEDENT><DEDENT>elif datastore == '<STR_LIT>':<EOL><INDENT>root = settings.CLOUD_BROWSER_FILESYSTEM_ROOT<EOL>if root is not None:<EOL><INDENT>from cloud_browser.cloud.fs import FilesystemConnection<EOL>conn_cls = FilesystemConnection<EOL>conn_fn = lambda: FilesystemConnection(root)<EOL><DEDENT><DEDENT>if conn_cls is None:<EOL><INDENT>raise ImproperlyConfigured(<EOL>"<STR_LIT>" %<EOL>datastore)<EOL><DEDENT>conn_fn = staticmethod(conn_fn)<EOL>cls.__connection_cls = conn_cls<EOL>cls.__connection_fn = conn_fn<EOL>return conn_cls, conn_fn<EOL>
Create configuration from Django settings or environment.
f1622:c0:m0
@classmethod<EOL><INDENT>def get_connection_cls(cls):<DEDENT>
if cls.__connection_cls is None:<EOL><INDENT>cls.__connection_cls, _ = cls.from_settings()<EOL><DEDENT>return cls.__connection_cls<EOL>
Return connection class. :rtype: :class:`type`
f1622:c0:m1
@classmethod<EOL><INDENT>def get_connection(cls):<DEDENT>
if cls.__connection_obj is None:<EOL><INDENT>if cls.__connection_fn is None:<EOL><INDENT>_, cls.__connection_fn = cls.from_settings()<EOL><DEDENT>cls.__connection_obj = cls.__connection_fn()<EOL><DEDENT>return cls.__connection_obj<EOL>
Return connection object. :rtype: :class:`cloud_browser.cloud.base.CloudConnection`
f1622:c0:m2
@classmethod<EOL><INDENT>@requires(cloudfiles, '<STR_LIT>')<EOL>def lazy_translations(cls):<DEDENT>
return {<EOL>cloudfiles.errors.NoSuchContainer: errors.NoContainerException,<EOL>cloudfiles.errors.NoSuchObject: errors.NoObjectException,<EOL>}<EOL>
Lazy translations.
f1623:c0:m0
@wrap_rs_errors<EOL><INDENT>def _get_object(self):<DEDENT>
return self.container.native_container.get_object(self.name)<EOL>
Return native storage object.
f1623:c1:m0
@wrap_rs_errors<EOL><INDENT>def _read(self):<DEDENT>
return self.native_obj.read()<EOL>
Return contents of object.
f1623:c1:m1
@classmethod<EOL><INDENT>def from_info(cls, container, info_obj):<DEDENT>
create_fn = cls.from_subdir if '<STR_LIT>' in info_objelse cls.from_file_info<EOL>return create_fn(container, info_obj)<EOL>
Create from subdirectory or file info object.
f1623:c1:m2
@classmethod<EOL><INDENT>def from_subdir(cls, container, info_obj):<DEDENT>
return cls(container,<EOL>info_obj['<STR_LIT>'],<EOL>obj_type=cls.type_cls.SUBDIR)<EOL>
Create from subdirectory info object.
f1623:c1:m3
@classmethod<EOL><INDENT>def choose_type(cls, content_type):<DEDENT>
return cls.type_cls.SUBDIR if content_type in cls.subdir_typeselse cls.type_cls.FILE<EOL>
Choose object type from content type.
f1623:c1:m4
@classmethod<EOL><INDENT>def from_file_info(cls, container, info_obj):<DEDENT>
<EOL>return cls(container,<EOL>name=info_obj['<STR_LIT:name>'],<EOL>size=info_obj['<STR_LIT>'],<EOL>content_type=info_obj['<STR_LIT>'],<EOL>last_modified=dt_from_header(info_obj['<STR_LIT>']),<EOL>obj_type=cls.choose_type(info_obj['<STR_LIT>']))<EOL>
Create from regular info object.
f1623:c1:m5
@classmethod<EOL><INDENT>def from_obj(cls, container, file_obj):<DEDENT>
<EOL>return cls(container,<EOL>name=file_obj.name,<EOL>size=file_obj.size,<EOL>content_type=file_obj.content_type,<EOL>last_modified=dt_from_header(file_obj.last_modified),<EOL>obj_type=cls.choose_type(file_obj.content_type))<EOL>
Create from regular info object.
f1623:c1:m6
@wrap_rs_errors<EOL><INDENT>def _get_container(self):<DEDENT>
return self.conn.native_conn.get_container(self.name)<EOL>
Return native container object.
f1623:c2:m0
@wrap_rs_errors<EOL><INDENT>def get_objects(self, path, marker=None,<EOL>limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):<DEDENT>
object_infos, full_query = self._get_object_infos(path, marker, limit)<EOL>if full_query and len(object_infos) < limit:<EOL><INDENT>object_infos, _ = self._get_object_infos(path, marker, <NUM_LIT:2> * limit)<EOL>object_infos = object_infos[:limit]<EOL><DEDENT>return [self.obj_cls.from_info(self, x) for x in object_infos]<EOL>
Get objects. **Pseudo-directory Notes**: Rackspace has two approaches to pseudo- directories within the (really) flat storage object namespace: 1. Dummy directory storage objects. These are real storage objects of type "application/directory" and must be manually uploaded by the client. 2. Implied subdirectories using the `path` API query parameter. Both serve the same purpose, but the latter is much preferred because there is no independent maintenance of extra dummy objects, and the `path` approach is always correct (for the existing storage objects). This package uses the latter `path` approach, but gets into an ambiguous situation where there is both a dummy directory storage object and an implied subdirectory. To remedy this situation, we only show information for the dummy directory object in results if present, and ignore the implied subdirectory. But, under the hood this means that our `limit` parameter may end up with less than the desired number of objects. So, we use the heuristic that if we **do** have "application/directory" objects, we end up doing an extra query of double the limit size to ensure we can get up to the limit amount of objects. This double query approach is inefficient, but as using dummy objects should now be deprecated, the second query should only rarely occur.
f1623:c2:m1
@wrap_rs_errors<EOL><INDENT>def _get_object_infos(self, path, marker=None,<EOL>limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):<DEDENT>
<EOL>orig_limit = limit<EOL>limit += <NUM_LIT:1><EOL>if limit > RS_MAX_LIST_OBJECTS_LIMIT:<EOL><INDENT>raise errors.CloudException("<STR_LIT>" %<EOL>RS_MAX_LIST_OBJECTS_LIMIT)<EOL><DEDENT>def _collapse(infos):<EOL><INDENT>"""<STR_LIT>"""<EOL>name = None<EOL>for info in infos:<EOL><INDENT>name = info.get('<STR_LIT:name>', name)<EOL>subdir = info.get('<STR_LIT>', '<STR_LIT>').strip(SEP)<EOL>if not name or subdir != name:<EOL><INDENT>yield info<EOL><DEDENT><DEDENT><DEDENT>path = path + SEP if path else '<STR_LIT>'<EOL>object_infos = self.native_container.list_objects_info(<EOL>limit=limit, delimiter=SEP, prefix=path, marker=marker)<EOL>full_query = len(object_infos) == limit<EOL>if object_infos:<EOL><INDENT>if (marker and<EOL>object_infos[<NUM_LIT:0>].get('<STR_LIT>', '<STR_LIT>').strip(SEP) == marker):<EOL><INDENT>object_infos = object_infos[<NUM_LIT:1>:]<EOL><DEDENT>object_infos = list(_collapse(object_infos))<EOL>if len(object_infos) > orig_limit:<EOL><INDENT>object_infos = object_infos[:orig_limit]<EOL><DEDENT><DEDENT>return object_infos, full_query<EOL>
Get raw object infos (single-shot).
f1623:c2:m2
@wrap_rs_errors<EOL><INDENT>def get_object(self, path):<DEDENT>
obj = self.native_container.get_object(path)<EOL>return self.obj_cls.from_obj(self, obj)<EOL>
Get single object.
f1623:c2:m3
def __init__(self, account, secret_key, servicenet=False, authurl=None):
super(RackspaceConnection, self).__init__(account, secret_key)<EOL>self.servicenet = servicenet<EOL>self.authurl = authurl<EOL>
Initializer.
f1623:c3:m0
@wrap_rs_errors<EOL><INDENT>@requires(cloudfiles, '<STR_LIT>')<EOL>def _get_connection(self):<DEDENT>
kwargs = {<EOL>'<STR_LIT:username>': self.account,<EOL>'<STR_LIT>': self.secret_key,<EOL>}<EOL>if self.servicenet:<EOL><INDENT>kwargs['<STR_LIT>'] = True<EOL><DEDENT>if self.authurl:<EOL><INDENT>kwargs['<STR_LIT>'] = self.authurl<EOL><DEDENT>return cloudfiles.get_connection(**kwargs)<EOL>
Return native connection object.
f1623:c3:m1
@wrap_rs_errors<EOL><INDENT>def _get_containers(self):<DEDENT>
infos = self.native_conn.list_containers_info()<EOL>return [self.cont_cls(self, i['<STR_LIT:name>'], i['<STR_LIT:count>'], i['<STR_LIT>'])<EOL>for i in infos]<EOL>
Return available containers.
f1623:c3:m2
@wrap_rs_errors<EOL><INDENT>def _get_container(self, path):<DEDENT>
cont = self.native_conn.get_container(path)<EOL>return self.cont_cls(self,<EOL>cont.name,<EOL>cont.object_count,<EOL>cont.size_used)<EOL>
Return single container.
f1623:c3:m3
def __new__(cls, *args, **kwargs):
obj = object.__new__(cls, *args, **kwargs)<EOL>if not obj.translations:<EOL><INDENT>lazy_translations = cls.lazy_translations()<EOL>if lazy_translations:<EOL><INDENT>obj.translations = lazy_translations<EOL><DEDENT><DEDENT>return obj<EOL>
New.
f1624:c5:m0
@classmethod<EOL><INDENT>def excepts(cls):<DEDENT>
if cls._excepts is None:<EOL><INDENT>cls._excepts = tuple(cls.translations.keys())<EOL><DEDENT>return cls._excepts<EOL>
Return tuple of underlying exception classes to trap and wrap. :rtype: ``tuple`` of ``type``
f1624:c5:m1
def translate(self, exc):
<EOL>for key in self.translations.keys():<EOL><INDENT>if isinstance(exc, key):<EOL><INDENT>return self.translations[key](str(exc))<EOL><DEDENT><DEDENT>return None<EOL>
Return translation of exception to new class. Calling code should only raise exception if exception class is passed in, else ``None`` (which signifies no wrapping should be done).
f1624:c5:m2
def __call__(self, operation):
@wraps(operation)<EOL>def wrapped(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return operation(*args, **kwargs)<EOL><DEDENT>except self.excepts() as exc:<EOL><INDENT>new_exc = self.translate(exc)<EOL>if new_exc:<EOL><INDENT>raise new_exc.__class__(new_exc, sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>return wrapped<EOL>
Call and wrap exceptions.
f1624:c5:m3
@classmethod<EOL><INDENT>def lazy_translations(cls):<DEDENT>
return None<EOL>
Lazy translations definitions (for additional checks).
f1624:c5:m4
@classmethod<EOL><INDENT>def _is_gs_folder(cls, result):<DEDENT>
return (cls.is_key(result) and<EOL>result.size == <NUM_LIT:0> and<EOL>result.name.endswith(cls._gs_folder_suffix))<EOL>
Return ``True`` if GS standalone folder object. GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a pseudo-directory place holder if there are no files present.
f1625:c0:m0
@classmethod<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def is_key(cls, result):<DEDENT>
from boto.gs.key import Key<EOL>return isinstance(result, Key)<EOL>
Return ``True`` if result is a key object.
f1625:c0:m1
@classmethod<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def is_prefix(cls, result):<DEDENT>
from boto.s3.prefix import Prefix<EOL>return isinstance(result, Prefix) or cls._is_gs_folder(result)<EOL>
Return ``True`` if result is a prefix object. .. note:: Boto uses the S3 Prefix object for GS prefixes.
f1625:c0:m2
@classmethod<EOL><INDENT>def from_prefix(cls, container, prefix):<DEDENT>
if cls._is_gs_folder(prefix):<EOL><INDENT>name, suffix, extra = prefix.name.partition(cls._gs_folder_suffix)<EOL>if (suffix, extra) == (cls._gs_folder_suffix, '<STR_LIT>'):<EOL><INDENT>prefix.name = name<EOL><DEDENT><DEDENT>return super(GsObject, cls).from_prefix(container, prefix)<EOL>
Create from prefix object.
f1625:c0:m3
def get_objects(self, path, marker=None,<EOL>limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
<EOL>folder = path.split(SEP)[-<NUM_LIT:1>]<EOL>objs = super(GsContainer, self).get_objects(path, marker, limit + <NUM_LIT:1>)<EOL>objs = [o for o in objs if not (o.size == <NUM_LIT:0> and o.name == folder)]<EOL>return objs[:limit]<EOL>
Get objects. Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an extra +1 limit query and ignore any such file objects.
f1625:c1:m0
@base.BotoConnection.wrap_boto_errors<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def _get_connection(self):<DEDENT>
return boto.connect_gs(self.account, self.secret_key)<EOL>
Return native connection object.
f1625:c2:m0
@classmethod<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def is_key(cls, result):<DEDENT>
from boto.s3.key import Key<EOL>return isinstance(result, Key)<EOL>
Return ``True`` if result is a key object.
f1626:c0:m0
@classmethod<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def is_prefix(cls, result):<DEDENT>
from boto.s3.prefix import Prefix<EOL>return isinstance(result, Prefix)<EOL>
Return ``True`` if result is a prefix object.
f1626:c0:m1
@base.BotoConnection.wrap_boto_errors<EOL><INDENT>@requires(boto, '<STR_LIT>')<EOL>def _get_connection(self):<DEDENT>
return boto.connect_s3(self.account, self.secret_key)<EOL>
Return native connection object.
f1626:c2:m0
def __init__(self, container, name, **kwargs):
self.container = container<EOL>self.name = name.rstrip(SEP)<EOL>self.size = kwargs.get('<STR_LIT:size>', <NUM_LIT:0>)<EOL>self.content_type = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.content_encoding = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>self.last_modified = kwargs.get('<STR_LIT>', None)<EOL>self.type = kwargs.get('<STR_LIT>', self.type_cls.FILE)<EOL>self.__native = None<EOL>
Initializer. :param container: Container object. :param name: Object name / path. :kwarg size: Number of bytes in object. :kwarg content_type: Document 'content-type'. :kwarg content_encoding: Document 'content-encoding'. :kwarg last_modified: Last modified date. :kwarg obj_type: Type of object (e.g., file or subdirectory).
f1627:c1:m0
@property<EOL><INDENT>def native_obj(self):<DEDENT>
if self.__native is None:<EOL><INDENT>self.__native = self._get_object()<EOL><DEDENT>return self.__native<EOL>
Native storage object.
f1627:c1:m1
def _get_object(self):
raise NotImplementedError<EOL>
Return native storage object.
f1627:c1:m2
@property<EOL><INDENT>def is_subdir(self):<DEDENT>
return self.type == self.type_cls.SUBDIR<EOL>
Is a subdirectory?
f1627:c1:m3
@property<EOL><INDENT>def is_file(self):<DEDENT>
return self.type == self.type_cls.FILE<EOL>
Is a file object?
f1627:c1:m4
@property<EOL><INDENT>def path(self):<DEDENT>
return path_join(self.container.name, self.name)<EOL>
Full path (including container).
f1627:c1:m5
@property<EOL><INDENT>def basename(self):<DEDENT>
return basename(self.name)<EOL>
Base name from rightmost separator.
f1627:c1:m6
@property<EOL><INDENT>def smart_content_type(self):<DEDENT>
content_type = self.content_type<EOL>if content_type in (None, '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>content_type, _ = mimetypes.guess_type(self.name)<EOL><DEDENT>return content_type<EOL>
Smart content type.
f1627:c1:m7
@property<EOL><INDENT>def smart_content_encoding(self):<DEDENT>
encoding = self.content_encoding<EOL>if not encoding:<EOL><INDENT>base_list = self.basename.split('<STR_LIT:.>')<EOL>while (not encoding) and len(base_list) > <NUM_LIT:1>:<EOL><INDENT>_, encoding = mimetypes.guess_type('<STR_LIT:.>'.join(base_list))<EOL>base_list.pop()<EOL><DEDENT><DEDENT>return encoding<EOL>
Smart content encoding.
f1627:c1:m8
def read(self):
return self._read()<EOL>
Return contents of object.
f1627:c1:m9
def _read(self):
raise NotImplementedError<EOL>
Return contents of object.
f1627:c1:m10
def __init__(self, conn, name=None, count=None, size=None):
self.conn = conn<EOL>self.name = name<EOL>self.count = count<EOL>self.size = size<EOL>self.__native = None<EOL>
Initializer.
f1627:c2:m0
@property<EOL><INDENT>def native_container(self):<DEDENT>
if self.__native is None:<EOL><INDENT>self.__native = self._get_container()<EOL><DEDENT>return self.__native<EOL>
Native container object.
f1627:c2:m1
def _get_container(self):
raise NotImplementedError<EOL>
Return native container object.
f1627:c2:m2
def get_objects(self, path, marker=None,<EOL>limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
raise NotImplementedError<EOL>
Get objects.
f1627:c2:m3
def get_object(self, path):
raise NotImplementedError<EOL>
Get single object.
f1627:c2:m4
def __init__(self, account, secret_key):
self.account = account<EOL>self.secret_key = secret_key<EOL>self.__native = None<EOL>
Initializer.
f1627:c3:m0
@property<EOL><INDENT>def native_conn(self):<DEDENT>
if self.__native is None:<EOL><INDENT>self.__native = self._get_connection()<EOL><DEDENT>return self.__native<EOL>
Native connection object.
f1627:c3:m1
def _get_connection(self):
raise NotImplementedError<EOL>
Return native connection object.
f1627:c3:m2
def get_containers(self):
permitted = lambda c: settings.container_permitted(c.name)<EOL>return [c for c in self._get_containers() if permitted(c)]<EOL>
Return available containers.
f1627:c3:m3
def _get_containers(self):
raise NotImplementedError<EOL>
Return available containers.
f1627:c3:m4
def get_container(self, path):
if not settings.container_permitted(path):<EOL><INDENT>raise errors.NotPermittedException(<EOL>"<STR_LIT>" % path)<EOL><DEDENT>return self._get_container(path)<EOL>
Return single container.
f1627:c3:m5
def _get_container(self, path):
raise NotImplementedError<EOL>
Return single container.
f1627:c3:m6
def get_connection():
from cloud_browser.cloud.config import Config<EOL>return Config.get_connection()<EOL>
Return global connection object. :rtype: :class:`cloud_browser.cloud.base.CloudConnection`
f1628:m0
def get_connection_cls():
from cloud_browser.cloud.config import Config<EOL>return Config.get_connection_cls()<EOL>
Return global connection class. :rtype: :class:`type`
f1628:m1
def not_dot(path):
return NO_DOT_RE.match(os.path.basename(path))<EOL>
Check if non-dot.
f1629:m0
def is_dir(path):
return not_dot(path) and os.path.isdir(path)<EOL>
Check if non-dot and directory.
f1629:m1
def _get_object(self):
return object()<EOL>
Return native storage object.
f1629:c2:m0
def _read(self):
with open(self.base_path, '<STR_LIT:rb>') as file_obj:<EOL><INDENT>return file_obj.read()<EOL><DEDENT>
Return contents of object.
f1629:c2:m1
@property<EOL><INDENT>def base_path(self):<DEDENT>
return os.path.join(self.container.base_path, self.name)<EOL>
Base absolute path of container.
f1629:c2:m2
@classmethod<EOL><INDENT>def from_path(cls, container, path):<DEDENT>
from datetime import datetime<EOL>path = path.strip(SEP)<EOL>full_path = os.path.join(container.base_path, path)<EOL>last_modified = datetime.fromtimestamp(os.path.getmtime(full_path))<EOL>obj_type = cls.type_cls.SUBDIR if is_dir(full_path)else cls.type_cls.FILE<EOL>return cls(container,<EOL>name=path,<EOL>size=os.path.getsize(full_path),<EOL>content_type=None,<EOL>last_modified=last_modified,<EOL>obj_type=obj_type)<EOL>
Create object from path.
f1629:c2:m3
def _get_container(self):
return object()<EOL>
Return native container object.
f1629:c3:m0
@wrap_fs_obj_errors<EOL><INDENT>def get_objects(self, path, marker=None,<EOL>limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):<DEDENT>
def _filter(name):<EOL><INDENT>"""<STR_LIT>"""<EOL>return (not_dot(name) and<EOL>(marker is None or<EOL>os.path.join(path, name).strip(SEP) > marker.strip(SEP)))<EOL><DEDENT>search_path = os.path.join(self.base_path, path)<EOL>objs = [self.obj_cls.from_path(self, os.path.join(path, o))<EOL>for o in os.listdir(search_path) if _filter(o)]<EOL>objs = sorted(objs, key=lambda x: x.base_path)<EOL>return objs[:limit]<EOL>
Get objects.
f1629:c3:m1
@wrap_fs_obj_errors<EOL><INDENT>def get_object(self, path):<DEDENT>
return self.obj_cls.from_path(self, path)<EOL>
Get single object.
f1629:c3:m2
@property<EOL><INDENT>def base_path(self):<DEDENT>
return os.path.join(self.conn.abs_root, self.name)<EOL>
Base absolute path of container.
f1629:c3:m3
@classmethod<EOL><INDENT>def from_path(cls, conn, path):<DEDENT>
path = path.strip(SEP)<EOL>full_path = os.path.join(conn.abs_root, path)<EOL>return cls(conn, path, <NUM_LIT:0>, os.path.getsize(full_path))<EOL>
Create container from path.
f1629:c3:m4
def __init__(self, root):
super(FilesystemConnection, self).__init__(None, None)<EOL>self.root = root<EOL>self.abs_root = os.path.abspath(root)<EOL>
Initializer.
f1629:c4:m0
def _get_connection(self):
return object()<EOL>
Return native connection object.
f1629:c4:m1
@wrap_fs_cont_errors<EOL><INDENT>def _get_containers(self):<DEDENT>
def full_fn(path):<EOL><INDENT>return os.path.join(self.abs_root, path)<EOL><DEDENT>return [self.cont_cls.from_path(self, d)<EOL>for d in os.listdir(self.abs_root) if is_dir(full_fn(d))]<EOL>
Return available containers.
f1629:c4:m2
@wrap_fs_cont_errors<EOL><INDENT>def _get_container(self, path):<DEDENT>
path = path.strip(SEP)<EOL>if SEP in path:<EOL><INDENT>raise errors.InvalidNameException(<EOL>"<STR_LIT>" % (SEP, path))<EOL><DEDENT>return self.cont_cls.from_path(self, path)<EOL>
Return single container.
f1629:c4:m3
@requires(boto, '<STR_LIT>')<EOL><INDENT>def translate(self, exc):<DEDENT>
from boto.exception import StorageResponseError<EOL>if isinstance(exc, StorageResponseError):<EOL><INDENT>if exc.status == <NUM_LIT>:<EOL><INDENT>return self.error_cls(str(exc))<EOL><DEDENT><DEDENT>return None<EOL>
Return whether or not to do translation.
f1630:c0:m0
@classmethod<EOL><INDENT>def is_key(cls, result):<DEDENT>
raise NotImplementedError<EOL>
Return ``True`` if result is a key object.
f1630:c3:m0
@classmethod<EOL><INDENT>def is_prefix(cls, result):<DEDENT>
raise NotImplementedError<EOL>
Return ``True`` if result is a prefix object.
f1630:c3:m1
@wrap_boto_errors<EOL><INDENT>def _get_object(self):<DEDENT>
return self.container.native_container.get_key(self.name)<EOL>
Return native storage object.
f1630:c3:m2