Handles the Blocks option in a outgoing request.

        :type request: Request
        :param request: the outgoing request
        :return: the edited request
343247
def send_request(self, request):
        
        assert isinstance(request, Request)
        if request.block1 or (request.payload is not None and len(request.payload) > defines.MAX_PAYLOAD):
            host, port = request.destination
            key_token = hash(str(host) + str(port) + str(request.token))
            if request.block1:
                num, m, size = request.block1
            else:
                num = 0
                m = 1
                size = defines.MAX_PAYLOAD

            self._block1_sent[key_token] = BlockItem(size, num, m, size, request.payload, request.content_type)
            request.payload = request.payload[0:size]
            del request.block1
            request.block1 = (num, m, size)
        elif request.block2:
            host, port = request.destination
            key_token = hash(str(host) + str(port) + str(request.token))
            num, m, size = request.block2
            item = BlockItem(size, num, m, size, "", None)
            self._block2_sent[key_token] = item
            return request
        return request
1028972
def call(self, request):
        
        result = None
        try:
            if 'extAction' in request:  # DirectSubmit method
                tid = request['extTID']
                action = request['extAction']
                method = request['extMethod']
            else:
                tid = request['tid']
                action = request['action']
                method = request['method']
            element = self.configuration[action][method]
            if isinstance(element, tuple):  # class level function
                func = getattr(self.instances[element[0]], element[1])
            else:  # module level function
                func = element
            if func.exposed_kind == BASIC:  # basic method
                args = request['data'] or []
                result = func(*args)
            elif func.exposed_kind == LOAD:  # DirectLoad method
                args = request['data'] or []
                result = {'success': True, 'data': func(*args)}
            elif func.exposed_kind == SUBMIT:  # DirectSubmit method
                kwargs = request
                for k in ['extAction', 'extMethod', 'extType', 'extTID', 'extUpload']:
                    if k in kwargs:
                        del kwargs[k]
                try:
                    func(**kwargs)
                    result = {'success': True}
                except FormError as e:
                    result = e.extra
                    result['success'] = False
                    if e.errors:
                        result['errors'] = e.errors
            elif func.exposed_kind == STORE_READ:  # DirectStore read method
                kwargs = request['data'] or {}
                data = func(**kwargs)
                result = {'total': len(data), 'data': data}
            elif func.exposed_kind == STORE_CUD:  # DirectStore create-update-destroy methods
                kwargs = request['data'][0] or {}
                try:
                    result = {'success': True, 'data': func(**kwargs)}
                except Error:
                    result = {'success': False}
        except Exception as e:
            if self.debug:
                return {'type': 'exception', 'message': str(e), 'where': '%s.%s' % (action, method)}
        return {'type': 'rpc', 'tid': tid, 'action': action, 'method': method, 'result': result}
258971
def dispatch(self, request, *args, **kwargs):
        
        # this part copied from django source code
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(),
                              self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        # we changed only this line - removed first 'request' argument
        return handler(*args, **kwargs)
326075
def insertMigrationRequest(self, request):
        
        conn = self.dbi.connection()
        # check if already queued.
        #If the migration_input is the same, but the src url is different,
        #We will consider it as a submitted request. YG 05-18-2012
        try:
            alreadyqueued = self.mgrlist.execute(conn,
                                                 migration_input=request["migration_input"])
            is_already_queued = len(alreadyqueued) > 0
            # close connection before returning json object
            if is_already_queued and conn:
                conn.close()
            #if the queued is not failed, then we don't need to do it again.
            #add a new migration_status=9 (terminal failure)
	    if is_already_queued and alreadyqueued[0]['migration_status'] == 2:
                return {"migration_report" : "REQUEST ALREADY QUEUED. Migration is finished",
                        "migration_details" : alreadyqueued[0] }
            elif is_already_queued and alreadyqueued[0]['migration_status'] != 9:
                return {"migration_report" : "REQUEST ALREADY QUEUED. Migration in progress",
                        "migration_details" : alreadyqueued[0] }
            elif is_already_queued and alreadyqueued[0]['migration_status'] == 9:
                return {"migration_report" : "REQUEST ALREADY QUEUED. Migration terminally failed. ",
                        "migration_details" : alreadyqueued[0] }
            else:
                # not already queued
                #Determine if its a dataset or block migration
                #The prepare list calls will check if the requested blocks/dataset already in destination.
                if request["migration_input"].find("#") != -1:
                    ordered_list = self.prepareBlockMigrationList(conn, request)
                else:
                    ordered_list = self.prepareDatasetMigrationList(conn, request)
            # now we have the blocks that need to be queued (ordered)
        except Exception as ex:
            if conn: conn.close()
            raise

        tran = conn.begin()
        try:
            # insert the request
            #request.update(migration_status=0)
            request['migration_request_id'] = self.sm.increment(conn, "SEQ_MR", tran)
            self.mgrin.execute(conn, request, tran)
            # INSERT the ordered_list
            totalQueued = 0
	    k = ordered_list.keys()
	    k.sort()
	    k.reverse()	
	    self.logger.debug("****************** ordered_list keys **********")
            self.logger.debug(k)
            #for iter in reversed(range(len(ordered_list))):
	    for iter in k:	
		self.logger.debug("length for Key: %s" %iter)
	        self.logger.debug(len(ordered_list[iter]))	
                if len(ordered_list[iter]) > 0:
                    daoinput = [{
                        "migration_block_id" :
                            self.sm.increment(conn, "SEQ_MB", tran),
                        "migration_request_id" :
                            request["migration_request_id"],
                        "migration_block_name" : blk,
                        "migration_order" : iter,
                        "migration_status" : 0,
                        "creation_date" : request['creation_date'],
                        "last_modification_date" : request['last_modification_date'],
                        "create_by" : request['create_by'],
                        "last_modified_by" : request['last_modified_by']
                        }
                             for blk in ordered_list[iter]]
                    self.mgrblkin.execute(conn, daoinput, tran)
                    totalQueued += len(ordered_list[iter])
            # all good ?, commit the transaction
            tran.commit()
            if conn: conn.close()
            # return things like (X blocks queued for migration)
            return {
                "migration_report" : "REQUEST QUEUED with total %d blocks to be migrated" %totalQueued,
                "migration_details" : request }
        except SQLAlchemyIntegrityError as ex:
	    e = "DBSMigration:  ENQUEUEING_FAILED1 from SQLAichemy Integrity Error. Reason may be (%s)" %(ex.statement + "; " + str(ex.params) + "; " + str(ex.orig))
	    self.logger.debug(e)		
	    import traceback
            tk = traceback.format_exc() 		
	    self.logger.debug(tk) 	
            tran.rollback()
            if conn: conn.close()
            if (str(ex).find("unique constraint") != -1 or
                str(ex).lower().find("duplicate") != -1):
                #FIXME: Need to check which unique key. YG 2/11/13
                #The unique constraints are: MIGRATION_REQUESTS(MIGRATION_INPUT)
                #MIGRATION_BLOCKS(MIGRATION_BLOCK_NAME, MIGRATION_REQUEST_ID)
                return {
                    "migration_report" : "REQUEST ALREADY QUEUED",
                    "migration_details" : request }
            else:
                if conn: conn.close()
		self.logger.error(tk)
                m = "DBSMigration:  ENQUEUEING_FAILED1."
                dbsExceptionHandler('dbsException-invalid-input2', m, self.logger.exception, e)
	except HTTPError as he:
	    raise he	
        except Exception as ex:
	    import traceback
            self.logger.error(traceback.format_exc())	
            if tran: tran.rollback()
            if conn: conn.close()
            m = "DBSMigration:  ENQUEUEING_FAILED."
            e = "DBSMigration:  ENQUEUEING_FAILED. General exception caught: Reason may be (%s)" %str(ex)
            dbsExceptionHandler('dbsException-invalid-input2', m, self.logger.exception, e)
        finally:
            if conn: conn.close()
76907
def in_edit_mode(self, request, placeholder):
        
        toolbar = getattr(request, 'toolbar', None)
        edit_mode = getattr(toolbar, 'edit_mode', False) and getattr(placeholder, 'is_editable', True)
        if edit_mode:
            edit_mode = placeholder.has_change_permission(request.user)
        return edit_mode
1105375
def process_request(self, request):
        
        if self._is_enabled():
            self._cache.set(self.guid_key, six.text_type(uuid4()))
            log_prefix = self._log_prefix(u"Before", request)
            self._cache.set(self.memory_data_key, self._memory_data(log_prefix))
296298
public void submitRequest(AsyncCacheRequest request) {
    ASYNC_CACHE_REQUESTS.inc();
    long blockId = request.getBlockId();
    long blockLength = request.getLength();
    if (mPendingRequests.putIfAbsent(blockId, request) != null) {
      // This block is already planned.
      ASYNC_CACHE_DUPLICATE_REQUESTS.inc();
      return;
    }
    try {
      mAsyncCacheExecutor.submit(() -> {
        boolean result = false;
        try {
          // Check if the block has already been cached on this worker
          long lockId = mBlockWorker.lockBlockNoException(Sessions.ASYNC_CACHE_SESSION_ID, blockId);
          if (lockId != BlockLockManager.INVALID_LOCK_ID) {
            try {
              mBlockWorker.unlockBlock(lockId);
            } catch (BlockDoesNotExistException e) {
              LOG.error("Failed to unlock block on async caching. We should never reach here", e);
            }
            ASYNC_CACHE_DUPLICATE_REQUESTS.inc();
            return;
          }
          Protocol.OpenUfsBlockOptions openUfsBlockOptions = request.getOpenUfsBlockOptions();
          boolean isSourceLocal = mLocalWorkerHostname.equals(request.getSourceHost());
          // Depends on the request, cache the target block from different sources
          if (isSourceLocal) {
            ASYNC_CACHE_UFS_BLOCKS.inc();
            result = cacheBlockFromUfs(blockId, blockLength, openUfsBlockOptions);
          } else {
            ASYNC_CACHE_REMOTE_BLOCKS.inc();
            InetSocketAddress sourceAddress =
                new InetSocketAddress(request.getSourceHost(), request.getSourcePort());
            result = cacheBlockFromRemoteWorker(
                    blockId, blockLength, sourceAddress, openUfsBlockOptions);
          }
          LOG.debug("Result of async caching block {}: {}", blockId, result);
        } catch (Exception e) {
          LOG.warn("Async cache request failed.\n{}\nError: {}", request, e);
        } finally {
          if (result) {
            ASYNC_CACHE_SUCCEEDED_BLOCKS.inc();
          } else {
            ASYNC_CACHE_FAILED_BLOCKS.inc();
          }
          mPendingRequests.remove(blockId);
        }
      });
    } catch (Exception e) {
      // RuntimeExceptions (e.g. RejectedExecutionException) may be thrown in extreme cases when the
      // gRPC thread pool is drained due to highly concurrent caching workloads. In these cases,
      // return as async caching is at best effort.
      LOG.warn("Failed to submit async cache request.\n{}\nError: {}", request, e);
      ASYNC_CACHE_FAILED_BLOCKS.inc();
      mPendingRequests.remove(blockId);
    }
  }
48345
def batch(request, request_options = {})
      client.post(Protocol.batch_uri(name), request.to_json, :batch, request_options)
    end
822852
def request(self, request):
        
        if request is None:
            raise ValueError("Invalid value for `request`, must not be `None`")
        if request is not None and not re.search('^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$', request):
            raise ValueError("Invalid value for `request`, must be a follow pattern or equal to `/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/`")

        self._request = request
379983
def changeable(self, request):
        '''
        
        '''
        return self.apply_changeable(self.get_queryset(), request) if self.check_changeable(self.model, request) is not False else self.get_queryset().none()
1135951
def handle_request(self, request, **resources):
        

        if request.method == 'OPTIONS':
            return super(RPCResource, self).handle_request(
                request, **resources)

        payload = request.data

        try:

            if request.method == 'GET':
                payload = request.GET.get('payload')
                try:
                    payload = js.loads(payload)
                except TypeError:
                    raise AssertionError("Invalid RPC Call.")

            if 'method' not in payload:
                raise AssertionError("Invalid RPC Call.")
            return self.rpc_call(request, **payload)

        except Exception as e: # noqa (any error)
            return SerializedHttpResponse(dict(error=dict(message=str(e))), error=True)
366076
public void changeSelected(String selectNode, ServletRequest request)
    {
        _selectedNode = TreeHelpers.changeSelected(this, _selectedNode, selectNode, request);
    }
297695
def post_request(url)
      do_request(url, Net::HTTP::Post) do |request|
        yield(request) if block_given?
      end
    end
659946
@Override
	public void handleRequest(final Request request) {
		if (isDisabled()) {
			// Protect against client-side tampering of disabled/read-only fields.
			return;
		}

		if (isMenuPresent(request)) {
			// If current ajax trigger, process menu for current selections
			if (AjaxHelper.isCurrentAjaxTrigger(this)) {
				WMenu menu = WebUtilities.getAncestorOfClass(WMenu.class, this);
				menu.handleRequest(request);

				// Execute associated action, if set
				final Action action = getAction();

				if (action != null) {
					final ActionEvent event = new ActionEvent(this, this.getActionCommand(),
							this.getActionObject());

					Runnable later = new Runnable() {
						@Override
						public void run() {
							action.execute(event);
						}
					};

					invokeLater(later);
				}
			}

			boolean openState = "true".equals(request.getParameter(getId() + ".open"));
			setOpen(openState);
		}
	}
354343
def HandleBlockReceived(self, inventory):
        
        block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block')
        if not block:
            return

        blockhash = block.Hash.ToBytes()
        try:
            if blockhash in BC.Default().BlockRequests:
                BC.Default().BlockRequests.remove(blockhash)
        except KeyError:
            pass
        try:
            if blockhash in self.myblockrequests:
                # logger.debug(f"{self.prefix} received block: {block.Index}")
                self.heart_beat(HEARTBEAT_BLOCKS)
                self.myblockrequests.remove(blockhash)
        except KeyError:
            pass
        self.leader.InventoryReceived(block)
24288
def _handle_get(self, request):
        # type: (Get) -> CallbackResponses
        """"""
        data = self._block

        for i, endpoint in enumerate(request.path[1:]):
            try:
                data = data[endpoint]
            except KeyError:
                if hasattr(data, "typeid"):
                    typ = data.typeid
                else:
                    typ = type(data)
                raise UnexpectedError(
                    "Object %s of type %r has no attribute %r" % (
                        request.path[:i+1], typ, endpoint))
        # Important to serialize now with the lock so we get a consistent set
        serialized = serialize_object(data)
        ret = [request.return_response(serialized)]
        return ret
112211
def poll_command_request(self):
        
        try:
            message = self.rpc.recv(zmq.NOBLOCK)
        except zmq.ZMQError as exc:
            if exc.errno == zmq.EAGAIN:
                return
            else:
                raise

        _logger.debug("Received command %s", message)
        segments = _unpack(message)
        action, params = segments[0], segments[1:]
        _logger.debug("Adding %s, %s to the request queue", action, params)
        self._command = _Command(action, params)