owning connection which is cheap or (ii) from the messaging engine which is expensive.
518861
private void setOrderingContextProxyId () throws SIConnectionUnavailableException, SIConnectionDroppedException, SIErrorException {
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setOrderingContextProxyId");

     final ConnectionProxy cp = getConnectionProxy();
     final Short orderContext = cp.getOrderContext();

     if (orderContext != null) {
       setProxyID(orderContext.shortValue());
     } else {
       create();
     }

     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setOrderingContextProxyId");
   }
501210
private ResourceBundleHolder loadMessageBundle(Method m) throws ClassNotFoundException {
        Class c = m.getDeclaringClass();
        Class<?> msg = c.getClassLoader().loadClass(c.getName().substring(0, c.getName().lastIndexOf(".")) + ".Messages");
        return ResourceBundleHolder.get(msg);
    }
342792
private boolean transfer(long total,
                             GlobusInputStream in,
                             GlobusOutputStream out)
        throws IOException {

        byte [] buffer       = new byte[bufferSize];
        int bytes            = 0;
        long totalBytes      = total;
        long transferedBytes = 0;

        if (total == -1) {
            while( (bytes = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytes);
                out.flush();

                if (listeners != null) {
                    transferedBytes += bytes;
                    fireUrlTransferProgressEvent(totalBytes,
                                                 transferedBytes);
                }
                if (isCanceled()) return false;
            }
        } else {
            while ( total != 0 ) {

                bytes = bufferSize;
                if (total < bufferSize) bytes = (int)total;

                bytes = in.read(buffer);
                out.write(buffer, 0, bytes);
                out.flush();
                total -= bytes;

                if (listeners != null) {
                    transferedBytes += bytes;
                    fireUrlTransferProgressEvent(totalBytes,
                                                 transferedBytes);
                }
                if (isCanceled()) return false;
            }
        }

        return true;
    }
1266228
def message_channel(self, message):
        
        data = "PRIVMSG %s :%s\r\n" % (self.channel, message)
        self.connection.socket.send(data.encode("utf-8"))
315751
def raw_connection_from(engine_or_conn):
    
    if hasattr(engine_or_conn, 'cursor'):
        return engine_or_conn, False
    if hasattr(engine_or_conn, 'connection'):
        return engine_or_conn.connection, False
    return engine_or_conn.raw_connection(), True
339222
public void consumeMessages(LockedMessageEnumeration messages) throws Exception
  {
    if (tc.isEntryEnabled())
      SibTr.entry(tc, "consumeMessages", new Object[] { messages });

    SIBusMessage jsMessage = null;
    
    while (messages.hasNext())
    {    
      try
      {
        jsMessage = messages.nextLocked();
      }
      catch (SIException e)
      {
        FFDCFilter.processException(
          e,
          "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
          "1:157:1.73",
          this);
          
        SibTr.exception(tc, e);
      }
  
      if (jsMessage!=null && 
          ((JsMessage) jsMessage).getJsMessageType() != MessageType.SUBSCRIPTION)
      {
        if (tc.isDebugEnabled())
          SibTr.debug(
            tc,
            "Message On incorrect Destination, expecting message "
              + "of Type "
              + MessageType.SUBSCRIPTION
              + " received "
              + ((JsMessage) jsMessage).getJsMessageType());
              
        if (tc.isEntryEnabled()) SibTr.exit(tc, "consumeMessages");
        return;
      }
  
      // Only continue if the message returned is not null
      if (jsMessage!=null)
      {    
        SubscriptionMessage subMessage = null;     
        
        try
        {
          subMessage = ((JsMessage) jsMessage).makeInboundSubscriptionMessage();
        }
        catch (IncorrectMessageTypeException e)
        {
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:193:1.73",
            this);
            
          SibTr.exception(tc, e);
        }
        
        // Invoke the limited ME comms trace again now that we have fluffed up the message
        if (TraceComponent.isAnyTracingEnabled()) {
          MECommsTrc.traceMessage(tc, 
              iProxyHandler.getMessageProcessor(), 
              subMessage.getGuaranteedSourceMessagingEngineUUID(),
              MECommsTrc.OP_SUBMSG_CONSUME, 
              null, 
              subMessage);
        }
        
        LocalTransaction transaction = null;
        
        // Switch on the Type of the Message to understand what we need to 
        // process
        try
        {
          
          // Get a transaction to operate under
          transaction = iProxyHandler.getTransactionManager().createLocalTransaction(true);
    
          switch (subMessage.getSubscriptionMessageType().toInt())
          {
            case SubscriptionMessageType.CREATE_INT :
    
              // Create a new Proxy subscription
              handleCreateProxySubscription(subMessage, (Transaction) transaction);
    
              break;
    
            case SubscriptionMessageType.DELETE_INT :
    
              // Delete a proxy subscription
              handleDeleteProxySubscription(subMessage, (Transaction) transaction);
    
              break;
    
            case SubscriptionMessageType.RESET_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, false);
    
              break;
    
            case SubscriptionMessageType.REQUEST_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, true);
    
              break;
  
            case SubscriptionMessageType.REPLY_INT :
    
              // Reset the subscription state.
              handleResetState(subMessage, (Transaction) transaction, false);
    
              break;
            default :
              // Log Message
              break;
          }
    
          // Delete the current message from the destination as we 
          // have now read it.
          messages.deleteCurrent(transaction);
        
          // Commit the transaction.
          transaction.commit();
        }      
        catch (SIException e)
        {        
          // If there are any exceptions, then this is bad, log a FFDC
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:273:1.73",
            this);
            
          SibTr.exception(tc, e);
          
          handleRollback(subMessage, transaction);                
        }
        catch (RuntimeException e)
        {        
          // If there are any exceptions, then this is bad, log a FFDC
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.proxyhandler.NeighbourProxyListener.consumeMessages",
            "1:286:1.73",
            this);
            
          SibTr.exception(tc, e);
          
          handleRollback(subMessage, transaction);        
          
          if (tc.isEntryEnabled()) SibTr.exit(tc, "consumeMessages", e);
          
          throw e;
        }
  
      }
    }

    if (tc.isEntryEnabled())
      SibTr.exit(tc, "consumeMessages");
  }
1278127
synchronized Transport borrowTransport() {
        long now = System.currentTimeMillis();

        List<PooledTransport> garbageTransports = new ArrayList<PooledTransport>();
        PooledTransport candidate = null;

        // Grab a transport
        for (Map.Entry<PooledTransport, Long> entry : idle.entrySet()) {
            PooledTransport transport = entry.getKey();
            if (validate(transport)) {
                candidate = transport;
                break;
            } else {
                garbageTransports.add(transport);
            }
        }

        // Remove any dead connections found
        for (PooledTransport transport : garbageTransports) {
            idle.remove(transport);
            release(transport);
        }

        // Create the connection if we didn't find any, remove it from the pool if we did.
        if (candidate == null) {
            candidate = create();
        } else {
            idle.remove(candidate);
        }

        // Lease.
        leased.put(candidate, now);
        return new LeasedTransport(candidate, this);
    }
443067
def release(self, conn):
        """"""
        self._pool_lock.acquire()
        self._pool.put(ConnectionWrapper(self._pool, conn))
        self._current_acquired -= 1
        self._pool_lock.release()
1307991
@Programmatic
    public CommunicationChannelOwnerLink createLink(
            final CommunicationChannel communicationChannel,
            final Object owner) {

        final CommunicationChannelType type = communicationChannel.getType();
        final Class<? extends CommunicationChannelOwnerLink> subtype = subtypeClassFor(owner, type);

        final CommunicationChannelOwnerLink link = repositoryService.instantiate(subtype);

        link.setCommunicationChannel(communicationChannel);
        // copy over the type, to support subsequent querying.
        link.setCommunicationChannelType(type);

        final Bookmark bookmark = bookmarkService.bookmarkFor(owner);
        link.setOwner(owner);
        link.setOwnerStr(bookmark.toString());

        repositoryService.persist(link);

        return link;
    }
1121
def cli(env, ipv6, test):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    version = 4
    if ipv6:
        version = 6

    if not (test or env.skip_confirmations):
        if not formatting.confirm("This action will incur charges on your "
                                  "account. Continue?"):
            raise exceptions.CLIAbort('Cancelling order.')

    result = mgr.add_global_ip(version=version, test_order=test)

    table = formatting.Table(['item', 'cost'])
    table.align['Item'] = 'r'
    table.align['cost'] = 'r'

    total = 0.0
    for price in result['orderDetails']['prices']:
        total += float(price.get('recurringFee', 0.0))
        rate = "%.2f" % float(price['recurringFee'])

        table.add_row([price['item']['description'], rate])

    table.add_row(['Total monthly cost', "%.2f" % total])
    env.fout(table)
1256388
public static void cost(String type, long costInMilli) {
        info(new JSONObject() {{
            put("type", type);
            put("cost", costInMilli);
        }});
    }
178147
@Override
	public boolean offer( Message e ) {

		boolean result = super.offer( e );
		if( result ) {
			this.receivedMessagesCount.incrementAndGet();
			this.timestampOfLastReceivedMessage.set( new Date().getTime());
		}

		return result;
	}
515581
def send(self, wallet_id, passcode, address, amount, message='', fee=None, fan_unspend=10):
        
        MINIMAL_FEE = 20000
        MINIMAL_SPLIT = 10000000

        wallet = self.get_wallet(wallet_id)

        if not wallet['spendingAccount']:
            raise NotSpendableWallet()

        if not wallet['isActive']:
            raise NotActiveWallet()

        if amount < 10000:
            raise Exception('amount to small')

        if wallet['confirmedBalance'] < amount:
            raise NotEnoughFunds('Not enough funds: balance %s amount %s' %
                                 (wallet['confirmedBalance'], amount)
            )

        change_address = self.create_address(wallet_id, chain=1)
        usableKeychain = False
        spendables = []
        chain_paths = []
        p2sh = []
        payables = [(address, amount)]
        keychain_path = ""

        for keychain in wallet['private']['keychains']:
            keychain_path = keychain['path'][1:]
            keychain = self.get_keychain(keychain['xpub'])
            if 'encryptedXprv' not in keychain:
                continue
            usableKeychain = True
            break

        if not usableKeychain:
            raise BitGoError("didn't found a spendable keychain")

        data = json.loads(keychain['encryptedXprv'])
        #add base64 paddings
        for k in ['iv', 'salt', 'ct']:
            data[k] = data[k] + "=="
        cipher = sjcl.SJCL()
        xprv = cipher.decrypt(data, passcode)

        unspents = self.get_unspents(wallet_id)
        unspents = filter(lambda u: u['confirmations'] > 0, unspents['unspents'][::-1])

        total_value = 0
        for d in unspents:
            path = keychain_path + d['chainPath']
            chain_paths.append(path)
            p2sh.append(h2b(d["redeemScript"]))
            spendables.append(Spendable(d["value"],
                                  h2b(d["script"]),
                                  h2b_rev(d["tx_hash"]),
                                  d["tx_output_n"]))

            total_value += d['value']
            if total_value > amount:
                break

        # make many outputs?
        if len(unspents) < 5 and (total_value > (amount + MINIMAL_SPLIT)) and fan_unspend > 0:
            fee = self.calculate_fee(len(spendables), fan_unspend)
            value = (total_value - amount - fee) / fan_unspend
            for i in range(fan_unspend):
                payables.append((change_address, value))
        elif total_value > (amount + MINIMAL_FEE):
            # add a change address
            if fee is None:
                fee = self.calculate_fee(len(spendables), 2)
            value = total_value - amount - fee
            if value > 10000: #avoid dust
                payables.append((change_address, value))

        p2sh_lookup = build_p2sh_lookup(p2sh)

        spendable_keys = []

        priv_key = BIP32Node.from_hwif(xprv)

        spendable_keys = [priv_key.subkey_for_path(path) for path in chain_paths]

        hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])

        tx = create_tx(spendables, payables)

        tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)

        r = requests.post(self.url + '/tx/send', {
                'tx': tx.as_hex(),
                'message': message
            }, headers={
                'Authorization': 'Bearer %s' % self.access_token,
            })

        return r.json()
1326320
def fromMessage(cls, message):
        
        dh_modulus = message.getArg(OPENID_NS, 'dh_modulus')
        dh_gen = message.getArg(OPENID_NS, 'dh_gen')
        if (dh_modulus is None and dh_gen is not None or
            dh_gen is None and dh_modulus is not None):

            if dh_modulus is None:
                missing = 'modulus'
            else:
                missing = 'generator'

            raise ProtocolError(message,
                                'If non-default modulus or generator is '
                                'supplied, both must be supplied. Missing %s'
                                % (missing,))

        if dh_modulus or dh_gen:
            dh_modulus = cryptutil.base64ToLong(dh_modulus)
            dh_gen = cryptutil.base64ToLong(dh_gen)
            dh = DiffieHellman(dh_modulus, dh_gen)
        else:
            dh = DiffieHellman.fromDefaults()

        consumer_pubkey = message.getArg(OPENID_NS, 'dh_consumer_public')
        if consumer_pubkey is None:
            raise ProtocolError(message, "Public key for DH-SHA1 session "
                                "not found in message %s" % (message,))

        consumer_pubkey = cryptutil.base64ToLong(consumer_pubkey)

        return cls(dh, consumer_pubkey)
664983
def pricing(self):
        
        if self._pricing is None:
            from twilio.rest.pricing import Pricing
            self._pricing = Pricing(self)
        return self._pricing
1140419
private Object openConnection(ManagedConnection mc, Subject s) throws ResourceException
   {
      if (plugin == null)
         return null;

      log.debugf("Open connection (%s, %s)", mc, s);

      return mc.getConnection(s, null);
   }
1069789
public void connect() throws Exception {
        if (connection != null && !connection.isOpen()) {
            connection.open();
            transaction = connection.getModbusTransport().createTransaction();
            ((ModbusSerialTransaction) transaction).setTransDelayMS(transDelay);
            setTransaction(transaction);
        }
    }