Parse out what resources are used, opened and closed in an action step.
483132
def _parse_resource_usage(cls, action_dict, declarations):
        """"""

        raw_used = action_dict.pop('use', [])
        opened = [x.strip() for x in action_dict.pop('open_before', [])]
        closed = [x.strip() for x in action_dict.pop('close_after', [])]

        used = {}

        for resource in raw_used:
            if 'as' in resource:
                global_name, _, local_name = resource.partition('as')
                global_name = global_name.strip()
                local_name = local_name.strip()

                if len(global_name) == 0 or len(local_name) == 0:
                    raise RecipeFileInvalid("Resource usage specified in action with invalid name using 'as' statement", global_name=global_name, local_name=local_name, statement=resource)
            else:
                global_name = resource.strip()
                local_name = global_name

            if local_name in used:
                raise RecipeFileInvalid("Resource specified twice for action", args=action_dict, resource=local_name, used_resources=used)

            used[local_name] = global_name

        # Make sure we only use, open and close declared resources
        for name in (x for x in used.values() if x not in declarations):
            raise RecipeFileInvalid("Action makes use of non-declared shared resource", name=name)

        for name in (x for x in opened if x not in declarations):
            raise RecipeFileInvalid("Action specified a non-declared shared resource in open_before", name=name)

        for name in (x for x in closed if x not in declarations):
            raise RecipeFileInvalid("Action specified a non-declared shared resource in close_after", name=name)

        return ResourceUsage(used, opened, closed)
1222017
function _extractActions( opts )
	{
		// main properties
		const 	data 		= opts.data,
				configState = opts.stateData,
				stateView 	= opts.stateView,
				stateName  	= opts.stateName;

		// new defined properties
		let stateTransitions = [],
			viewData 		 = opts.viewData,
			appDataView,
			action,
			statePrefix;

		forein( configState.actions, ( prop, actionName ) => {

			statePrefix = (stateName+ '->' +actionName);
			appDataView = data[ prop.target ].view;

			// Return action data for FSM
			action = {
				action 		: actionName,
				target 		: prop.target,
				_id 		: statePrefix
			};

			// return ViewData for View manager and append all views
			viewData[ statePrefix ] = {
				currentView 		: stateView,
				nextView 			: appDataView,
				linkedVTransModules : _extractTransitions( prop, stateView, appDataView ),
				name  				: actionName
			};

			// // assign fsm action to state
			stateTransitions[ stateTransitions.length ] = action;
		});

		return { stateTransitions : stateTransitions, viewData : viewData };
	}
668920
def parse(data, datafile):
    """"""
    data._last_travel = [0, [0]]  # x and verbs used by section 3

    while True:
        section_number = int(datafile.readline())
        if not section_number:  # no further sections
            break
        store = globals().get('section%d' % section_number)
        while True:
            fields = [ (int(field) if field.lstrip('-').isdigit() else field)
                       for field in datafile.readline().strip().split('\t') ]
            if fields[0] == -1:  # end-of-section marker
                break
            store(data, *fields)

    del data._last_travel  # state used by section 3
    del data._object       # state used by section 5

    data.object_list = sorted(set(data.objects.values()), key=attrgetter('n'))
    #data.room_list = sorted(set(data.rooms.values()), key=attrgetter('n'))
    for obj in data.object_list:
        name = obj.names[0]
        if hasattr(data, name):
            name = name + '2'  # create identifiers like ROD2, PLANT2
        setattr(data, name, obj)

    return data
33873
def analyse_action(func):
    """"""
    description = inspect.getdoc(func) or 'undocumented action'
    arguments = []
    args, varargs, kwargs, defaults = inspect.getargspec(func)
    if varargs or kwargs:
        raise TypeError('variable length arguments for action not allowed.')
    if len(args) != len(defaults or ()):
        raise TypeError('not all arguments have proper definitions')

    for idx, (arg, definition) in enumerate(zip(args, defaults or ())):
        if arg.startswith('_'):
            raise TypeError('arguments may not start with an underscore')
        if not isinstance(definition, tuple):
            shortcut = None
            default = definition
        else:
            shortcut, default = definition
        argument_type = argument_types[type(default)]
        if isinstance(default, bool) and default is True:
            arg = 'no-' + arg
        arguments.append((arg.replace('_', '-'), shortcut,
                          default, argument_type))
    return func, description, arguments
588772
def _get_action_endpoint(action):
    
    _endpoint = None
    if is_method(action):
        if hasattr(action, "_rule_cache"):
            rc = action._rule_cache
            if rc:
                k = list(rc.keys())[0]
                rules = rc[k]
                len_rules = len(rules)
                if len_rules == 1:
                    rc_kw = rules[0][1]
                    _endpoint = rc_kw.get("endpoint", None)
                    if not _endpoint:
                        _endpoint = _build_endpoint_route_name(action)
                elif len_rules > 1:
                    _prefix = _build_endpoint_route_name(action)
                    for r in Mocha._app.url_map.iter_rules():
                        if ('GET' in r.methods or 'POST' in r.methods) \
                                and _prefix in r.endpoint:
                            _endpoint = r.endpoint
                            break
    return _endpoint
1148045
private void readActivities()
   {
      List<MapRow> items = new ArrayList<MapRow>();
      for (MapRow row : m_tables.get("ACT"))
      {
         items.add(row);
      }
      final AlphanumComparator comparator = new AlphanumComparator();
      Collections.sort(items, new Comparator<MapRow>()
      {
         @Override public int compare(MapRow o1, MapRow o2)
         {
            return comparator.compare(o1.getString("ACTIVITY_ID"), o2.getString("ACTIVITY_ID"));
         }
      });

      for (MapRow row : items)
      {
         String activityID = row.getString("ACTIVITY_ID");

         String wbs;
         if (m_wbsFormat == null)
         {
            wbs = null;
         }
         else
         {
            m_wbsFormat.parseRawValue(row.getString("WBS"));
            wbs = m_wbsFormat.getFormattedValue();
         }

         ChildTaskContainer parent = m_wbsMap.get(wbs);
         if (parent == null)
         {
            parent = m_projectFile;
         }

         Task task = parent.addTask();
         setFields(TASK_FIELDS, row, task);
         task.setStart(task.getEarlyStart());
         task.setFinish(task.getEarlyFinish());
         task.setMilestone(task.getDuration().getDuration() == 0);
         task.setWBS(wbs);
         Duration duration = task.getDuration();
         Duration remainingDuration = task.getRemainingDuration();
         task.setActualDuration(Duration.getInstance(duration.getDuration() - remainingDuration.getDuration(), TimeUnit.HOURS));
         m_activityMap.put(activityID, task);
      }
   }
1317693
def _parse_action(self, action, current_time):
        
        if action.action_type == 'research':
            name = mgz.const.TECHNOLOGIES[action.data.technology_type]
            self._research[action.data.player_id].append({
                'technology': name,
                'timestamp': _timestamp_to_time(action.timestamp)
            })
        elif action.action_type == 'build':
            self._build[action.data.player_id].append({
                'building': mgz.const.UNITS[action.data.building_type],
                'timestamp': _timestamp_to_time(current_time),
                'coordinates': {'x': action.data.x, 'y': action.data.y}
            })
        elif action.action_type == 'queue':
            for _ in range(0, int(action.data.number)):
                self._queue.append({
                    'unit': mgz.const.UNITS[action.data.unit_type],
                    'timestamp': _timestamp_to_time(current_time)
                })
34907
def parse_resource(name):
    
    with closing(pkg_resources.resource_stream(__name__, name)) as fp:
        rbytes = fp.read()

    return _load(StringIO(rbytes.decode('utf-8')))
558849
def _cleanup_resources(self, initialized_resources):
        """"""

        cleanup_errors = []

        # Make sure we clean up all resources that we can and don't error out at the
        # first one.
        for name, res in initialized_resources.items():
            try:
                if res.opened:
                    res.close()
            except Exception:
                _type, value, traceback = sys.exc_info()
                cleanup_errors.append((name, value, traceback))

        if len(cleanup_errors) > 0:
            raise RecipeResourceManagementError(operation="resource cleanup", errors=cleanup_errors)
1116917
def resources(self):
        """"""
        with open(os.path.join(EULER_DATA, 'resources.json')) as data_file:
            data = json.load(data_file)

        problem_num = str(self.num)

        if problem_num in data:
            files = data[problem_num]

            # Ensure a list of files is returned
            return files if isinstance(files, list) else [files]
        else:
            return None
198100
def post_parse_action(self, entry):
        """"""
        if 'source_host' in entry.keys():
            host = self.ip_port_regex.findall(entry['source_host'])
            if host:
                hlist = host[0].split('.')
                entry['source_host'] = '.'.join(hlist[:4])
                entry['source_port'] = hlist[-1]
        if 'dest_host' in entry.keys():
            host = self.ip_port_regex.findall(entry['dest_host'])
            if host:
                hlist = host[0].split('.')
                entry['dest_host'] = '.'.join(hlist[:4])
                entry['dest_port'] = hlist[-1]

        return entry
841012
protected function gatherActionData()
    {
        foreach ($this->actionsOrder as $actionType) {
            // Find all Actions to be processed.
            $actions = $this->getActions(
                $actionType,
                $this->scheduler->getPeriodStart(),
                $this->scheduler->getPeriodEnd()
            );

            // Store all the Action-related info in the Job entity.
            if (!$actions) {
                $this->io->text(
                    'No actions of type "'.$actionType.'" scheduled within the past '.$this->interval.' minutes.'
                );

                continue;
            }

            $tableHeaders = ['ID', 'Start Date', 'End Date', 'Name', 'Status'];
            if ($actionType != Action::TYPE_CAMPAIGN) {
                $tableHeaders[] = 'Campaign ID';
                $tableHeaders[] = 'Campaign Status';
            }
            if ($actionType == Action::TYPE_OPERATION) {
                $tableHeaders[] = 'Action ID';
                $tableHeaders[] = 'Action Status';
            }

            $outputTableRows = [];

            foreach ($actions as $action) {
                // Has a scheduler job been defined in the Action's module?
                $actionServices = $action->getModule()->getServices();
                if (!is_array($actionServices) || !isset($actionServices['job'])) {
                    $message =
                        'No job service defined for module "'
                        .$action->getModule()->getIdentifier()
                        .'" in bundle "'
                        .$action->getModule()->getBundle()->getName().'" '
                        .'while processing Action of type "'.$action->getType().'" '
                        .'with ID "'.$action->getId().'"'
                        .'.';

                    $this->io->text($message);

                    continue;
                }

                // Queue new Job.
                $this->queueJob(
                    $action->getType(),
                    $action->getId(),
                    $action->getModule()->getServices()['job'],
                    'action'
                );

                $this->logger->info(
                    'New job of {type} with the action ID {id} queued',
                    [
                        'type' => $action->getType(),
                        'id' => $action->getId(),
                    ]
                );

                // Highlight the date that is within the execution period.
                $startDate = $action->getStartDate()->format('Y-m-d H:i:s');
                $endDate = null;

                if ($action->getStartDate() >= $this->scheduler->getPeriodStart()) {
                    $startDate = '<options=bold>'.$startDate.'</options=bold>';
                } elseif ($action->getEndDate()) {
                    $endDate = $action->getEndDate()->format('Y-m-d H:i:s');
                    $endDate = '<options=bold>'.$endDate.'</options=bold>';
                }

                $tableRows = [
                    $action->getId(),
                    $startDate,
                    $endDate,
                    $action->getName(),
                    $action->getStatus(),
                ];

                if ($actionType == Action::TYPE_ACTIVITY || $actionType == Action::TYPE_MILESTONE) {
                    $tableRows[] = $action->getCampaign()->getId();
                    $tableRows[] = $action->getCampaign()->getStatus();
                }
                if ($actionType == Action::TYPE_OPERATION) {
                    $tableRows[] = $action->getActivity()->getCampaign()->getId();
                    $tableRows[] = $action->getActivity()->getCampaign()->getStatus();
                    $tableRows[] = $action->getActivity()->getId();
                    $tableRows[] = $action->getActivity()->getStatus();
                }

                $outputTableRows[] = $tableRows;
            }

            if (count($outputTableRows)) {
                // Create the table rows for output.
                $this->io->newLine();
                $this->io->text('These actions of type "'.$actionType.'"  will be executed:');
                $this->io->table($tableHeaders, $outputTableRows);
            } else {
                $this->io->text(
                    'No actions of type "'.$actionType.'" scheduled within the past '.$this->interval.' minutes.'
                );
            }
        }
    }
255776
def process_action(ctx, param, value):
    """"""
    actions = current_app.extensions['invenio-access'].actions
    if value not in actions:
        raise click.BadParameter('Action "%s" is not registered.', value)
    return actions[value]
1243777
def _get_usage(self):
        
        parser = argparse.ArgumentParser()
        parser.prog = 'juju-resources {}'.format(self.object_name)
        for set_name, set_args in getattr(self.object, '_subcommand_argsets', {}).items():
            for ap_args, ap_kwargs in set_args:
                parser.add_argument(*ap_args, **ap_kwargs)
        for ap_args, ap_kwargs in getattr(self.object, '_subcommand_args', []):
            parser.add_argument(*ap_args, **ap_kwargs)
        usage = parser.format_usage()
        usage = re.sub(r'\n *', ' ', usage)
        return usage.strip()
278002
def read_resource_list(self, uri):
        """"""
        self.logger.info("Reading resource list %s" % (uri))
        try:
            resource_list = ResourceList(allow_multifile=self.allow_multifile,
                                         mapper=self.mapper)
            resource_list.read(uri=uri)
        except Exception as e:
            raise ClientError("Can't read source resource list from %s (%s)" %
                              (uri, str(e)))
        self.logger.debug("Finished reading resource list")
        return(resource_list)
429789
def parse(self) -> InstanceRoute:
        """"""
        res = InstanceRoute()
        if self.at_end():
            return res
        if self.peek() == "/":
            self.offset += 1
        if self.at_end():
            return res
        sn = self.schema_node
        while True:
            name, ns = self.prefixed_name()
            cn = sn.get_data_child(name, ns)
            if cn is None:
                for cn in sn.children:
                    if (isinstance(cn, RpcActionNode) and cn.name == name and
                            (ns is None or cn.ns == ns)):
                        res.append(ActionName(name, ns))
                        return res
                raise NonexistentSchemaNode(sn.qual_name, name, ns)
            res.append(MemberName(name, ns))
            if self.at_end():
                return res
            if isinstance(cn, SequenceNode):
                self.char("=")
                res.append(self._key_values(cn))
                if self.at_end():
                    return res
            else:
                self.char("/")
            sn = cn
120734
def load(cls, v):
        """"""
        if v is None:
            return []
        if isinstance(v, list):
            return [ Action(s) for s in v ]
        elif isinstance(v, str):
            return [Action(v)]
        else:
            raise ParseError("Couldn't parse action: %r" % v)