Converts a generator with approval rows into ApprovalRequest objects.
557236
def _ResponseToApprovalsWithGrants(response):
  """"""
  prev_triplet = None
  cur_approval_request = None
  for (approval_id_int, approval_timestamp, approval_request_bytes,
       grantor_username, grant_timestamp) in response:

    cur_triplet = (approval_id_int, approval_timestamp, approval_request_bytes)

    if cur_triplet != prev_triplet:
      prev_triplet = cur_triplet

      if cur_approval_request:
        yield cur_approval_request

      cur_approval_request = mysql_utils.StringToRDFProto(
          rdf_objects.ApprovalRequest, approval_request_bytes)
      cur_approval_request.approval_id = _IntToApprovalID(approval_id_int)
      cur_approval_request.timestamp = mysql_utils.TimestampToRDFDatetime(
          approval_timestamp)

    if grantor_username and grant_timestamp:
      cur_approval_request.grants.append(
          rdf_objects.ApprovalGrant(
              grantor_username=grantor_username,
              timestamp=mysql_utils.TimestampToRDFDatetime(grant_timestamp)))

  if cur_approval_request:
    yield cur_approval_request
338154
def _serialize_rules(rules):
    
    result = [(rule_name, str(rule)) for rule_name, rule in rules.items()]
    return sorted(result, key=lambda rule: rule[0])
851157
def _bulk_size_generator(num_records, bulk_size, active):
    
    while active and num_records > 0:
        req_size = min(num_records, bulk_size)
        num_records -= req_size
        yield req_size
994109
def from_raw(self, rule_ids, outputs, raw_rules):
        
        self._rule_pool = [([], [])] + raw_rules
        self._rule_list = []
        for i, idx in enumerate(rule_ids):
            rule = Rule([Clause(f, c) for f, c in zip(*self._rule_pool[idx])], outputs[i])
            self._rule_list.append(rule)
            # self._rule_list.append(rule_str2rule(_rule_name, outputs[i]))
        self._rule_ids = rule_ids
        self._rule_outputs = outputs
463458
public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,
            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception
    {
        List<Object> entities = new ArrayList<Object>();
        if (rowIds != null)
        {
            for (Object rowKey : rowIds)
            {
                Object e = fromThriftRow(clazz, m, rowKey, relationNames, isWrapReq, consistencyLevel);
                if (e != null)
                {
                    entities.add(e);
                }
            }
        }
        return entities;
    }
1204404
def GrantApproval(self,
                    requestor_username,
                    approval_id,
                    grantor_username,
                    cursor=None):
    """"""
    self._GrantApproval(
        requestor_username, _ApprovalIDToInt(approval_id), grantor_username,
        cursor)
316817
def BuildApprovalUrn(self, approval_id):
    """"""
    event = rdf_events.AuditEvent(
        user=self.token.username,
        action="CLIENT_APPROVAL_REQUEST",
        client=self.subject_urn,
        description=self.reason)
    events.Events.PublishEvent("Audit", event, token=self.token)

    return self.ApprovalUrnBuilder(self.subject_urn.Path(), self.token.username,
                                   approval_id)
706628
def action_to_approve(self):
        """"""
        template = self.env.ref(
            'document_page_approval.email_template_new_draft_need_approval')
        approver_gid = self.env.ref(
            'document_page_approval.group_document_approver_user')
        for rec in self:
            if rec.state != 'draft':
                raise UserError(
                    _("Can't approve pages in '%s' state.") % rec.state)
            if not (rec.am_i_owner or rec.am_i_approver):
                raise UserError(
                    _('You are not authorized to do this.\r\n'
                      'Only owners or approvers can request approval.'))
            # request approval
            if rec.is_approval_required:
                rec.write({'state': 'to approve'})
                guids = [g.id for g in rec.page_id.approver_group_ids]
                users = self.env['res.users'].search([
                    ('groups_id', 'in', guids),
                    ('groups_id', 'in', approver_gid.id)])
                rec.message_subscribe_users([u.id for u in users])
                rec.message_post_with_template(template.id)
            else:
                # auto-approve if approval is not required
                rec.action_approve()
599703
def from_request(cls, request):
    """"""
    mapreduce_spec = MapreduceSpec.from_json_str(request.get("mapreduce_spec"))
    mapper_spec = mapreduce_spec.mapper
    input_reader_spec_dict = json.loads(request.get("input_reader_state"),
                                        cls=json_util.JsonDecoder)
    input_reader = mapper_spec.input_reader_class().from_json(
        input_reader_spec_dict)
    initial_input_reader_spec_dict = json.loads(
        request.get("initial_input_reader_state"), cls=json_util.JsonDecoder)
    initial_input_reader = mapper_spec.input_reader_class().from_json(
        initial_input_reader_spec_dict)

    output_writer = None
    if mapper_spec.output_writer_class():
      output_writer = mapper_spec.output_writer_class().from_json(
          json.loads(request.get("output_writer_state", "{}"),
                     cls=json_util.JsonDecoder))
      assert isinstance(output_writer, mapper_spec.output_writer_class()), (
          "%s.from_json returned an instance of wrong class: %s" % (
              mapper_spec.output_writer_class(),
              output_writer.__class__))

    handler = util.try_deserialize_handler(request.get("serialized_handler"))
    if not handler:
      handler = mapreduce_spec.mapper.handler

    return cls(mapreduce_spec.params["base_path"],
               mapreduce_spec,
               str(request.get("shard_id")),
               int(request.get("slice_id")),
               input_reader,
               initial_input_reader,
               output_writer=output_writer,
               retries=int(request.get("retries")),
               handler=handler)
271961
protected Collection<GrantedAuthority> transformToSimpleAuthorities(Set<String> strAuthorities, boolean appendRolePrefix) {
		if (null != strAuthorities) {
			Collection<GrantedAuthority> authorities = new HashSet<>(strAuthorities.size());
			for (String authority : strAuthorities) {
				if (!StringUtils.isEmpty(authority)) {
					String role = authority.trim().toUpperCase(Locale.ENGLISH);
					if (appendRolePrefix) {
						authorities.add(new SimpleGrantedAuthority(getRolePrefix() + role));
					} else {
						authorities.add(new SimpleGrantedAuthority(role));
					}
				}
			}
			return authorities;
		}
		return Collections.emptyList();
	}
1215250
function gatherStateMachineRestrictions (stateMachines, permissionModel) {
  // Grab restrictions from state machines
  // -------------------------------------

  const docTasks = []

  if (!stateMachines) {
    return docTasks
  }

  for (const [name, stateMachine] of Object.entries(stateMachines)) {
    for (const restriction of (stateMachine.restrictions || [])) {
      restriction.stateMachineName = name
      docTasks.push({
        domain: 'stateMachineRestriction',
        docId: name + '_' + restriction.roleId,
        docSource: restriction,
        dao: permissionModel,
        docMaker: makePermissionDoc
      })
    }
  }

  return docTasks
}
203248
def ReadApprovalRequests(self,
                           requestor_username,
                           approval_type,
                           subject_id=None,
                           include_expired=False):
    """"""
    now = rdfvalue.RDFDatetime.Now()

    result = []
    approvals = self.approvals_by_username.get(requestor_username, {})
    for approval in itervalues(approvals):
      if approval.approval_type != approval_type:
        continue

      if subject_id and approval.subject_id != subject_id:
        continue

      if not include_expired and approval.expiration_time < now:
        continue

      result.append(approval)

    return result
1371560
def Grant(self):
    """"""

    approvals_root_urn = aff4.ROOT_URN.Add("ACL").Add(
        self.subject_urn.Path()).Add(self.delegate)
    children_urns = list(aff4.FACTORY.ListChildren(approvals_root_urn))
    if not children_urns:
      raise access_control.UnauthorizedAccess(
          "No approval found for user %s" % utils.SmartStr(self.token.username),
          subject=self.subject_urn)

    approvals = aff4.FACTORY.MultiOpen(
        children_urns, mode="r", aff4_type=Approval, token=self.token)
    found_approval_urn = None
    for approval in approvals:
      approval_reason = approval.Get(approval.Schema.REASON)
      if (utils.SmartUnicode(approval_reason) == utils.SmartUnicode(self.reason)
          and (not found_approval_urn or
               approval_reason.age > found_approval_urn.age)):
        found_approval_urn = approval.urn
        found_approval_urn.age = approval_reason.age

    if not found_approval_urn:
      raise access_control.UnauthorizedAccess(
          "No approval with reason '%s' found for user %s" % (utils.SmartStr(
              self.reason), utils.SmartStr(self.token.username)),
          subject=self.subject_urn)

    # This object must already exist.
    try:
      approval_request = aff4.FACTORY.Open(
          found_approval_urn,
          mode="rw",
          aff4_type=self.approval_type,
          token=self.token)
    except IOError:
      raise access_control.UnauthorizedAccess(
          "Approval object does not exist.", requested_access="rw")

    with approval_request:
      # We are now an approver for this request.
      approval_request.AddAttribute(
          approval_request.Schema.APPROVER(self.token.username))

    return found_approval_urn
606569
def descriptor_to_generator(cls_descriptor, cls, limit=0):
    ''

    generators = []
    for descriptor in cls_descriptor.fields_by_name.values():
        generator = _prototype_to_generator(descriptor, cls)

        if limit != 0:
            generator.set_limit(limit)

        generators.append(generator)

    obj = cls(cls_descriptor.name, *generators)
    return obj
752398
def WriteApprovalRequest(self, approval_request, cursor=None):
    """"""
    # Copy the approval_request to ensure we don't modify the source object.
    approval_request = approval_request.Copy()
    # Generate random approval id.
    approval_id_int = random.UInt64()

    grants = approval_request.grants
    approval_request.grants = None

    expiry_time = approval_request.expiration_time

    args = {
        "username_hash": mysql_utils.Hash(approval_request.requestor_username),
        "approval_type": int(approval_request.approval_type),
        "subject_id": approval_request.subject_id,
        "approval_id": approval_id_int,
        "expiration_time": mysql_utils.RDFDatetimeToTimestamp(expiry_time),
        "approval_request": approval_request.SerializeToString()
    }
    query = """
    INSERT INTO approval_request (username_hash, approval_type,
                                  subject_id, approval_id, expiration_time,
                                  approval_request)
    VALUES (%(username_hash)s, %(approval_type)s,
            %(subject_id)s, %(approval_id)s, FROM_UNIXTIME(%(expiration_time)s),
            %(approval_request)s)
    """
    cursor.execute(query, args)

    for grant in grants:
      self._GrantApproval(approval_request.requestor_username, approval_id_int,
                          grant.grantor_username, cursor)

    return _IntToApprovalID(approval_id_int)
785931
def _extract_list_from_generator(generator):
    

    extracted = []
    for i in generator:
        extracted.append(list(i))
    return extracted
62224
def _split_generators(self, dl_manager):
    
    splits = super(Imagenet2012Corrupted, self)._split_generators(dl_manager)
    validation = splits[1]
    return [validation]