void dhcpAddOption(DhcpMessage *message, uint8_t optionCode,
   const void *optionValue, size_t optionLen)
{
   size_t n;
   DhcpOption *option;

   //Point to the very first option
   n = 0;

   //Parse DHCP options
   while(1)
   {
      //Point to the current option
      option = (DhcpOption *) (message->options + n);

      //End option detected?
      if(option->code == DHCP_OPT_END)
         break;

      //Jump to next the next option
      n += sizeof(DhcpOption) + option->length;
   }

   //Sanity check
   if(optionLen <= UINT8_MAX)
   {
      //Point to the buffer where the option is to be written
      option = (DhcpOption *) (message->options + n);

      //Option code
      option->code = optionCode;
      //Option length
      option->length = (uint8_t) optionLen;
      //Option value
      osMemcpy(option->value, optionValue, optionLen);

      //Jump to next the next option
      n += sizeof(DhcpOption) + option->length;

      //Point to the buffer where the option is to be written
      option = (DhcpOption *) (message->options + n);

      //Always terminate the options field with 255
      option->code = DHCP_OPT_END;
   }
}


DhcpOption *dhcpGetOption(const DhcpMessage *message,
   size_t length, uint8_t optionCode)
{
   uint_t i;
   DhcpOption *option;

   //Make sure the DHCP header is valid
   if(length < sizeof(DhcpMessage))
      return NULL;
   //Get the length of the options field
   length -= sizeof(DhcpMessage);

   //Parse DHCP options
   for(i = 0; i < length; i++)
   {
      //Point to the current option
      option = (DhcpOption *) (message->options + i);

      //Pad option detected?
      if(option->code == DHCP_OPT_PAD)
         continue;
      //End option detected?
      if(option->code == DHCP_OPT_END)
         break;
      //Check option length
      if((i + 1) >= length || (i + 1 + option->length) >= length)
         break;

      //Current option code matches the specified one?
      if(option->code == optionCode)
         return option;

      //Jump to the next option
      i += option->length + 1;
   }

   //Specified option code not found
   return NULL;
}


bool_t enc28j60IrqHandler(NetInterface *interface)
{
   bool_t flag;
   uint8_t status;

   //This flag will be set if a higher priority task must be woken
   flag = FALSE;

   //Clear the INTIE bit, immediately after an interrupt event
   enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_INTIE);

   //Read interrupt status register
   status = enc28j60ReadReg(interface, ENC28J60_REG_EIR);

   //Link status change?
   if((status & EIR_LINKIF) != 0)
   {
      //Disable LINKIE interrupt
      enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_LINKIE);

      //Set event flag
      interface->nicEvent = TRUE;
      //Notify the TCP/IP stack of the event
      flag |= osSetEventFromIsr(&netEvent);
   }

   //Packet received?
   if((status & EIR_PKTIF) != 0)
   {
      //Disable PKTIE interrupt
      enc28j60ClearBit(interface, ENC28J60_REG_EIE, EIE_PKTIE);

      //Set event flag
      interface->nicEvent = TRUE;
      //Notify the TCP/IP stack of the event
      flag |= osSetEventFromIsr(&netEvent);
   }

   //Packet transmission complete?
   if((status & (EIR_TXIF | EIE_TXERIE)) != 0)
   {
      //Clear interrupt flags
      enc28j60ClearBit(interface, ENC28J60_REG_EIR, EIR_TXIF | EIE_TXERIE);

      //Notify the TCP/IP stack that the transmitter is ready to send
      flag |= osSetEventFromIsr(&interface->nicTxEvent);
   }

   //Once the interrupt has been serviced, the INTIE bit
   //is set again to re-enable interrupts
   enc28j60SetBit(interface, ENC28J60_REG_EIE, EIE_INTIE);

   //A higher priority task must be woken?
   return flag;
}


error_t ksz8851UpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   uint_t k;
   uint32_t crc;
   uint16_t hashTable[4];
   MacFilterEntry *entry;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Clear hash table
   osMemset(hashTable, 0, sizeof(hashTable));

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Point to the current entry
      entry = &interface->macAddrFilter[i];

      //Valid entry?
      if(entry->refCount > 0)
      {
         //Compute CRC over the current MAC address
         crc = ksz8851CalcCrc(&entry->addr, sizeof(MacAddr));
         //Calculate the corresponding index in the table
         k = (crc >> 26) & 0x3F;
         //Update hash table contents
         hashTable[k / 16] |= (1 << (k % 16));
      }
   }

   //Write the hash table to the KSZ8851 controller
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR0, hashTable[0]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR1, hashTable[1]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR2, hashTable[2]);
   ksz8851WriteReg(interface, KSZ8851_REG_MAHTR3, hashTable[3]);

   //Debug message
   TRACE_DEBUG("  MAHTR0 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR0));
   TRACE_DEBUG("  MAHTR1 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR1));
   TRACE_DEBUG("  MAHTR2 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR2));
   TRACE_DEBUG("  MAHTR3 = %04" PRIX16 "\r\n", ksz8851ReadReg(interface, KSZ8851_REG_MAHTR3));

   //Successful processing
   return NO_ERROR;
}


uint16_t lpc546xxEthReadPhyReg(uint8_t opcode, uint8_t phyAddr,
   uint8_t regAddr)
{
   uint16_t data;
   uint32_t temp;

   //Valid opcode?
   if(opcode == SMI_OPCODE_READ)
   {
      //Take care not to alter MDC clock configuration
      temp = ENET->MAC_MDIO_ADDR & ENET_MAC_MDIO_ADDR_CR_MASK;
      //Set up a read operation
      temp |= ENET_MAC_MDIO_ADDR_MOC(3) | ENET_MAC_MDIO_ADDR_MB_MASK;
      //PHY address
      temp |= ENET_MAC_MDIO_ADDR_PA(phyAddr);
      //Register address
      temp |= ENET_MAC_MDIO_ADDR_RDA(regAddr);

      //Start a read operation
      ENET->MAC_MDIO_ADDR = temp;
      //Wait for the read to complete
      while((ENET->MAC_MDIO_ADDR & ENET_MAC_MDIO_ADDR_MB_MASK) != 0)
      {
      }

      //Get register value
      data = ENET->MAC_MDIO_DATA & ENET_MAC_MDIO_DATA_MD_MASK;
   }
   else
   {
      //The MAC peripheral only supports standard Clause 22 opcodes
      data = 0;
   }

   //Return the value of the PHY register
   return data;
}


error_t lpc546xxEthUpdateMacAddrFilter(NetInterface *interface)
{
   uint_t i;
   bool_t acceptMulticast;

   //Debug message
   TRACE_DEBUG("Updating MAC filter...\r\n");

   //Set the MAC address of the station
   ENET->MAC_ADDR_LOW = interface->macAddr.w[0] | (interface->macAddr.w[1] << 16);
   ENET->MAC_ADDR_HIGH = interface->macAddr.w[2];

   //This flag will be set if multicast addresses should be accepted
   acceptMulticast = FALSE;

   //The MAC address filter contains the list of MAC addresses to accept
   //when receiving an Ethernet frame
   for(i = 0; i < MAC_ADDR_FILTER_SIZE; i++)
   {
      //Valid entry?
      if(interface->macAddrFilter[i].refCount > 0)
      {
         //Accept multicast addresses
         acceptMulticast = TRUE;
         //We are done
         break;
      }
   }

   //Enable the reception of multicast frames if necessary
   if(acceptMulticast)
   {
      ENET->MAC_FRAME_FILTER |= ENET_MAC_FRAME_FILTER_PM_MASK;
   }
   else
   {
      ENET->MAC_FRAME_FILTER &= ~ENET_MAC_FRAME_FILTER_PM_MASK;
   }

   //Successful processing
   return NO_ERROR;
}


error_t lpc546xxEthReceivePacket(NetInterface *interface)
{
   error_t error;
   size_t n;
   NetRxAncillary ancillary;

   //The current buffer is available for reading?
   if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_OWN) == 0)
   {
      //FD and LD flags should be set
      if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_FD) != 0 &&
         (rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_LD) != 0)
      {
         //Make sure no error occurred
         if((rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_ES) == 0)
         {
            //Retrieve the length of the frame
            n = rxDmaDesc[rxIndex].rdes3 & ENET_RDES3_PL;
            //Limit the number of data to read
            n = MIN(n, LPC546XX_ETH_RX_BUFFER_SIZE);

            //Additional options can be passed to the stack along with the packet
            ancillary = NET_DEFAULT_RX_ANCILLARY;

            //Pass the packet to the upper layer
            nicProcessPacket(interface, rxBuffer[rxIndex], n, &ancillary);

            //Valid packet received
            error = NO_ERROR;
         }
         else
         {
            //The received packet contains an error
            error = ERROR_INVALID_PACKET;
         }
      }
      else
      {
         //The packet is not valid
         error = ERROR_INVALID_PACKET;
      }

      //Set the start address of the buffer
      rxDmaDesc[rxIndex].rdes0 = (uint32_t) rxBuffer[rxIndex];
      //Give the ownership of the descriptor back to the DMA
      rxDmaDesc[rxIndex].rdes3 = ENET_RDES3_OWN | ENET_RDES3_IOC | ENET_RDES3_BUF1V;

      //Increment index and wrap around if necessary
      if(++rxIndex >= LPC546XX_ETH_RX_BUFFER_COUNT)
      {
         rxIndex = 0;
      }
   }
   else
   {
      //No more data in the receive buffer
      error = ERROR_BUFFER_EMPTY;
   }

   //Clear RBU flag to resume processing
   ENET->DMA_CH[0].DMA_CHX_STAT = ENET_DMA_CH_DMA_CHX_STAT_RBU_MASK;
   //Instruct the DMA to poll the receive descriptor list
   ENET->DMA_CH[0].DMA_CHX_RXDESC_TAIL_PTR = 0;

   //Return status code
   return error;
}


error_t tja1101Init(NetInterface *interface)
{
   uint16_t value;

   //Debug message
   TRACE_INFO("Initializing TJA1101...\r\n");

   //Undefined PHY address?
   if(interface->phyAddr >= 32)
   {
      //Use the default address
      interface->phyAddr = TJA1101_PHY_ADDR;
   }

   //Initialize serial management interface
   if(interface->smiDriver != NULL)
   {
      interface->smiDriver->init();
   }

   //Initialize external interrupt line driver
   if(interface->extIntDriver != NULL)
   {
      interface->extIntDriver->init();
   }

   //Reset PHY transceiver
   tja1101WritePhyReg(interface, TJA1101_BASIC_CTRL,
      TJA1101_BASIC_CTRL_RESET);

   //Wait for the reset to complete
   while(tja1101ReadPhyReg(interface, TJA1101_BASIC_CTRL) &
      TJA1101_BASIC_CTRL_RESET)
   {
   }

   //Dump PHY registers for debugging purpose
   tja1101DumpPhyReg(interface);

   //Enable configuration register access
   value = tja1101ReadPhyReg(interface, TJA1101_EXTENDED_CTRL);
   value |= TJA1101_EXTENDED_CTRL_CONFIG_EN;
   tja1101WritePhyReg(interface, TJA1101_EXTENDED_CTRL, value);

   //Select RMII mode (25MHz XTAL)
   value = tja1101ReadPhyReg(interface, TJA1101_CONFIG1);
   value &= ~TJA1101_CONFIG1_MII_MODE;
   value |= TJA1101_CONFIG1_MII_MODE_RMII_25MHZ;
   tja1101WritePhyReg(interface, TJA1101_CONFIG1, value);

   //The PHY is configured for autonomous operation
   value = tja1101ReadPhyReg(interface, TJA1101_COMM_CTRL);
   value |= TJA1101_COMM_CTRL_AUTO_OP;
   tja1101WritePhyReg(interface, TJA1101_COMM_CTRL, value);

   //Force the TCP/IP stack to poll the link state at startup
   interface->phyEvent = TRUE;
   //Notify the TCP/IP stack of the event
   osSetEvent(&netEvent);

   //Successful initialization
   return NO_ERROR;
}


    def to_yaml(self, data, options=None):
        """
        Given some Python data, produces YAML output.
        """
        options = options or {}

        if yaml is None:
            raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.")

        return yaml.dump(self.to_simple(data, options))


def check_password(password, encoded, setter=None, preferred='default'):
    """
    Returns a boolean of whether the raw password matches the three
    part encoded digest.

    If setter is specified, it'll be called when you need to
    regenerate the password.
    """
    if password is None or not is_password_usable(encoded):
        return False

    preferred = get_hasher(preferred)
    hasher = identify_hasher(encoded)

    must_update = hasher.algorithm != preferred.algorithm
    if not must_update:
        must_update = preferred.must_update(encoded)
    is_correct = hasher.verify(password, encoded)
    if setter and is_correct and must_update:
        setter(password)
    return is_correct


    def test_filename(self):
        tmpname = mktemp('', 'mmap')
        fp = memmap(tmpname, dtype=self.dtype, mode='w+',
                       shape=self.shape)
        abspath = os.path.abspath(tmpname)
        fp[:] = self.data[:]
        self.assertEqual(abspath, fp.filename)
        b = fp[:1]
        self.assertEqual(abspath, b.filename)
        del b
        del fp
        os.unlink(tmpname)


    def tearDown(self):
        if os.path.isfile(self.filename):
            os.unlink(self.filename)


        def visit_Call(self, call):
            if call.func.id in INVALID_CALLS:
                raise Exception("invalid function: %s" % call.func.id)


    def _expand(self, key_material):
        output = [b""]
        counter = 1

        while (self._algorithm.digest_size // 8) * len(output) < self._length:
            h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
            h.update(output[-1])
            h.update(self._info)
            h.update(six.int2byte(counter))
            output.append(h.finalize())
            counter += 1

        return b"".join(output)[:self._length]


    def _update_load_status(self, ok: bool) -> None:
        """Update the load status after a page finished loading.

        Needs to be called by subclasses to trigger a load status update, e.g.
        as a response to a loadFinished signal.
        """
        if ok and not self._has_ssl_errors:
            if self.url().scheme() == 'https':
                self._set_load_status(usertypes.LoadStatus.success_https)
            else:
                self._set_load_status(usertypes.LoadStatus.success)
        elif ok:
            self._set_load_status(usertypes.LoadStatus.warn)
        else:
            self._set_load_status(usertypes.LoadStatus.error)


    async def on_send_leave_request(
        self, origin: str, content: JsonDict, room_id: str


    async def on_GET(self, origin, content, query, context):
        return await self.handler.on_context_state_request(
            origin,
            context,
            parse_string_from_args(query, "event_id", None, required=False),
        )


    async def on_GET(self, origin, _content, query, context, user_id):
        """
        Args:
            origin (unicode): The authenticated server_name of the calling server

            _content (None): (GETs don't have bodies)

            query (dict[bytes, list[bytes]]): Query params from the request.

            **kwargs (dict[unicode, unicode]): the dict mapping keys to path
                components as specified in the path match regexp.

        Returns:
            Tuple[int, object]: (response code, response object)
        """
        versions = query.get(b"ver")
        if versions is not None:
            supported_versions = [v.decode("utf-8") for v in versions]
        else:
            supported_versions = ["1"]

        content = await self.handler.on_make_join_request(
            origin, context, user_id, supported_versions=supported_versions
        )
        return 200, content


def _is_javascript_scheme(s):
    if _is_image_dataurl(s):
        return None
    return _is_possibly_malicious_scheme(s)


  def __setstate__(self, state):
    """Restore from pickled state."""
    self.__dict__ = state
    self._lock = threading.Lock()
    self._descriptor_cache = weakref.WeakKeyDictionary()
    self._key_for_call_stats = self._get_key_for_call_stats()


  def testValuesInVariable(self):
    indices = constant_op.constant([[1]], dtype=dtypes.int64)
    values = variables.Variable([1], trainable=False, dtype=dtypes.float32)
    shape = constant_op.constant([1], dtype=dtypes.int64)

    sp_input = sparse_tensor.SparseTensor(indices, values, shape)
    sp_output = sparse_ops.sparse_add(sp_input, sp_input)

    with test_util.force_cpu():
      self.evaluate(variables.global_variables_initializer())
      output = self.evaluate(sp_output)
      self.assertAllEqual(output.values, [2])


    def skip(self, type):
        if type == TType.STOP:
            return
        elif type == TType.BOOL:
            self.readBool()
        elif type == TType.BYTE:
            self.readByte()
        elif type == TType.I16:
            self.readI16()
        elif type == TType.I32:
            self.readI32()
        elif type == TType.I64:
            self.readI64()
        elif type == TType.DOUBLE:
            self.readDouble()
        elif type == TType.FLOAT:
            self.readFloat()
        elif type == TType.STRING:
            self.readString()
        elif type == TType.STRUCT:
            name = self.readStructBegin()
            while True:
                (name, type, id) = self.readFieldBegin()
                if type == TType.STOP:
                    break
                self.skip(type)
                self.readFieldEnd()
            self.readStructEnd()
        elif type == TType.MAP:
            (ktype, vtype, size) = self.readMapBegin()
            for _ in range(size):
                self.skip(ktype)
                self.skip(vtype)
            self.readMapEnd()
        elif type == TType.SET:
            (etype, size) = self.readSetBegin()
            for _ in range(size):
                self.skip(etype)
            self.readSetEnd()
        elif type == TType.LIST:
            (etype, size) = self.readListBegin()
            for _ in range(size):
                self.skip(etype)
            self.readListEnd()


def _new_fixed_fetch(validate_certificate):

    def fixed_fetch(
        url,
        payload=None,
        method="GET",
        headers={},
        allow_truncated=False,
        follow_redirects=True,
        deadline=None,
    ):
        return fetch(
            url,
            payload=payload,
            method=method,
            headers=headers,
            allow_truncated=allow_truncated,
            follow_redirects=follow_redirects,
            deadline=deadline,
            validate_certificate=validate_certificate,
        )

    return fixed_fetch


    def _request(
        self,
        conn,
        host,
        absolute_uri,
        request_uri,
        method,
        body,
        headers,
        redirections,
        cachekey,


def _normalize_headers(headers):
    return dict(
        [
            (key.lower(), NORMALIZE_SPACE.sub(value, " ").strip())
            for (key, value) in headers.iteritems()
        ]
    )


def _parse_cache_control(headers):
    retval = {}
    if "cache-control" in headers:
        parts = headers["cache-control"].split(",")
        parts_with_args = [
            tuple([x.strip().lower() for x in part.split("=", 1)])
            for part in parts
            if -1 != part.find("=")
        ]
        parts_wo_args = [
            (name.strip().lower(), 1) for name in parts if -1 == name.find("=")
        ]
        retval = dict(parts_with_args + parts_wo_args)
    return retval


    def __init__(self, desc, response, content):
        self.response = response
        self.content = content
        HttpLib2Error.__init__(self, desc)


def _updateCache(request_headers, response_headers, content, cache, cachekey):
    if cachekey:
        cc = _parse_cache_control(request_headers)
        cc_response = _parse_cache_control(response_headers)
        if "no-store" in cc or "no-store" in cc_response:
            cache.delete(cachekey)
        else:
            info = email.message.Message()
            for key, value in response_headers.items():
                if key not in ["status", "content-encoding", "transfer-encoding"]:
                    info[key] = value

            # Add annotations to the cache to indicate what headers
            # are variant for this request.
            vary = response_headers.get("vary", None)
            if vary:
                vary_headers = vary.lower().replace(" ", "").split(",")
                for header in vary_headers:
                    key = "-varied-%s" % header
                    try:
                        info[key] = request_headers[header]
                    except KeyError:
                        pass

            status = response_headers.status
            if status == 304:
                status = 200

            status_header = "status: %d\r\n" % status

            try:
                header_str = info.as_string()
            except UnicodeEncodeError:
                setattr(info, "_write_headers", _bind_write_headers(info))
                header_str = info.as_string()

            header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
            text = b"".join(
                [status_header.encode("utf-8"), header_str.encode("utf-8"), content]
            )

            cache.set(cachekey, text)


def test_digest_object():
    credentials = ("joe", "password")
    host = None
    request_uri = "/test/digest/"
    headers = {}
    response = {
        "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"'
    }
    content = b""

    d = httplib2.DigestAuthentication(
        credentials, host, request_uri, headers, response, content, None
    )
    d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46")
    our_request = "authorization: " + headers["authorization"]
    working_request = (
        'authorization: Digest username="joe", realm="myrealm", '
        'nonce="KBAA=35", uri="/test/digest/"'
        + ', algorithm=MD5, response="de6d4a123b80801d0e94550411b6283f", '
        'qop=auth, nc=00000001, cnonce="33033375ec278a46"'
    )
    assert our_request == working_request


    def builtin_roles(self):
        return self._builtin_roles


def parse_jwt_token(request: func.HttpRequest) -> Result[UserInfo]:
    """Obtains the Access Token from the Authorization Header"""
    token_str = get_auth_token(request)
    if token_str is None:
        return Error(
            code=ErrorCode.INVALID_REQUEST,
            errors=["unable to find authorization token"],
        )

    # This token has already been verified by the azure authentication layer
    token = jwt.decode(token_str, options={"verify_signature": False})

    application_id = UUID(token["appid"]) if "appid" in token else None
    object_id = UUID(token["oid"]) if "oid" in token else None
    upn = token.get("upn")
    return UserInfo(application_id=application_id, object_id=object_id, upn=upn)


def main() -> None:
    formatter = argparse.ArgumentDefaultsHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=formatter)
    parser.add_argument("resource_group")
    parser.add_argument("storage_account")
    parser.add_argument("admins", type=UUID, nargs="*")
    args = parser.parse_args()

    client = get_client_from_cli_profile(StorageManagementClient)
    storage_keys = client.storage_accounts.list_keys(
        args.resource_group, args.storage_account
    )
    table_service = TableService(
        account_name=args.storage_account, account_key=storage_keys.keys[0].value
    )
    update_admins(table_service, args.resource_group, args.admins)


def test_bad_request(settings):
    class BadRequestSpider(ResponseSpider):
        custom_settings = {'HTTPERROR_ALLOW_ALL': True}

        def start_requests(self):
            yield SplashRequest(self.url, endpoint='execute',
                                args={'lua_source': DEFAULT_SCRIPT, 'wait': 'bar'})

    class GoodRequestSpider(ResponseSpider):
        custom_settings = {'HTTPERROR_ALLOW_ALL': True}

        def start_requests(self):
            yield SplashRequest(self.url, endpoint='execute',
                                args={'lua_source': DEFAULT_SCRIPT})

    items, url, crawler = yield crawl_items(BadRequestSpider, HelloWorld,
                                            settings)
    resp = items[0]['response']
    assert resp.status == 400
    assert resp.splash_response_status == 400

    items, url, crawler = yield crawl_items(GoodRequestSpider, Http400Resource,
                                            settings)
    resp = items[0]['response']
    assert resp.status == 400
    assert resp.splash_response_status == 200


def test_adjust_timeout():
    mw = _get_mw()
    req1 = scrapy.Request("http://example.com", meta = {
        'splash': {'args': {'timeout': 60, 'html': 1}},

        # download_timeout is always present,
        # it is set by DownloadTimeoutMiddleware
        'download_timeout': 30,
    })
    req1 = mw.process_request(req1, None)
    assert req1.meta['download_timeout'] > 60

    req2 = scrapy.Request("http://example.com", meta = {
        'splash': {'args': {'html': 1}},
        'download_timeout': 30,
    })
    req2 = mw.process_request(req2, None)
    assert req2.meta['download_timeout'] == 30


    def render_GET(self, request):
        request.setHeader(b'content-type', to_bytes(self.content_type))
        for name, value in self.extra_headers.items():
            request.setHeader(to_bytes(name), to_bytes(value))
        request.setResponseCode(self.status_code)
        return to_bytes(self.html)


def temppath():
    path = tempfile.mktemp()
    try:
        yield path
    finally:
        if os.path.exists(path):
            if os.path.isfile(path):
                os.remove(path)
            else:
                shutil.rmtree(path)


    def test_session_with_cookie_followed_by_another_header(self, httpbin):
        """
        Make sure headers don’t get mutated — <https://github.com/httpie/httpie/issues/1126>
        """
        self.start_session(httpbin)
        session_data = {
            "headers": {
                "cookie": "...",
                "zzz": "..."
            }
        }
        session_path = self.config_dir / 'session-data.json'
        session_path.write_text(json.dumps(session_data))
        r = http('--session', str(session_path), 'GET', httpbin.url + '/get',
                 env=self.env())
        assert HTTP_OK in r
        assert 'Zzz' in r


    def test_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin):
        session = Session(self.config_dir)
        session['cookies'] = initial_cookie
        session.remove_cookies([expired_cookie])
        assert expired_cookie not in session.cookies


def needs_clamp(t, encoding):
    if encoding not in (Encoding.ABI, Encoding.JSON_ABI):
        return False
    if isinstance(t, (ByteArrayLike, DArrayType)):
        if encoding == Encoding.JSON_ABI:
            # don't have bytestring size bound from json, don't clamp
            return False
        return True
    if isinstance(t, BaseType) and t.typ not in ("int256", "uint256", "bytes32"):
        return True
    if isinstance(t, SArrayType):
        return needs_clamp(t.subtype, encoding)
    if isinstance(t, TupleLike):
        return any(needs_clamp(m, encoding) for m in t.tuple_members())
    return False


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String encoding = request.getHeader("Accept-Encoding");
        boolean supportsGzip = (encoding != null && encoding.toLowerCase().indexOf("gzip") > -1);
        SessionTerminal st = (SessionTerminal) request.getSession(true).getAttribute("terminal");
        if (st == null || st.isClosed()) {
            st = new SessionTerminal(getCommandProcessor(), getThreadIO());
            request.getSession().setAttribute("terminal", st);
        }
        String str = request.getParameter("k");
        String f = request.getParameter("f");
        String dump = st.handle(str, f != null && f.length() > 0);
        if (dump != null) {
            if (supportsGzip) {
                response.setHeader("Content-Encoding", "gzip");
                response.setHeader("Content-Type", "text/html");
                try {
                    GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream());
                    gzos.write(dump.getBytes());
                    gzos.close();
                } catch (IOException ie) {
                    LOG.info("Exception writing response: ", ie);
                }
            } else {
                response.getOutputStream().write(dump.getBytes());
            }
        }
    }


   public void setExpirationTime(int expirationTime) {
     this.expirationTime = expirationTime;
   }


    protected ObjectStreamClass readClassDescriptor()
            throws IOException, ClassNotFoundException {
        int type = read();
        if (type < 0) {
            throw new EOFException();
        }
        switch (type) {
            case ThrowableObjectOutputStream.TYPE_EXCEPTION:
                return ObjectStreamClass.lookup(Exception.class);
            case ThrowableObjectOutputStream.TYPE_STACKTRACEELEMENT:
                return ObjectStreamClass.lookup(StackTraceElement.class);
            case ThrowableObjectOutputStream.TYPE_FAT_DESCRIPTOR:
                return super.readClassDescriptor();
            case ThrowableObjectOutputStream.TYPE_THIN_DESCRIPTOR:
                String className = readUTF();
                Class<?> clazz = loadClass(className);
                return ObjectStreamClass.lookup(clazz);
            default:
                throw new StreamCorruptedException(
                        "Unexpected class descriptor type: " + type);
        }
    }


	public static SecretKey decryptCEK(final SecretKey kek,
					   final byte[] iv,
					   final AuthenticatedCipherText authEncrCEK,
					   final int keyLength,
					   final Provider provider)
		throws JOSEException {

		byte[] keyBytes = AESGCM.decrypt(kek, iv, authEncrCEK.getCipherText(), new byte[0], authEncrCEK.getAuthenticationTag(), provider);

		if (ByteUtils.bitLength(keyBytes) != keyLength) {

			throw new KeyLengthException("CEK key length mismatch: " + ByteUtils.bitLength(keyBytes) + " != " + keyLength);
		}

		return new SecretKeySpec(keyBytes, "AES");
	}


    private String loginUser(URI hostUri) throws Throwable {
        URI usersLink = UriUtils.buildUri(hostUri, UserService.FACTORY_LINK);
        // wait for factory availability
        this.host.waitForReplicatedFactoryServiceAvailable(usersLink);

        String basicAuth = BasicAuthenticationUtils.constructBasicAuth(adminUser, adminUser);
        URI loginUri = UriUtils.buildUri(hostUri, ServiceUriPaths.CORE_AUTHN_BASIC);
        AuthenticationRequest login = new AuthenticationRequest();
        login.requestType = AuthenticationRequest.AuthenticationRequestType.LOGIN;

        String[] authToken = new String[1];
        authToken[0] = null;

        Date exp = this.host.getTestExpiration();
        while (new Date().before(exp)) {
            Operation loginPost = Operation.createPost(loginUri)
                    .setBody(login)
                    .addRequestHeader(Operation.AUTHORIZATION_HEADER, basicAuth)
                    .forceRemote()
                    .setCompletion((op, ex) -> {
                        if (ex != null) {
                            this.host.completeIteration();
                            return;
                        }
                        authToken[0] = op.getResponseHeader(Operation.REQUEST_AUTH_TOKEN_HEADER);
                        this.host.completeIteration();
                    });

            this.host.testStart(1);
            this.host.send(loginPost);
            this.host.testWait();

            if (authToken[0] != null) {
                break;
            }
            Thread.sleep(250);
        }

        if (new Date().after(exp)) {
            throw new TimeoutException();
        }

        assertNotNull(authToken[0]);

        return authToken[0];
    }


	private void displayVerificationWarningDialog(final Contact contact, final Invite invite) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.verify_omemo_keys);
		View view = getLayoutInflater().inflate(R.layout.dialog_verify_fingerprints, null);
		final CheckBox isTrustedSource = view.findViewById(R.id.trusted_source);
		TextView warning = view.findViewById(R.id.warning);
		warning.setText(JidDialog.style(this, R.string.verifying_omemo_keys_trusted_source, contact.getJid().asBareJid().toEscapedString(), contact.getDisplayName()));
		builder.setView(view);
		builder.setPositiveButton(R.string.confirm, (dialog, which) -> {
			if (isTrustedSource.isChecked() && invite.hasFingerprints()) {
				xmppConnectionService.verifyFingerprints(contact, invite.getFingerprints());
			}
			switchToConversation(contact, invite.getBody());
		});
		builder.setNegativeButton(R.string.cancel, (dialog, which) -> StartConversationActivity.this.finish());
		AlertDialog dialog = builder.create();
		dialog.setCanceledOnTouchOutside(false);
		dialog.setOnCancelListener(dialog1 -> StartConversationActivity.this.finish());
		dialog.show();
	}


	public void checkAccess(ThreadGroup g) {
		if (RobocodeProperties.isSecurityOff()) {
			return;
		}
		Thread c = Thread.currentThread();

		if (isSafeThread(c)) {
			return;
		}
		super.checkAccess(g);

		final ThreadGroup cg = c.getThreadGroup();

		if (cg == null) {
			// What the heck is going on here?  JDK 1.3 is sending me a dead thread.
			// This crashes the entire jvm if I don't return here.
			return;
		}

		// Bug fix #382 Unable to run robocode.bat -- Access Control Exception
		if ("SeedGenerator Thread".equals(c.getName()) && "SeedGenerator ThreadGroup".equals(cg.getName())) {
			return; // The SeedGenerator might create a thread, which needs to be silently ignored
		}

		IHostedThread robotProxy = threadManager.getLoadedOrLoadingRobotProxy(c);

		if (robotProxy == null) {
			throw new AccessControlException("Preventing " + c.getName() + " from access to " + g.getName());
		}

		if (cg.activeCount() > 5) {
			String message = "Robots are only allowed to create up to 5 threads!";

			robotProxy.punishSecurityViolation(message);
			throw new AccessControlException(message);
		}
	}


    final void set(CharSequence name, String value) {
        final AsciiString normalizedName = normalizeName(name);
        requireNonNull(value, "value");
        final int h = normalizedName.hashCode();
        final int i = index(h);
        remove0(h, i, normalizedName);
        add0(h, i, normalizedName, value);
    }


    public void removingANameForASecondTimeShouldReturnFalse() {
        final HttpHeadersBase headers = newEmptyHeaders();
        headers.add("name1", "value1");
        headers.add("name2", "value2");
        assertThat(headers.remove("name2")).isTrue();
        assertThat(headers.remove("name2")).isFalse();
    }


    public void subsetOfHeadersShouldNotBeEquivalent() {
        final HttpHeadersBase headers1 = newEmptyHeaders();
        headers1.add("name1", "value1");
        headers1.add("name2", "value2");
        final HttpHeadersBase headers2 = newEmptyHeaders();
        headers1.add("name1", "value1");
        assertThat(headers1).isNotEqualTo(headers2);
    }


    public void testCopy() throws Exception {
        HttpHeadersBase headers = newEmptyHeaders();
        headers.addLong("long", Long.MAX_VALUE);
        headers.addInt("int", Integer.MIN_VALUE);
        headers.addDouble("double", Double.MAX_VALUE);
        headers.addFloat("float", Float.MAX_VALUE);
        final long millis = System.currentTimeMillis();
        headers.addTimeMillis("millis", millis);
        headers.addObject("object", "Hello World");
        headers.add("name", "value");

        final HttpHeadersBase oldHeaders = headers;
        headers = newEmptyHeaders();
        headers.add(oldHeaders);

        assertThat(headers.containsLong("long", Long.MAX_VALUE)).isTrue();
        assertThat(headers.containsLong("long", Long.MIN_VALUE)).isFalse();

        assertThat(headers.containsInt("int", Integer.MIN_VALUE)).isTrue();
        assertThat(headers.containsInt("int", Integer.MAX_VALUE)).isFalse();

        assertThat(headers.containsDouble("double", Double.MAX_VALUE)).isTrue();
        assertThat(headers.containsDouble("double", Double.MIN_VALUE)).isFalse();

        assertThat(headers.containsFloat("float", Float.MAX_VALUE)).isTrue();
        assertThat(headers.containsFloat("float", Float.MIN_VALUE)).isFalse();

        assertThat(headers.containsTimeMillis("millis", millis)).isTrue();
        // This test doesn't work on midnight, January 1, 1970 UTC
        assertThat(headers.containsTimeMillis("millis", 0)).isFalse();

        assertThat(headers.containsObject("object", "Hello World")).isTrue();
        assertThat(headers.containsObject("object", "")).isFalse();

        assertThat(headers.contains("name", "value")).isTrue();
        assertThat(headers.contains("name", "value1")).isFalse();
    }


    public void multipleTestingOfSameClass() throws Exception {
        assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
            .isEmpty();
        assertThat(ConstraintViolations.format(validator.validate(new CorrectExample())))
            .isEmpty();
        assertThat(TestLoggerFactory.getAllLoggingEvents())
            .isEmpty();
    }


        public void validateFail3(ViolationCollector col) {
            col.addViolation(FAILED + "3");
        }


    public void addViolation(String message) {
        violationOccurred = true;
        String messageTemplate = escapeEl(message);
        context.buildConstraintViolationWithTemplate(messageTemplate)
                .addConstraintViolation();
    }


  public boolean deleteSynchronously(String mediaPackageId) throws SearchException, UnauthorizedException,
          NotFoundException {
    SearchResult result;
    try {
      result = solrRequester.getForWrite(new SearchQuery().withId(mediaPackageId));
      if (result.getItems().length == 0) {
        logger.warn(
                "Can not delete mediapackage {}, which is not available for the current user to delete from the search index.",
                mediaPackageId);
        return false;
      }
      logger.info("Removing mediapackage {} from search index", mediaPackageId);

      Date now = new Date();
      try {
        persistence.deleteMediaPackage(mediaPackageId, now);
        logger.info("Removed mediapackage {} from search persistence", mediaPackageId);
      } catch (NotFoundException e) {
        // even if mp not found in persistence, it might still exist in search index.
        logger.info("Could not find mediapackage with id {} in persistence, but will try remove it from index, anyway.",
                mediaPackageId);
      } catch (SearchServiceDatabaseException e) {
        logger.error("Could not delete media package with id {} from persistence storage", mediaPackageId);
        throw new SearchException(e);
      }

      return indexManager.delete(mediaPackageId, now);
    } catch (SolrServerException e) {
      logger.info("Could not delete media package with id {} from search index", mediaPackageId);
      throw new SearchException(e);
    }
  }


    public boolean isValid(String value, ConstraintValidatorContext context) {
      long longValue = 0;
      boolean failed = false;
      String errorMessage = "";
      try {
        longValue = Long.parseLong(value);
      } catch (NumberFormatException ex) {
        failed = true;
        errorMessage = String.format("Invalid integer value: '%s'", value);
      }

      if (!failed && longValue < 0) {
        failed = true;
        errorMessage = String.format("Expected positive integer value, got: '%s'", value);
      }

      if (!failed) {
        return true;
      }

      LOG.warn(errorMessage);
      context.buildConstraintViolationWithTemplate(errorMessage).addConstraintViolation();

      return false;
    }


    default boolean contains(String name) {
        return get(name, Object.class).isPresent();
    }


    public Argument<Publisher> argumentType() {
        return Argument.of(Publisher.class);
    }


    default OptionalLong contentLength() {
        Optional<Long> optional = getFirst(HttpHeaders.CONTENT_LENGTH, Long.class);
        return optional.map(OptionalLong::of).orElseGet(OptionalLong::empty);
    }


    public void shouldNotIncludeCommitFromAnotherBranchInGetLatestModifications() throws Exception {
        Modification lastCommit = hgCommand.latestOneModificationAsModifications().get(0);

        makeACommitToSecondBranch();
        hg(workingDirectory, "pull").runOrBomb(null);
        Modification actual = hgCommand.latestOneModificationAsModifications().get(0);
        assertThat(actual, is(lastCommit));
        assertThat(actual.getComment(), is(lastCommit.getComment()));
    }


error_t nicSendPacket(NetInterface *interface, const NetBuffer *buffer,
   size_t offset, NetTxAncillary *ancillary)
{
   error_t error;
   bool_t status;

   //Gather entropy
   netContext.entropy += netGetSystemTickCount();

#if (TRACE_LEVEL >= TRACE_LEVEL_DEBUG)
   //Retrieve the length of the packet
   size_t length = netBufferGetLength(buffer) - offset;

   //Debug message
   TRACE_DEBUG("Sending packet (%" PRIuSIZE " bytes)...\r\n", length);
   TRACE_DEBUG_NET_BUFFER("  ", buffer, offset, length);
#endif

   //Check whether the interface is enabled for operation
   if(interface->configured && interface->nicDriver != NULL)
   {
      //Loopback interface?
      if(interface->nicDriver->type == NIC_TYPE_LOOPBACK)
      {
         //The loopback interface is always available
         status = TRUE;
      }
      else
      {
         //Wait for the transmitter to be ready to send
         status = osWaitForEvent(&interface->nicTxEvent, NIC_MAX_BLOCKING_TIME);
      }

      //Check whether the specified event is in signaled state
      if(status)
      {
         //Disable interrupts
         interface->nicDriver->disableIrq(interface);

         //Send the packet
         error = interface->nicDriver->sendPacket(interface, buffer, offset,
            ancillary);

         //Re-enable interrupts if necessary
         if(interface->configured)
         {
            interface->nicDriver->enableIrq(interface);
         }
      }
      else
      {
         //If the transmitter is busy, then drop the packet
         error = NO_ERROR;
      }
   }
   else
   {
      //Report an error
      error = ERROR_INVALID_INTERFACE;
   }

   //Return status code
   return error;
}


    private void initAndSaveDocument(XWikiContext context, XWikiDocument newDocument, String title, String template,
        String parent) throws XWikiException
    {
        XWiki xwiki = context.getWiki();
        DocumentReferenceResolver<String> resolver = getCurrentMixedDocumentReferenceResolver();

        // Set the locale and default locale, considering that we're creating the original version of the document
        // (not a translation).
        newDocument.setLocale(Locale.ROOT);
        if (newDocument.getDefaultLocale() == Locale.ROOT) {
            newDocument.setDefaultLocale(xwiki.getLocalePreference(context));
        }

        // Copy the template.
        DocumentReference templateReference = resolver.resolve(template);
        newDocument.readFromTemplate(templateReference, context);

        // Set the parent field.
        if (!StringUtils.isEmpty(parent)) {
            DocumentReference parentReference = resolver.resolve(parent);
            newDocument.setParentReference(parentReference);
        }

        // Set the document title
        if (title != null) {
            newDocument.setTitle(title);
        }

        // Set the author and creator.
        DocumentReference currentUserReference = context.getUserReference();
        newDocument.setAuthorReference(currentUserReference);
        newDocument.setCreatorReference(currentUserReference);

        // Make sure the user is allowed to make this modification
        xwiki.checkSavingDocument(currentUserReference, newDocument, context);

        xwiki.saveDocument(newDocument, context);
    }


    public void existingDocumentFromUIDeprecated() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI space=X&page=Y
        when(mockRequest.getParameter("space")).thenReturn("X");
        when(mockRequest.getParameter("page")).thenReturn("Y");

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note: We are creating X.Y since the deprecated parameters were creating terminal documents by default.
        verify(mockURLFactory).createURL("X", "Y", "edit", "template=&parent=Main.WebHome&title=Y", null, "xwiki",
            context);
    }


    public void existingDocumentFromUITemplateProviderSpecifiedRestrictionExists() throws Exception
    {
        // current document = xwiki:Main.WebHome
        DocumentReference documentReference = new DocumentReference("xwiki", Arrays.asList("Main"), "WebHome");
        XWikiDocument document = mock(XWikiDocument.class);
        when(document.getDocumentReference()).thenReturn(documentReference);
        when(document.isNew()).thenReturn(false);
        when(document.getLocalReferenceMaxLength()).thenReturn(255);
        context.setDoc(document);

        // Submit from the UI spaceReference=X&name=Y&templateProvider=XWiki.MyTemplateProvider
        String templateProviderFullName = "XWiki.MyTemplateProvider";
        String spaceReferenceString = "X";
        when(mockRequest.getParameter("spaceReference")).thenReturn(spaceReferenceString);
        when(mockRequest.getParameter("name")).thenReturn("Y");
        when(mockRequest.getParameter("templateprovider")).thenReturn(templateProviderFullName);

        // Mock 1 existing template provider that allows usage in target space.
        mockExistingTemplateProviders(templateProviderFullName,
            new DocumentReference("xwiki", Arrays.asList("XWiki"), "MyTemplateProvider"), Arrays.asList("X"));

        // Run the action
        String result = action.render(context);

        // The tests are below this line!

        // Verify null is returned (this means the response has been returned)
        assertNull(result);

        // Note1: We are allowed to create anything under space X, be it a terminal or a non-terminal document.
        // Note2: We are creating X.Y and using the template extracted from the template provider.
        verify(mockURLFactory).createURL("X.Y", "WebHome", "edit",
            "template=XWiki.MyTemplate&parent=Main.WebHome&title=Y", null, "xwiki", context);
    }


    public String invokeServletAndReturnAsString(String url, XWikiContext xwikiContext)
    {

        HttpServletRequest servletRequest = xwikiContext.getRequest();
        HttpServletResponse servletResponse = xwikiContext.getResponse();

        try {
            return IncludeServletAsString.invokeServletAndReturnAsString(url, servletRequest, servletResponse);
        } catch (Exception e) {
            LOGGER.warn("Exception including url: " + url, e);
            return "Exception including \"" + url + "\", see logs for details.";
        }

    }


    public void translate(ServerEntityHeadLookPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (packet.getEntityId() == session.getPlayerEntity().getEntityId()) {
            entity = session.getPlayerEntity();
        }

        if (entity == null) return;

        entity.updateHeadLookRotation(session, packet.getHeadYaw());
    }


    public void translate(ServerPlayerActionAckPacket packet, GeyserSession session) {
        ChunkUtils.updateBlock(session, packet.getNewState(), packet.getPosition());
        if (packet.getAction() == PlayerAction.START_DIGGING && !packet.isSuccessful()) {
            LevelEventPacket stopBreak = new LevelEventPacket();
            stopBreak.setType(LevelEventType.BLOCK_STOP_BREAK);
            stopBreak.setPosition(Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ()));
            stopBreak.setData(0);
            session.setBreakingBlock(BlockStateValues.JAVA_AIR_ID);
            session.sendUpstreamPacket(stopBreak);
        }
    }


    public void translate(ServerSetSubtitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.SUBTITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }


    public void translate(ServerSetTitleTextPacket packet, GeyserSession session) {
        String text;
        if (packet.getText() == null) { //TODO 1.17 can this happen?
            text = " ";
        } else {
            text = MessageTranslator.convertMessage(packet.getText(), session.getLocale());
        }

        SetTitlePacket titlePacket = new SetTitlePacket();
        titlePacket.setType(SetTitlePacket.Type.TITLE);
        titlePacket.setText(text);
        titlePacket.setXuid("");
        titlePacket.setPlatformOnlineId("");
        session.sendUpstreamPacket(titlePacket);
    }


    public void translate(ServerOpenHorseWindowPacket packet, GeyserSession session) {
        Entity entity = session.getEntityCache().getEntityByJavaId(packet.getEntityId());
        if (entity == null) {
            return;
        }

        UpdateEquipPacket updateEquipPacket = new UpdateEquipPacket();
        updateEquipPacket.setWindowId((short) packet.getWindowId());
        updateEquipPacket.setWindowType((short) ContainerType.HORSE.getId());
        updateEquipPacket.setUniqueEntityId(entity.getGeyserId());

        NbtMapBuilder builder = NbtMap.builder();
        List<NbtMap> slots = new ArrayList<>();

        InventoryTranslator inventoryTranslator;
        if (entity instanceof LlamaEntity) {
            inventoryTranslator = new LlamaInventoryTranslator(packet.getNumberOfSlots());
            slots.add(CARPET_SLOT);
        } else if (entity instanceof ChestedHorseEntity) {
            inventoryTranslator = new DonkeyInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
        } else {
            inventoryTranslator = new HorseInventoryTranslator(packet.getNumberOfSlots());
            slots.add(SADDLE_SLOT);
            slots.add(ARMOR_SLOT);
        }

        // Build the NbtMap that sets the icons for Bedrock (e.g. sets the saddle outline on the saddle slot)
        builder.putList("slots", NbtType.COMPOUND, slots);

        updateEquipPacket.setTag(builder.build());
        session.sendUpstreamPacket(updateEquipPacket);

        session.setInventoryTranslator(inventoryTranslator);
        InventoryUtils.openInventory(session, new Container(entity.getMetadata().getString(EntityData.NAMETAG), packet.getWindowId(), packet.getNumberOfSlots(), null, session.getPlayerInventory()));
    }


    private static boolean validateChainData(JsonNode data) throws Exception {
        ECPublicKey lastKey = null;
        boolean validChain = false;
        for (JsonNode node : data) {
            JWSObject jwt = JWSObject.parse(node.asText());

            if (!validChain) {
                validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
            }

            if (lastKey != null) {
                if (!EncryptionUtils.verifyJwt(jwt, lastKey)) return false;
            }

            JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());
            JsonNode ipkNode = payloadNode.get("identityPublicKey");
            Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
            lastKey = EncryptionUtils.generateKey(ipkNode.asText());
        }
        return validChain;
    }


        setImmediate(() => {
            if (!this.pendingPublishRequestCount) {
                return;
            }
            const starving_subscription = this._find_starving_subscription();
            if (starving_subscription) {
                doDebug && debugLog(chalk.bgWhite.red("feeding most late subscription subscriptionId  = "), starving_subscription.id);
                starving_subscription.process_subscription();
            }
        });


    public boolean isAvailable() {
        try {
            GeoTools.getInitialContext();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public DataSource createNewDataSource(Map<String, ?> params) throws IOException {
        String refName = (String) JNDI_REFNAME.lookUp(params);
        try {
            return (DataSource) GeoTools.getInitialContext().lookup(refName);
        } catch (Exception e) {
            throw new DataSourceException("Could not find the specified data source in JNDI", e);
        }
    }


    protected DataSource createDataSource() throws SQLException {
        InitialContext context = null;
        DataSource source = null;
        try {
            context = GeoTools.getInitialContext();
            source = (DataSource) context.lookup(datasourceName);
        } catch (IllegalArgumentException | NoInitialContextException exception) {
            // Fall back on 'return null' below.
        } catch (NamingException exception) {
            registerInto = context;
            // Fall back on 'return null' below.
        }
        return source;
    }


    public void validate() {
        final String filter = format(ldapConfiguration.getUserSearchFilter(), "test");
        ldapConnectionTemplate.searchFirst(ldapConfiguration.getSearchBases().get(0), filter, SearchScope.SUBTREE, entry -> entry);
    }


    public static UnsafeAccess getInstance() {
        SecurityCheck.getInstance();
        return INSTANCE;
    }


static int intel_pmu_handle_irq(struct pt_regs *regs)
{
	struct perf_sample_data data;
	struct cpu_hw_events *cpuc;
	int bit, loops;
	u64 status;
	int handled;

	perf_sample_data_init(&data, 0);

	cpuc = &__get_cpu_var(cpu_hw_events);

	/*
	 * Some chipsets need to unmask the LVTPC in a particular spot
	 * inside the nmi handler.  As a result, the unmasking was pushed
	 * into all the nmi handlers.
	 *
	 * This handler doesn't seem to have any issues with the unmasking
	 * so it was left at the top.
	 */
	apic_write(APIC_LVTPC, APIC_DM_NMI);

	intel_pmu_disable_all();
	handled = intel_pmu_drain_bts_buffer();
	status = intel_pmu_get_status();
	if (!status) {
		intel_pmu_enable_all(0);
		return handled;
	}

	loops = 0;
again:
	intel_pmu_ack_status(status);
	if (++loops > 100) {
		WARN_ONCE(1, "perfevents: irq loop stuck!\n");
		perf_event_print_debug();
		intel_pmu_reset();
		goto done;
	}

	inc_irq_stat(apic_perf_irqs);

	intel_pmu_lbr_read();

	/*
	 * PEBS overflow sets bit 62 in the global status register
	 */
	if (__test_and_clear_bit(62, (unsigned long *)&status)) {
		handled++;
		x86_pmu.drain_pebs(regs);
	}

	for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
		struct perf_event *event = cpuc->events[bit];

		handled++;

		if (!test_bit(bit, cpuc->active_mask))
			continue;

		if (!intel_pmu_save_and_restart(event))
			continue;

		data.period = event->hw.last_period;

		if (perf_event_overflow(event, 1, &data, regs))
			x86_pmu_stop(event, 0);
	}

	/*
	 * Repeat if there is more work to be done:
	 */
	status = intel_pmu_get_status();
	if (status)
		goto again;

done:
	intel_pmu_enable_all(0);
	return handled;
}


mptctl_fw_download(unsigned long arg)
{
	struct mpt_fw_xfer __user *ufwdl = (void __user *) arg;
	struct mpt_fw_xfer	 kfwdl;

	if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
		printk(KERN_ERR MYNAM "%s@%d::_ioctl_fwdl - "
				"Unable to copy mpt_fw_xfer struct @ %p\n",
				__FILE__, __LINE__, ufwdl);
		return -EFAULT;
	}

	return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
}


compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,
			unsigned long arg)
{
	struct mpt_fw_xfer32 kfw32;
	struct mpt_fw_xfer kfw;
	MPT_ADAPTER *iocp = NULL;
	int iocnum, iocnumX;
	int nonblock = (filp->f_flags & O_NONBLOCK);
	int ret;

	if (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))
		return -EFAULT;

	/* Verify intended MPT adapter */
	iocnumX = kfw32.iocnum & 0xFF;
	if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
	    (iocp == NULL)) {
		printk(KERN_DEBUG MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
			__LINE__, iocnumX);
		return -ENODEV;
	}

	if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
		return ret;

	dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mptfwxfer_ioctl() called\n",
	    iocp->name));
	kfw.iocnum = iocnum;
	kfw.fwlen = kfw32.fwlen;
	kfw.bufp = compat_ptr(kfw32.bufp);

	ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);

	mutex_unlock(&iocp->ioctl_cmds.mutex);

	return ret;
}


inline typename V::VectorType FBUnserializer<V>::unserializeList() {
  p_ += CODE_SIZE;

  // the list size is written so we can reserve it in the vector
  // in future. Skip past it for now.
  unserializeInt64();

  typename V::VectorType ret = V::createVector();

  size_t code = nextCode();
  while (code != FB_SERIALIZE_STOP) {
    V::vectorAppend(ret, unserializeThing());
    code = nextCode();
  }
  p_ += CODE_SIZE;
  return ret;
}


static Variant HHVM_FUNCTION(simplexml_import_dom,
  const Object& node,
  const String& class_name /* = "SimpleXMLElement" */) {
  auto domnode = Native::data<DOMNode>(node);
  xmlNodePtr nodep = domnode->nodep();

  if (nodep) {
    if (nodep->doc == nullptr) {
      raise_warning("Imported Node must have associated Document");
      return init_null();
    }
    if (nodep->type == XML_DOCUMENT_NODE ||
        nodep->type == XML_HTML_DOCUMENT_NODE) {
      nodep = xmlDocGetRootElement((xmlDocPtr) nodep);
    }
  }

  if (nodep && nodep->type == XML_ELEMENT_NODE) {
    auto cls = class_from_name(class_name, "simplexml_import_dom");
    if (!cls) {
      return init_null();
    }
    Object obj = create_object(cls->nameStr(), Array(), false);
    auto sxe = Native::data<SimpleXMLElement>(obj.get());
    sxe->node = libxml_register_node(nodep);
    return obj;
  } else {
    raise_warning("Invalid Nodetype to import");
    return init_null();
  }
  return false;
}


bool DNP3_Base::ParseAppLayer(Endpoint* endp)
	{
	bool orig = (endp == &orig_state);
	binpac::DNP3::DNP3_Flow* flow = orig ? interp->upflow() : interp->downflow();

	u_char* data = endp->buffer + PSEUDO_TRANSPORT_INDEX; // The transport layer byte counts as app-layer it seems.
	int len = endp->pkt_length - 5;

	// DNP3 Packet :  DNP3 Pseudo Link Layer | DNP3 Pseudo Transport Layer | DNP3 Pseudo Application Layer
	// DNP3 Serial Transport Layer data is always 1 byte.
	// Get FIN FIR seq field in transport header.
	// FIR indicate whether the following DNP3 Serial Application Layer is first chunk of bytes or not.
	// FIN indicate whether the following DNP3 Serial Application Layer is last chunk of bytes or not.

	int is_first = (endp->tpflags & 0x40) >> 6; // Initial chunk of data in this packet.
	int is_last = (endp->tpflags & 0x80) >> 7; // Last chunk of data in this packet.

	int transport = PSEUDO_TRANSPORT_LEN;

	int i = 0;
	while ( len > 0 )
		{
		int n = min(len, 16);

		// Make sure chunk has a correct checksum.
		if ( ! CheckCRC(n, data, data + n, "app_chunk") )
			return false;

		// Pass on to BinPAC.
		assert(data + n < endp->buffer + endp->buffer_len);
		flow->flow_buffer()->BufferData(data + transport, data + n);
		transport = 0;

		data += n + 2;
		len -= n;
		}

	if ( is_first )
		endp->encountered_first_chunk = true;

	if ( ! is_first && ! endp->encountered_first_chunk )
		{
		// We lost the first chunk.
		analyzer->Weird("dnp3_first_application_layer_chunk_missing");
		return false;
		}

	if ( is_last )
		{
		flow->flow_buffer()->FinishBuffer();
		flow->FlowEOF();
		ClearEndpointState(orig);
		}

	return true;
	}


jas_seq2d_t *jas_seq2d_copy(jas_seq2d_t *x)
{
	jas_matrix_t *y;
	int i;
	int j;
	y = jas_seq2d_create(jas_seq2d_xstart(x), jas_seq2d_ystart(x),
	  jas_seq2d_xend(x), jas_seq2d_yend(x));
	assert(y);
	for (i = 0; i < x->numrows_; ++i) {
		for (j = 0; j < x->numcols_; ++j) {
			*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
		}
	}
	return y;
}


int jas_matrix_resize(jas_matrix_t *matrix, int numrows, int numcols)
{
	int size;
	int i;

	size = numrows * numcols;
	if (size > matrix->datasize_ || numrows > matrix->maxrows_) {
		return -1;
	}

	matrix->numrows_ = numrows;
	matrix->numcols_ = numcols;

	for (i = 0; i < numrows; ++i) {
		matrix->rows_[i] = &matrix->data_[numcols * i];
	}

	return 0;
}


void CSecurityTLS::shutdown(bool needbye)
{
  if (session && needbye)
    if (gnutls_bye(session, GNUTLS_SHUT_RDWR) != GNUTLS_E_SUCCESS)
      vlog.error("gnutls_bye failed");

  if (anon_cred) {
    gnutls_anon_free_client_credentials(anon_cred);
    anon_cred = 0;
  }

  if (cert_cred) {
    gnutls_certificate_free_credentials(cert_cred);
    cert_cred = 0;
  }

  if (session) {
    gnutls_deinit(session);
    session = 0;

    gnutls_global_deinit();
  }
}


void SSecurityTLS::initGlobal()
{
  static bool globalInitDone = false;

  if (!globalInitDone) {
    if (gnutls_global_init() != GNUTLS_E_SUCCESS)
      throw AuthFailureException("gnutls_global_init failed");
    globalInitDone = true;
  }
}


void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix)
{
  int stride;
  U8 *buf;
  int w, h, b;

  w = r.width();
  h = r.height();
  b = format.bpp/8;

  if (h == 0)
    return;

  buf = getBufferRW(r, &stride);

  if (b == 1) {
    while (h--) {
      memset(buf, *(const U8*)pix, w);
      buf += stride * b;
    }
  } else {
    U8 *start;
    int w1;

    start = buf;

    w1 = w;
    while (w1--) {
      memcpy(buf, pix, b);
      buf += b;
    }
    buf += (stride - w) * b;
    h--;

    while (h--) {
      memcpy(buf, start, w * b);
      buf += stride * b;
    }
  }

  commitBufferRW(r);
}


char *Hub::inflate(char *data, size_t &length) {
    dynamicInflationBuffer.clear();

    inflationStream.next_in = (Bytef *) data;
    inflationStream.avail_in = length;

    int err;
    do {
        inflationStream.next_out = (Bytef *) inflationBuffer;
        inflationStream.avail_out = LARGE_BUFFER_SIZE;
        err = ::inflate(&inflationStream, Z_FINISH);
        if (!inflationStream.avail_in) {
            break;
        }
        dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);
    } while (err == Z_BUF_ERROR);

    inflateReset(&inflationStream);

    if (err != Z_BUF_ERROR && err != Z_OK) {
        length = 0;
        return nullptr;
    }

    if (dynamicInflationBuffer.length()) {
        dynamicInflationBuffer.append(inflationBuffer, LARGE_BUFFER_SIZE - inflationStream.avail_out);

        length = dynamicInflationBuffer.length();
        return (char *) dynamicInflationBuffer.data();
    }

    length = LARGE_BUFFER_SIZE - inflationStream.avail_out;
    return inflationBuffer;
}


R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {
	RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
	if (!se) {
		return NULL;
	}
	se->tag = type;
	if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
		se->info.obj_val_cp_idx = (ut16) value;
	} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
		/*if (bin->offset_sz == 4) {
		se->info.uninit_offset = value;
		} else {
		se->info.uninit_offset = (ut16) value;
		}*/
		se->info.uninit_offset = (ut16) value;
	}
	return se;
}


static const char* ConvertOneFloat(PyObject* v, T* out) {
  if (PyErr_Occurred()) {
    return nullptr;
  }
  if (TF_PREDICT_TRUE(PyFloat_Check(v))) {
    const double as_double = PyFloat_AS_DOUBLE(v);
    *out = static_cast<T>(as_double);
    // Check for overflow
    if (TF_PREDICT_FALSE(sizeof(T) < sizeof(double) && std::isinf(*out) &&
                         std::isfinite(as_double))) {
      return ErrorOutOfRangeDouble;
    }
    return nullptr;
  }
#if PY_MAJOR_VERSION < 3
  if (PyInt_Check(v)) {
    *out = PyInt_AS_LONG(v);
    return nullptr;
  }
#endif
  if (PyLong_Check(v)) {
    *out = PyLong_AsDouble(v);
    if (PyErr_Occurred()) return ErrorOutOfRangeDouble;
    return nullptr;
  }
  if (PyIsInstance(v, &PyFloatingArrType_Type)) {  // NumPy float types
    Safe_PyObjectPtr as_float = make_safe(PyNumber_Float(v));
    if (PyErr_Occurred()) {
      return nullptr;
    }
    return ConvertOneFloat<T>(as_float.get(), out);
  }
  if (PyIsInstance(v, &PyIntegerArrType_Type)) {  // NumPy integers
#if PY_MAJOR_VERSION < 3
    Safe_PyObjectPtr as_int = make_safe(PyNumber_Int(v));
#else
    Safe_PyObjectPtr as_int = make_safe(PyNumber_Long(v));
#endif
    if (PyErr_Occurred()) {
      return nullptr;
    }
    return ConvertOneFloat<T>(as_int.get(), out);
  }
  return ErrorMixedTypes;
}


  void readStructEnd() {
    lastFieldId_ = nestedStructFieldIds_.back();
    nestedStructFieldIds_.pop_back();
  }


uint64_t HeaderMapImpl::byteSize() const {
  uint64_t byte_size = 0;
  for (const HeaderEntryImpl& header : headers_) {
    byte_size += header.key().size();
    byte_size += header.value().size();
  }

  return byte_size;
}


void HeaderMapImpl::removePrefix(const LowerCaseString& prefix) {
  headers_.remove_if([&](const HeaderEntryImpl& entry) {
    bool to_remove = absl::StartsWith(entry.key().getStringView(), prefix.get());
    if (to_remove) {
      // If this header should be removed, make sure any references in the
      // static lookup table are cleared as well.
      EntryCb cb = ConstSingleton<StaticLookupTable>::get().find(entry.key().getStringView());
      if (cb) {
        StaticLookupResponse ref_lookup_response = cb(*this);
        if (ref_lookup_response.entry_) {
          *ref_lookup_response.entry_ = nullptr;
        }
      }
    }
    return to_remove;
  });
}


void ConnPoolImplBase::checkForIdleAndCloseIdleConnsIfDraining() {
  if (is_draining_for_deletion_) {
    closeIdleConnectionsForDrainingPool();
  }

  if (isIdleImpl()) {
    ENVOY_LOG(debug, "invoking idle callbacks - is_draining_for_deletion_={}",
              is_draining_for_deletion_);
    for (const Instance::IdleCb& cb : idle_callbacks_) {
      cb();
    }
  }
}


  CdsIntegrationTest()
      : HttpIntegrationTest(Http::CodecType::HTTP2, ipVersion(),
                            ConfigHelper::discoveredClustersBootstrap(
                                sotwOrDelta() == Grpc::SotwOrDelta::Sotw ||
                                        sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw
                                    ? "GRPC"
                                    : "DELTA_GRPC")) {
    if (sotwOrDelta() == Grpc::SotwOrDelta::UnifiedSotw ||
        sotwOrDelta() == Grpc::SotwOrDelta::UnifiedDelta) {
      config_helper_.addRuntimeOverride("envoy.reloadable_features.unified_mux", "true");
    }
    use_lds_ = false;
    sotw_or_delta_ = sotwOrDelta();
  }


TEST_F(RouterTest, RetryUpstreamResetResponseStarted) {
  NiceMock<Http::MockRequestEncoder> encoder1;
  Http::ResponseDecoder* response_decoder = nullptr;
  expectNewStreamWithImmediateEncoder(encoder1, &response_decoder, Http::Protocol::Http10);

  expectResponseTimerCreate();

  Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}};
  HttpTestUtility::addDefaultHeaders(headers);
  router_.decodeHeaders(headers, true);
  EXPECT_EQ(1U,
            callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());

  // Since the response is already started we don't retry.
  EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _, _)).WillOnce(Return(RetryStatus::No));
  EXPECT_CALL(callbacks_, encodeHeaders_(_, false));
  Http::ResponseHeaderMapPtr response_headers(
      new Http::TestResponseHeaderMapImpl{{":status", "200"}});
  EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,
              putHttpResponseCode(200));
  response_decoder->decodeHeaders(std::move(response_headers), false);
  EXPECT_CALL(cm_.thread_local_cluster_.conn_pool_.host_->outlier_detector_,
              putResult(Upstream::Outlier::Result::LocalOriginConnectFailed, _));
  // Normally, sendLocalReply will actually send the reply, but in this case the
  // HCM will detect the headers have already been sent and not route through
  // the encoder again.
  EXPECT_CALL(callbacks_, sendLocalReply(_, _, _, _, _)).WillOnce(testing::InvokeWithoutArgs([] {
  }));
  encoder1.stream_.resetStream(Http::StreamResetReason::RemoteReset);
  // For normal HTTP, once we have a 200 we consider this a success, even if a
  // later reset occurs.
  EXPECT_TRUE(verifyHostUpstreamStats(1, 0));
  EXPECT_EQ(1U,
            callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value());
}


void *UntrustedCacheMalloc::GetBuffer() {
  void **buffers = nullptr;
  void *buffer;
  bool is_pool_empty;

  {
    LockGuard spin_lock(&lock_);
    is_pool_empty = buffer_pool_.empty();
    if (is_pool_empty) {
      buffers =
          primitives::AllocateUntrustedBuffers(kPoolIncrement, kPoolEntrySize);
      for (int i = 0; i < kPoolIncrement; i++) {
        if (!buffers[i] ||
            !TrustedPrimitives::IsOutsideEnclave(buffers[i], kPoolEntrySize)) {
          abort();
        }
        buffer_pool_.push(buffers[i]);
      }
    }
    buffer = buffer_pool_.top();
    buffer_pool_.pop();
    busy_buffers_.insert(buffer);
  }

  if (is_pool_empty) {
    // Free memory held by the array of buffer pointers returned by
    // AllocateUntrustedBuffers.
    Free(buffers);
  }
  return buffer;
}


  RectangleRequest(const struct RectangleRequest &req)
    : Explicit()
  {
    // Not nice, but this is really faster and simpler
    memcpy(this,&req,sizeof(struct RectangleRequest));
    // Not linked in any way if this is new.
    rr_pNext = NULL;
  }


    def forwarded_for
      @env[FORWARDED_FOR]
    end


  def check_action_permission!(skip_source = nil)
    super(skip_source)
    # only perform the following check, if we are called from
    # BsRequest.permission_check_change_state! (that is, if
    # skip_source is set to true). Always executing this check
    # would be a regression, because this code is also executed
    # if a new request is created (which could fail if User.current
    # cannot modify the source_package).
    return unless skip_source
    target_project = Project.get_by_name(self.target_project)
    return unless target_project && target_project.is_a?(Project)
    target_package = target_project.packages.find_by_name(self.target_package)
    initialize_devel_package = target_project.find_attribute('OBS', 'InitializeDevelPackage')
    return if target_package || !initialize_devel_package
    source_package = Package.get_by_project_and_name(source_project, self.source_package)
    return if !source_package || User.current.can_modify?(source_package)
    msg = 'No permission to initialize the source package as a devel package'
    raise PostRequestNoPermission, msg
  end


      def munge_name(name)
        # LAK:NOTE http://snurl.com/21zf8  [groups_google_com]
        # Change to name.downcase.split(".",-1).reverse for FQDN support
        name.downcase.split(".").reverse
      end


  def select_terminus(request)
    # We rely on the request's parsing of the URI.

    # Short-circuit to :file if it's a fully-qualified path or specifies a 'file' protocol.
    return PROTOCOL_MAP["file"] if Puppet::Util.absolute_path?(request.key)
    return PROTOCOL_MAP["file"] if request.protocol == "file"

    # We're heading over the wire the protocol is 'puppet' and we've got a server name or we're not named 'apply' or 'puppet'
    if request.protocol == "puppet" and (request.server or !["puppet","apply"].include?(Puppet.settings[:name]))
      return PROTOCOL_MAP["puppet"]
    end

    if request.protocol and PROTOCOL_MAP[request.protocol].nil?
      raise(ArgumentError, "URI protocol '#{request.protocol}' is not currently supported for file serving")
    end

    # If we're still here, we're using the file_server or modules.
    :file_server
  end


  it "should should include the IndirectionHooks module in its indirection" do
    Puppet::FileServing::Metadata.indirection.singleton_class.included_modules.should include(Puppet::FileServing::IndirectionHooks)
  end


  def setup_user(operation, type = "", search = nil, user = :one)
    @one = users(user)
    as_admin do
      permission = Permission.find_by_name("#{operation}_#{type}") || FactoryGirl.create(:permission, :name => "#{operation}_#{type}")
      filter = FactoryGirl.build(:filter, :search => search)
      filter.permissions = [ permission ]
      role = Role.where(:name => "#{operation}_#{type}").first_or_create
      role.filters = [ filter ]
      role.save!
      filter.role = role
      filter.save!
      @one.roles << role
      yield(@one) if block_given?
      @one.save!
    end
    User.current = @one
  end


  def test_clone
    get :clone, {:id => Hostgroup.first}, set_session_user
    assert_template 'new'
  end


        def initialize
          # Generate and cache 3 bytes of identifying information from the current
          # machine.
          @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("C3")

          @mutex = Mutex.new
          @last_timestamp = nil
          @counter = 0
        end


        def next
          now = Time.new.to_i

          counter = @mutex.synchronize do
            last_timestamp, @last_timestamp = @last_timestamp, now

            if last_timestamp == now
              @counter += 1
            else
              @counter = 0
            end
          end

          generate(now, counter)
        end


        def __bson_load__(io)
          new io.read(12).unpack('C*')
        end


      def initialize(data = nil, time = nil)
        if data
          @data = data
        elsif time
          @data = @@generator.generate(time.to_i)
        else
          @data = @@generator.next
        end
      end


    def sync_server(server)
      [].tap do |hosts|
        socket = server.socket

        if socket.connect
          info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1)

          if info["ismaster"]
            server.primary = true
          end

          if info["secondary"]
            server.secondary = true
          end

          if info["primary"]
            hosts.push info["primary"]
          end

          if info["hosts"]
            hosts.concat info["hosts"]
          end

          if info["passives"]
            hosts.concat info["passives"]
          end

          merge(server)

        end
      end.uniq
    end


    def reconnect
      @servers = servers.map { |server| Server.new(server.address) }
    end


    def initialize(session, query_operation)
      @session = session
      @query_op = query_operation.dup

      @get_more_op = Protocol::GetMore.new(
        @query_op.database,
        @query_op.collection,
        0,
        @query_op.limit
      )

      @kill_cursor_op = Protocol::KillCursors.new([0])
    end


    def limited?
      @query_op.limit > 0
    end


    def logout
      session.cluster.logout(name)
    end


      def initialize(string)
        super("'#{string}' is not a valid object id.")
      end


    def remove_all
      delete = Protocol::Delete.new(
        operation.database,
        operation.collection,
        operation.selector
      )

      session.with(consistency: :strong) do |session|
        session.execute delete
      end
    end


    def update(change, flags = nil)
      update = Protocol::Update.new(
        operation.database,
        operation.collection,
        operation.selector,
        change,
        flags: flags
      )

      session.with(consistency: :strong) do |session|
        session.execute update
      end
    end


      it "returns the same hash" do
        Moped::BSON::ObjectId.new(bytes).hash.should eq Moped::BSON::ObjectId.new(bytes).hash
      end


      it "adds the node to the master set" do
        cluster.sync_server server
        cluster.primaries.should include server
      end


    it "adds the credentials to the auth cache" do
      cluster.login("admin", "username", "password")
      cluster.auth.should eq("admin" => ["username", "password"])
    end


    it "stores the list of seeds" do
      cluster.seeds.should eq ["127.0.0.1:27017", "127.0.0.1:27018"]
    end


    it "has an empty list of primaries" do
      cluster.primaries.should be_empty
    end


        it "applies the cached authentication" do
          cluster.stub(:sync) { cluster.servers << server }
          socket.should_receive(:apply_auth).with(cluster.auth)
          cluster.socket_for(:write)
        end


        it "returns all other known hosts" do
          cluster.sync_server(server).should =~ ["localhost:61085", "localhost:61086", "localhost:61084"]
        end


    it "stores the database" do
      collection.database.should eq database
    end


    it "removes the first matching document" do
      session.should_receive(:with, :consistency => :strong).
        and_yield(session)

      session.should_receive(:execute).with do |delete|
        delete.flags.should eq [:remove_first]
        delete.selector.should eq query.operation.selector
      end

      query.remove
    end


    it "executes a distinct command" do
      database.should_receive(:command).with(
        distinct: collection.name,
        key: "name",
        query: selector
      ).and_return("values" => [ "durran", "bernerd" ])
      query.distinct(:name)
    end


    it "sets the query operation's fields" do
      query.select(a: 1)
      query.operation.fields.should eq(a: 1)
    end


    it "yields all documents in the cursor" do
      cursor = Moped::Cursor.allocate
      cursor.stub(:to_enum).and_return([1, 2].to_enum)

      Moped::Cursor.stub(new: cursor)

      query.to_a.should eq [1, 2]
    end


    it "returns the document" do
      session.simple_query(query).should eq(a: 1)
    end


    it "stores the cluster" do
      session.cluster.should be_a(Moped::Cluster)
    end


        it "doesn't try to set flags" do
          session.stub(socket_for: socket)
          expect { session.query(query) }.not_to raise_exception
        end


      it "returns the new session" do
        session.stub(with: new_session)
        session.new(new_options).should eql new_session
      end


      it "queries a slave node" do
        session.should_receive(:socket_for).with(:read).
          and_return(socket)
        session.query(query)
      end


    it "sets the :database option" do
      session.use :admin
      session.options[:database].should eq(:admin)
    end


    it 'avoids xss attacks' do
      h = last_response.headers['X-MiniProfiler-Ids']
      id = ::JSON.parse(h)[0]
      get "/mini-profiler-resources/results?id=%22%3E%3Cqss%3E"
      last_response.should_not be_ok
      last_response.body.should_not =~ /<qss>/
      last_response.body.should =~ /<qss>/
    end


it 'should not choke on valueless attributes' do
      @s.fragment('foo foo bar')
        .must_equal 'foo foo bar'
    end


      it "generates the correct messages for a secure topic" do
        Jobs.run_immediately!
        UserActionManager.enable

        admin = Fabricate(:admin)

        cat = Fabricate(:category)
        cat.set_permissions(admins: :full)
        cat.save

        created_post = nil

        messages = MessageBus.track_publish do
          created_post = PostCreator.new(admin, basic_topic_params.merge(category: cat.id)).create
          _reply = PostCreator.new(admin, raw: "this is my test reply 123 testing", topic_id: created_post.topic_id).create
        end

        messages.filter! { |m| m.channel != "/distributed_hash" }

        channels = messages.map { |m| m.channel }.sort

        # 2 for topic, one to notify of new topic another for tracking state
        expect(channels).to eq(
          [
            "/new",
            "/u/#{admin.username}",
            "/u/#{admin.username}",
            "/unread/#{admin.id}",
            "/unread/#{admin.id}",
            "/latest",
            "/latest",
            "/topic/#{created_post.topic_id}",
            "/topic/#{created_post.topic_id}",
            "/user",
            "/user",
            "/user"
          ].sort
        )

        admin_ids = [Group[:admins].id]
        expect(messages.any? { |m| m.group_ids != admin_ids && m.user_ids != [admin.id] }).to eq(false)
      end


    it 'returns a list of all private messages that has been archived' do
      UserArchivedMessage.archive!(user_2.id, private_message)
      GroupArchivedMessage.archive!(user_2.id, group_message)

      topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics

      expect(topics).to contain_exactly(private_message, group_message)
    end


    it "should redeem the invite if invited by non staff and approve if staff not required to approve" do
      inviter = invite.invited_by
      user = invite_redeemer.redeem

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.invited_by).to eq(inviter)
      expect(inviter.notifications.count).to eq(1)
      expect(user.approved).to eq(true)
    end


    it "should redeem the invite if invited by non staff and approve if email in auto_approve_email_domains setting" do
      SiteSetting.must_approve_users = true
      SiteSetting.auto_approve_email_domains = "example.com"
      user = invite_redeemer.redeem

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.approved).to eq(true)
    end


  def email_login
    raise Discourse::NotFound if !SiteSetting.enable_local_logins_via_email
    second_factor_token = params[:second_factor_token]
    second_factor_method = params[:second_factor_method].to_i
    token = params[:token]
    valid_token = !!EmailToken.valid_token_format?(token)
    user = EmailToken.confirmable(token)&.user

    if valid_token && user&.totp_enabled?
      if !second_factor_token.present?
        @second_factor_required = true
        @backup_codes_enabled = true if user&.backup_codes_enabled?
        return render layout: 'no_ember'
      elsif !user.authenticate_second_factor(second_factor_token, second_factor_method)
        RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 3, 1.minute).performed!
        @error = I18n.t('login.invalid_second_factor_code')
        return render layout: 'no_ember'
      end
    end

    if user = EmailToken.confirm(token)
      if login_not_approved_for?(user)
        @error = login_not_approved[:error]
      elsif payload = login_error_check(user)
        @error = payload[:error]
      else
        log_on_user(user)
        return redirect_to path("/")
      end
    else
      @error = I18n.t('email_login.invalid_token')
    end

    render layout: 'no_ember'
  end


        it 'should authenticate user and delete token' do
          user = Fabricate(:user)

          get "/session/current.json"
          expect(response.status).to eq(404)

          token = SecureRandom.hex
          $redis.setex "otp_#{token}", 10.minutes, user.username

          get "/session/otp/#{token}"

          expect(response.status).to eq(302)
          expect(response).to redirect_to("/")
          expect($redis.get("otp_#{token}")).to eq(nil)

          get "/session/current.json"
          expect(response.status).to eq(200)
        end


            it 'logs in correctly' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(response).to redirect_to("/")
            end


func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error {
	switch m.Device {
	case "cgroup":
		// No mount point(s) need to be created:
		//
		// * for v1, mount points are saved by CRIU because
		//   /sys/fs/cgroup is a tmpfs mount
		//
		// * for v2, /sys/fs/cgroup is a real mount, but
		//   the mountpoint appears as soon as /sys is mounted
		return nil
	case "bind":
		// The prepareBindMount() function checks if source
		// exists. So it cannot be used for other filesystem types.
		if err := prepareBindMount(m, c.config.Rootfs); err != nil {
			return err
		}
	default:
		// for all other filesystems just create the mountpoints
		dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination)
		if err != nil {
			return err
		}
		if err := checkProcMount(c.config.Rootfs, dest, ""); err != nil {
			return err
		}
		m.Destination = dest
		if err := os.MkdirAll(dest, 0755); err != nil {
			return err
		}
	}
	return nil
}


func mountCgroupV1(m *configs.Mount, c *mountConfig) error {
	binds, err := getCgroupMounts(m)
	if err != nil {
		return err
	}
	var merged []string
	for _, b := range binds {
		ss := filepath.Base(b.Destination)
		if strings.Contains(ss, ",") {
			merged = append(merged, ss)
		}
	}
	tmpfs := &configs.Mount{
		Source:           "tmpfs",
		Device:           "tmpfs",
		Destination:      m.Destination,
		Flags:            defaultMountFlags,
		Data:             "mode=755",
		PropagationFlags: m.PropagationFlags,
	}
	if err := mountToRootfs(tmpfs, c); err != nil {
		return err
	}
	for _, b := range binds {
		if c.cgroupns {
			subsystemPath := filepath.Join(c.root, b.Destination)
			if err := os.MkdirAll(subsystemPath, 0755); err != nil {
				return err
			}
			flags := defaultMountFlags
			if m.Flags&unix.MS_RDONLY != 0 {
				flags = flags | unix.MS_RDONLY
			}
			cgroupmount := &configs.Mount{
				Source:      "cgroup",
				Device:      "cgroup", // this is actually fstype
				Destination: subsystemPath,
				Flags:       flags,
				Data:        filepath.Base(subsystemPath),
			}
			if err := mountNewCgroup(cgroupmount); err != nil {
				return err
			}
		} else {
			if err := mountToRootfs(b, c); err != nil {
				return err
			}
		}
	}
	for _, mc := range merged {
		for _, ss := range strings.Split(mc, ",") {
			// symlink(2) is very dumb, it will just shove the path into
			// the link and doesn't do any checks or relative path
			// conversion. Also, don't error out if the cgroup already exists.
			if err := os.Symlink(mc, filepath.Join(c.root, m.Destination, ss)); err != nil && !os.IsExist(err) {
				return err
			}
		}
	}
	return nil
}


func (f *ScmpFilter) addRuleGeneric(call ScmpSyscall, action ScmpAction, exact bool, conds []ScmpCondition) error {
	f.lock.Lock()
	defer f.lock.Unlock()

	if !f.valid {
		return errBadFilter
	}

	if len(conds) == 0 {
		if err := f.addRuleWrapper(call, action, exact, nil); err != nil {
			return err
		}
	} else {
		// We don't support conditional filtering in library version v2.1
		if !checkVersionAbove(2, 2, 1) {
			return VersionError{
				message: "conditional filtering is not supported",
				minimum: "2.2.1",
			}
		}

		for _, cond := range conds {
			cmpStruct := C.make_struct_arg_cmp(C.uint(cond.Argument), cond.Op.toNative(), C.uint64_t(cond.Operand1), C.uint64_t(cond.Operand2))
			defer C.free(cmpStruct)

			if err := f.addRuleWrapper(call, action, exact, C.scmp_cast_t(cmpStruct)); err != nil {
				return err
			}
		}
	}

	return nil
}


func doesPolicySignatureV2Match(formValues http.Header) APIErrorCode {
	cred := globalActiveCred
	accessKey := formValues.Get(xhttp.AmzAccessKeyID)
	cred, _, s3Err := checkKeyValid(accessKey)
	if s3Err != ErrNone {
		return s3Err
	}
	policy := formValues.Get("Policy")
	signature := formValues.Get(xhttp.AmzSignatureV2)
	if !compareSignatureV2(signature, calculateSignatureV2(policy, cred.SecretKey)) {
		return ErrSignatureDoesNotMatch
	}
	return ErrNone
}


		action := args[2].(func(child argoappv1.ResourceNode, appName string))
		appName := ""
		if res, ok := data.namespacedResources[key]; ok {
			appName = res.AppName
		}
		action(argoappv1.ResourceNode{ResourceRef: argoappv1.ResourceRef{Kind: key.Kind, Group: key.Group, Namespace: key.Namespace, Name: key.Name}}, appName)
	}).Return(nil)


func NewPool(evidenceDB dbm.DB, stateDB sm.Store, blockStore BlockStore) (*Pool, error) {

	state, err := stateDB.Load()
	if err != nil {
		return nil, fmt.Errorf("cannot load state: %w", err)
	}

	pool := &Pool{
		stateDB:         stateDB,
		blockStore:      blockStore,
		state:           state,
		logger:          log.NewNopLogger(),
		evidenceStore:   evidenceDB,
		evidenceList:    clist.New(),
		consensusBuffer: make([]types.Evidence, 0),
	}

	// if pending evidence already in db, in event of prior failure, then check for expiration,
	// update the size and load it back to the evidenceList
	pool.pruningHeight, pool.pruningTime = pool.removeExpiredPendingEvidence()
	evList, _, err := pool.listEvidence(baseKeyPending, -1)
	if err != nil {
		return nil, err
	}
	atomic.StoreUint32(&pool.evidenceSize, uint32(len(evList)))
	for _, ev := range evList {
		pool.evidenceList.PushBack(ev)
	}

	return pool, nil
}


func (EmptyEvidencePool) Update(State, types.EvidenceList)              {}


func makeStreamDistributedQueryCampaignResultsHandler(svc kolide.Service, jwtKey string, logger kitlog.Logger) http.Handler {
	opt := sockjs.DefaultOptions
	opt.Websocket = true
	opt.RawWebsocket = true
	return sockjs.NewHandler("/api/v1/kolide/results", opt, func(session sockjs.Session) {
		defer session.Close(0, "none")

		conn := &websocket.Conn{Session: session}

		// Receive the auth bearer token
		token, err := conn.ReadAuthToken()
		if err != nil {
			logger.Log("err", err, "msg", "failed to read auth token")
			return
		}

		// Authenticate with the token
		vc, err := authViewer(context.Background(), jwtKey, token, svc)
		if err != nil || !vc.CanPerformActions() {
			logger.Log("err", err, "msg", "unauthorized viewer")
			conn.WriteJSONError("unauthorized")
			return
		}

		ctx := viewer.NewContext(context.Background(), *vc)

		msg, err := conn.ReadJSONMessage()
		if err != nil {
			logger.Log("err", err, "msg", "reading select_campaign JSON")
			conn.WriteJSONError("error reading select_campaign")
			return
		}
		if msg.Type != "select_campaign" {
			logger.Log("err", "unexpected msg type, expected select_campaign", "msg-type", msg.Type)
			conn.WriteJSONError("expected select_campaign")
			return
		}

		var info struct {
			CampaignID uint `json:"campaign_id"`
		}
		err = json.Unmarshal(*(msg.Data.(*json.RawMessage)), &info)
		if err != nil {
			logger.Log("err", err, "msg", "unmarshaling select_campaign data")
			conn.WriteJSONError("error unmarshaling select_campaign data")
			return
		}
		if info.CampaignID == 0 {
			logger.Log("err", "campaign ID not set")
			conn.WriteJSONError("0 is not a valid campaign ID")
			return
		}

		svc.StreamCampaignResults(ctx, conn, info.CampaignID)

	})
}


func (svc Service) TeamScheduleQuery(ctx context.Context, teamID uint, q *fleet.ScheduledQuery) (*fleet.ScheduledQuery, error) {
	if err := svc.authz.Authorize(ctx, &fleet.Pack{TeamIDs: []uint{teamID}}, fleet.ActionWrite); err != nil {
		return nil, err
	}

	gp, err := svc.ds.EnsureTeamPack(ctx, teamID)
	if err != nil {
		return nil, err
	}
	q.PackID = gp.ID

	return svc.unauthorizedScheduleQuery(ctx, q)
}


func (svc *Service) DeleteUser(ctx context.Context, id uint) error {
	if err := svc.authz.Authorize(ctx, &fleet.User{ID: id}, fleet.ActionWrite); err != nil {
		return err
	}

	return svc.ds.DeleteUser(ctx, id)
}


func InitGenesis(
	ctx sdk.Context,
	k keeper.Keeper,
	ak types.AccountKeeper,
	sk types.StakingKeeper,
	data types.GenesisState,
) {
	// Ensure inflation module account is set on genesis
	if acc := ak.GetModuleAccount(ctx, types.ModuleName); acc == nil {
		panic("the inflation module account has not been set")
	}

	// Set genesis state
	params := data.Params
	k.SetParams(ctx, params)

	period := data.Period
	k.SetPeriod(ctx, period)

	epochIdentifier := data.EpochIdentifier
	k.SetEpochIdentifier(ctx, epochIdentifier)

	epochsPerPeriod := data.EpochsPerPeriod
	k.SetEpochsPerPeriod(ctx, epochsPerPeriod)

	// Get bondedRatio
	bondedRatio := sk.BondedRatio(ctx)

	// Calculate epoch mint provision
	epochMintProvision := types.CalculateEpochMintProvision(
		params,
		period,
		epochsPerPeriod,
		bondedRatio,
	)
	k.SetEpochMintProvision(ctx, epochMintProvision)
}


func TestBuilder_BuildBootstrapStaticResources(t *testing.T) {
	t.Run("valid", func(t *testing.T) {
		b := New("localhost:1111", "localhost:2222", filemgr.NewManager(), nil)
		staticCfg, err := b.BuildBootstrapStaticResources()
		assert.NoError(t, err)
		testutil.AssertProtoJSONEqual(t, `
			{
				"clusters": [
					{
						"name": "pomerium-control-plane-grpc",
						"type": "STATIC",
						"connectTimeout": "5s",
						"http2ProtocolOptions": {},
						"loadAssignment": {
							"clusterName": "pomerium-control-plane-grpc",
							"endpoints": [{
								"lbEndpoints": [{
									"endpoint": {
										"address": {
											"socketAddress":{
												"address": "127.0.0.1",
												"portValue": 1111
											}
										}
									}
								}]
							}]
						}
					}
				]
			}
		`, staticCfg)
	})
	t.Run("bad gRPC address", func(t *testing.T) {
		b := New("xyz:zyx", "localhost:2222", filemgr.NewManager(), nil)
		_, err := b.BuildBootstrapStaticResources()
		assert.Error(t, err)
	})
}


func (mgr *MetricsManager) updateInfo(cfg *Config) {
	serviceName := telemetry.ServiceName(cfg.Options.Services)
	if serviceName == mgr.serviceName {
		return
	}

	hostname, err := os.Hostname()
	if err != nil {
		log.Error(context.TODO()).Err(err).Msg("telemetry/metrics: failed to get OS hostname")
		hostname = "__unknown__"
	}

	metrics.SetBuildInfo(serviceName, hostname, cfg.EnvoyVersion)
	mgr.serviceName = serviceName
}


func (mgr *MetricsManager) updateServer(cfg *Config) {
	if cfg.Options.MetricsAddr == mgr.addr &&
		cfg.Options.MetricsBasicAuth == mgr.basicAuth &&
		cfg.Options.InstallationID == mgr.installationID {
		return
	}

	mgr.addr = cfg.Options.MetricsAddr
	mgr.basicAuth = cfg.Options.MetricsBasicAuth
	mgr.installationID = cfg.Options.InstallationID
	mgr.handler = nil

	if mgr.addr == "" {
		log.Info(context.TODO()).Msg("metrics: http server disabled")
		return
	}

	handler, err := metrics.PrometheusHandler(EnvoyAdminURL, mgr.installationID)
	if err != nil {
		log.Error(context.TODO()).Err(err).Msg("metrics: failed to create prometheus handler")
		return
	}

	if username, password, ok := cfg.Options.GetMetricsBasicAuth(); ok {
		handler = middleware.RequireBasicAuth(username, password)(handler)
	}

	mgr.handler = handler
}


func (s *Service) handleMessage(stream StepStream, addr string, exp *certificateExpirationCheck) error {
	request, err := stream.Recv()
	if err == io.EOF {
		return err
	}
	if err != nil {
		s.Logger.Warningf("Stream read from %s failed: %v", addr, err)
		return err
	}

	exp.checkExpiration(time.Now(), extractChannel(request))

	if s.StepLogger.IsEnabledFor(zap.DebugLevel) {
		nodeName := commonNameFromContext(stream.Context())
		s.StepLogger.Debugf("Received message from %s(%s): %v", nodeName, addr, requestAsString(request))
	}

	if submitReq := request.GetSubmitRequest(); submitReq != nil {
		nodeName := commonNameFromContext(stream.Context())
		s.Logger.Debugf("Received message from %s(%s): %v", nodeName, addr, requestAsString(request))
		return s.handleSubmit(submitReq, stream, addr)
	}

	// Else, it's a consensus message.
	return s.Dispatcher.DispatchConsensus(stream.Context(), request.GetConsensusRequest())
}


    static buildGenesisOpReturn(config: configBuildGenesisOpReturn, type = 0x01) {
        let hash;
        try {
            hash = config.hash!.toString('hex')
        } catch (_) { hash = null }

        return SlpTokenType1.buildGenesisOpReturn(
            config.ticker,
            config.name,
            config.documentUri,
            hash,
            config.decimals,
            config.batonVout,
            config.initialQuantity,
            type
        )
    }


          link: new ApolloLink((operation, forward) => {
            return forward(operation).map((response) => {
              const context = operation.getContext();
              const {
                response: { headers },
              } = context;
              expect(headers.get('access-control-allow-origin')).toEqual('*');
              checked = true;
              return response;
            });
          }).concat(


			.then((promiseResult) => {
				// This promise resolver simply swallows the result of Promise.all.
				// When we decide we want to expose this level of detail
				// to other extensions then we will design that return type and implement it here.
			}),


module.exports = (yargs) => {
    yargs.command('exec <container name> [commands...]', 'Execute command in docker container', () => {}, async (argv) => {
        const containers = docker.getContainers();
        const services = Object.keys(containers);

        if (services.includes(argv.containername) || services.some((service) => service.includes(argv.containername))) {
            const container = containers[argv.containername]
                ? containers[argv.containername]
                : Object.entries(containers).find(([key]) => key.includes(argv.containername))[1];

            if (argv.commands.length === 0) {
                // if we have default connect command then use it
                if (container.connectCommand) {
                    // eslint-disable-next-line no-param-reassign
                    argv.commands = container.connectCommand;
                } else {
                    // otherwise fall back to bash (if it exists inside container)
                    argv.commands.push('bash');
                }
            }
            await executeInContainer({
                containerName: container.name,
                commands: argv.commands
            });

            return;
        }

        logger.error(`No container found "${argv.containername}"`);
    });
};


function applyInlineFootnotes(elem) {
  const footnoteRefs = elem.querySelectorAll("sup.footnote-ref");

  footnoteRefs.forEach((footnoteRef) => {
    const expandableFootnote = document.createElement("a");
    expandableFootnote.classList.add("expand-footnote");
    expandableFootnote.innerHTML = iconHTML("ellipsis-h");
    expandableFootnote.href = "";
    expandableFootnote.role = "button";
    expandableFootnote.dataset.footnoteId = footnoteRef
      .querySelector("a")
      .id.replace("footnote-ref-", "");

    footnoteRef.after(expandableFootnote);
  });

  if (footnoteRefs.length) {
    elem.classList.add("inline-footnotes");
  }
}