Question:
Get the whole slice as a simple integer.

@return Integer long value.

public final long parseInteger() {
        int pos = off, radix = 10;
        boolean neg = false;
        if (len > 2 && charAt(0) == '0' && charAt(1) == 'x') {
            pos += 2;
            radix = 16;
        } else if (len > 1 && charAt(0) == '0') {
            pos += 1;
            radix = 8;
        } else if (len > 1 && charAt(0) == '-') {
            neg = true;
            pos += 1;
        }
        long res = 0;
        for (; pos < off + len; ++pos) {
            res *= radix;
            res += validate(fb[pos], valueOfHex(fb[pos]), radix);
        }
        return neg ? -res : res;
    }

func WriteArray(lst []interface{}, buf *goetty.ByteBuf) {
	buf.WriteByte('*')
	if len(lst) == 0 {
		buf.Write(NullArray)
		buf.Write(Delims)
	} else {
		buf.Write(goetty.StringToSlice(strconv.Itoa(len(lst))))
		buf.Write(Delims)

		for i := 0; i < len(lst); i++ {
			switch v := lst[i].(type) {
			case []interface{}:
				WriteArray(v, buf)
			case [][]byte:
				WriteSliceArray(v, buf)
			case []byte:
				WriteBulk(v, buf)
			case nil:
				WriteBulk(nil, buf)
			case int64:
				WriteInteger(v, buf)
			case string:
				WriteStatus(goetty.StringToSlice(v), buf)
			case error:
				WriteError(goetty.StringToSlice(v.Error()), buf)
			default:
				panic(fmt.Sprintf("invalid array type %T %v", lst[i], v))
			}
		}
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Helper method to set the sortorder.

@return void

protected function set_new_sortorder() {
        $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid'));
        $this->raw_set('sortorder', $this->count_records($search));
    }

public function changeSort(int $id, ?int $prevId, ?int $nextId)
	{
		$this->mapper->changeSort('position', $id, $prevId, $nextId);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Validate data based on the given context of the data AKA Custom Validation.

@param  array  $data   Data to be processed.
@param  string $rules  Custom context validation rules.

@return Payload\Payload

public function validateContext($data, $rules)
	{
		// Init base return values.
		$returnStatus = 'valid';
		$returnData   = null;

		// We only need to validate context if context rules are configured.
		if(array_key_exists('context', $rules))
		{
			foreach($rules['context'] as $rule)
			{
				switch($rule)
				{
					case 'EXAMPLE':
						if(1 !== 2)
						{
							$returnStatus = $rule;
						}
					break;

					default:
					break;
				}
			}
		}

		// Check for any configured custom validation messages.
		if($returnStatus != 'valid')
		{
			if(array_key_exists($returnStatus, $this->messages))
			{
				$data = $this->messages[$returnStatus];
			}
		}

		return new Payload($data, $returnStatus);
	}

public static Map<String, Map<String, Map<String, Map<String, ?>>>> getCoreValidationConstraints() {
		if (CORE_CONSTRAINTS.isEmpty()) {
			for (Map.Entry<String, Class<? extends ParaObject>> e : ParaObjectUtils.getCoreClassesMap().entrySet()) {
				String type = e.getKey();
				List<Field> fieldlist = Utils.getAllDeclaredFields(e.getValue());
				for (Field field : fieldlist) {
					Annotation[] annos = field.getAnnotations();
					if (annos.length > 1) {
						Map<String, Map<String, ?>> constrMap = new HashMap<>();
						for (Annotation anno : annos) {
							if (isValidConstraintType(anno.annotationType())) {
								Constraint c = fromAnnotation(anno);
								if (c != null) {
									constrMap.put(c.getName(), c.getPayload());
								}
							}
						}
						if (!constrMap.isEmpty()) {
							if (!CORE_CONSTRAINTS.containsKey(type)) {
								CORE_CONSTRAINTS.put(type, new HashMap<>());
							}
							CORE_CONSTRAINTS.get(type).put(field.getName(), constrMap);
						}
					}
				}
			}
		}
		return Collections.unmodifiableMap(CORE_CONSTRAINTS);
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetPrimaryEndpoint sets the PrimaryEndpoint field's value.

func (s *NodeGroup) SetPrimaryEndpoint(v *Endpoint) *NodeGroup {
	s.PrimaryEndpoint = v
	return s
}

public void configureHttpPipeline(ChannelPipeline pipeline, TargetHandler targetHandler) {
        pipeline.addLast(Constants.HTTP_CLIENT_CODEC, new HttpClientCodec());
        addCommonHandlers(pipeline);
        pipeline.addLast(Constants.BACK_PRESSURE_HANDLER, new BackPressureHandler());
        pipeline.addLast(Constants.TARGET_HANDLER, targetHandler);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Validates an Ipv6 as Host.

@see http://tools.ietf.org/html/rfc6874#section-2
@see http://tools.ietf.org/html/rfc6874#section-4

private function isValidIpv6Hostname(string $host): bool
    {
        [$ipv6, $scope] = explode('%', $host, 2) + [1 => null];
        if (null === $scope) {
            return (bool) filter_var($ipv6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
        }

        $scope = rawurldecode('%'.$scope);

        return 1 !== preg_match(self::REGEXP_NON_ASCII_PATTERN, $scope)
            && 1 !== preg_match(self::REGEXP_GEN_DELIMS, $scope)
            && filter_var($ipv6, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)
            && 0 === strpos((string) inet_pton((string) $ipv6), self::ADDRESS_BLOCK);
    }

public function checkAddress($address)
    {
        $addr = $this->decodeBase58($address);
        if (strlen($addr) != 50) {
            return false;
        }
        $check = substr($addr, 0, strlen($addr) - 8);
        $check = pack('H*', $check);
        $check = strtoupper(hash('sha256', hash('sha256', $check, true)));
        $check = substr($check, 0, 8);

        return $check == substr($addr, strlen($addr) - 8);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Asserts that base-name is unique. This disallows having multiple invocations for
same base-name but having different alias names.

@param PharInvocation $invocation
@param int $flags
@return bool

private function assertUniqueBaseName(PharInvocation $invocation, int $flags): bool
    {
        if (!($flags & static::UNIQUE_BASE_NAME)) {
            return true;
        }
        return $this->findByCallback(
            function (PharInvocation $candidate) use ($invocation) {
                return $candidate->getBaseName() === $invocation->getBaseName();
            }
        ) === null;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Add additional css classes

@param  array|string  $extra_classes  extra CSS classes

@return  self

public function addExtraClasses($classes)
    {
        if (!is_array($classes)) {
            $classes = explode(" ", $classes);
        }

        $this->extra_classes = array_merge(
            $this->extra_classes,
            $classes
        );

        return $this;
    }

def output_header(code)
      if header = @grammar.directives['header']
        code << header.action.strip
        code << "\n"
      end

      pre_class = @grammar.directives['pre-class']

      if @standalone
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name}\n"

        cp  = standalone_region("compiled_parser.rb")
        cpi = standalone_region("compiled_parser.rb", "INITIALIZE")
        pp  = standalone_region("position.rb")

        cp.gsub!(/^\s*include Position/, pp)
        code << "  # :stopdoc:\n"
        code << cpi << "\n" unless @grammar.variables['custom_initialize']
        code << cp  << "\n"
        code << "  # :startdoc:\n"
      else
        code << "require 'kpeg/compiled_parser'\n\n"
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name} < KPeg::CompiledParser\n"
      end

      @grammar.setup_actions.each do |act|
        code << "\n#{act.action}\n\n"
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Removes all the commerce discounts where expirationDate < ? and status = ? from the database.

@param expirationDate the expiration date
@param status the status

@Override
	public void removeByLtE_S(Date expirationDate, int status) {
		for (CommerceDiscount commerceDiscount : findByLtE_S(expirationDate,
				status, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(commerceDiscount);
		}
	}

public static String getParamFromState(String state, String paramName) {

        String prefix = PARAM_SEPARATOR + paramName + PARAM_ASSIGN;
        if (state.contains(prefix)) {
            String result = state.substring(state.indexOf(prefix) + prefix.length());
            if (result.contains(PARAM_SEPARATOR)) {
                result = result.substring(0, result.indexOf(PARAM_SEPARATOR));
            }
            return CmsEncoder.decode(result, CmsEncoder.ENCODING_UTF_8);
        }
        return null;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Iterate recommend/update procedure and compute incremental recall.

        Args:
            test_events (list of Event): Positive test events.

        Returns:
            list of tuples: (rank, recommend time, update time)

def evaluate(self, test_events):

        for i, e in enumerate(test_events):
            self.__validate(e)

            # target items (all or unobserved depending on a detaset)
            unobserved = set(self.item_buffer)
            if not self.repeat:
                unobserved -= self.rec.users[e.user.index]['known_items']

            # item i interacted by user u must be in the recommendation candidate
            # even if it is a new item
            unobserved.add(e.item.index)

            candidates = np.asarray(list(unobserved))

            # make top-{at} recommendation for the 1001 items
            start = time.clock()
            recos, scores = self.__recommend(e, candidates)
            recommend_time = (time.clock() - start)

            rank = np.where(recos == e.item.index)[0][0]

            # Step 2: update the model with the observed event
            self.rec.users[e.user.index]['known_items'].add(e.item.index)
            start = time.clock()
            self.rec.update(e)
            update_time = (time.clock() - start)

            self.item_buffer.append(e.item.index)

            # (top-1 score, where the correct item is ranked, rec time, update time)
            yield scores[0], rank, recommend_time, update_time

async def connect(self):

        if not self._local_candidates_end:
            raise ConnectionError('Local candidates gathering was not performed')

        if (self.remote_username is None or
           self.remote_password is None):
            raise ConnectionError('Remote username or password is missing')

        # 5.7.1. Forming Candidate Pairs
        for remote_candidate in self._remote_candidates:
            for protocol in self._protocols:
                if (protocol.local_candidate.can_pair_with(remote_candidate) and
                   not self._find_pair(protocol, remote_candidate)):
                    pair = CandidatePair(protocol, remote_candidate)
                    self._check_list.append(pair)
        self.sort_check_list()

        self._unfreeze_initial()

        # handle early checks
        for check in self._early_checks:
            self.check_incoming(*check)
        self._early_checks = []

        # perform checks
        while True:
            if not self.check_periodic():
                break
            await asyncio.sleep(0.02)

        # wait for completion
        if self._check_list:
            res = await self._check_list_state.get()
        else:
            res = ICE_FAILED

        # cancel remaining checks
        for check in self._check_list:
            if check.handle:
                check.handle.cancel()

        if res != ICE_COMPLETED:
            raise ConnectionError('ICE negotiation failed')

        # start consent freshness tests
        self._query_consent_handle = asyncio.ensure_future(self.query_consent())

Instruction: Given a code description, retrieve the corresponding code.


Question: Sends shop data to our api to be saved(or updated) in the db

public function setConsumerData( $consumerKey, $consumerSecret, $store, $apiKey, $currency )
    {

        $endpoint = $this->endpoint . '/consumer_data';

        $params = array_merge($this->prepareParams(), ['consumer_key' => $consumerKey, 'consumer_secret' => $consumerSecret, 'store' => $store, 'api_key' => $apiKey, 'currency' => $currency] );

        $response = $this->restClient->post( $endpoint, $params );

        return $response['body'];
    }

private function _createItem(array $response)
    {
        $model = new Item();
        $model->setName($response[Item::FIELD_NAME])
            ->setDescription($response[Item::FIELD_DESCRIPTION])
            ->setItemNumber($response[Item::FIELD_ITEM_NUMBER])
            ->setUrl($response[Item::FIELD_URL])
            ->setAmount($response[Item::FIELD_AMOUNT])
            ->setQuantity($response[Item::FIELD_QUANTITY]);

        return $model;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Instantiate a HiGlass display with the given views

def display(views, location_sync=[], zoom_sync=[], host='localhost', server_port=None):
    '''

    '''
    from .server import Server
    from .client import ViewConf
    tilesets = []

    for view in views:
        for track in view.tracks:
            if track.tracks:
                for track1 in track.tracks:
                    if track1.tileset:
                        tilesets += [track1.tileset]

            if track.tileset:
                tilesets += [track.tileset]
    print("tilesets:", tilesets)

    server = Server(tilesets, host=host, port=server_port)
    server.start()

    for view in views:
        for track in view.tracks:
            if track.tracks:
                for track1 in track.tracks:
                    if ('server' not in track1.viewconf or
                            track1.viewconf['server'] is None):
                        track1.viewconf['server'] = server.api_address
            else:
                if ('server' not in track.viewconf or
                        track.viewconf['server'] is None):
                    track.viewconf['server'] = server.api_address

    conf = ViewConf(views, location_syncs=location_syncs,
        zoom_syncs=zoom_syncs)

    return (HiGlassDisplay(viewconf=conf.to_dict()), server, conf)

def get_viewer_names(self, dataobj):

        res = []
        for bnch in self.viewer_db.values():
            for vtype in bnch.vtypes:
                if isinstance(dataobj, vtype):
                    res.append(bnch.vname)
        return res

Instruction: Given a code description, retrieve the corresponding code.


Question: Calls openers callbacks

def call_openers(self, client, clients_list):

        for func in self.openers:
            func(client, clients_list)

func init() {
	DefaultCallback.Query().Register("gorm:query", queryCallback)
	DefaultCallback.Query().Register("gorm:preload", preloadCallback)
	DefaultCallback.Query().Register("gorm:after_query", afterQueryCallback)
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Authorization link for OAUTH.

@param int $website

@return string

public function getAuthorizeLink($website = 0)
    {
        //base url, check for custom oauth domain
        if ($this->isAuthorizeCustomDomain($website)) {
            $baseUrl = $this->getWebsiteConfig(self::XML_PATH_CONNECTOR_CUSTOM_DOMAIN)
                . self::API_CONNECTOR_OAUTH_URL_AUTHORISE;
        } else {
            $baseUrl = $this->getRegionAuthorize($website) . self::API_CONNECTOR_OAUTH_URL_AUTHORISE;
        }

        return $baseUrl;
    }

private function parseUrl($url)
    {
        $parsed = parse_url($url);
        if ($parsed === false) {
            throw new ConnectionException('Unable to parse url '. $url);
        }
        array_push($this->hosts, $parsed + ['port' => '61613', 'scheme' => 'tcp']);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Tell this object to stop listening to either specific events ... or to every object it's currently listening to.

function(object, events, callback) {
      var listeners = this._listeners;
      if (!listeners) return;
      if (object) {
        object.off(events, callback, this);
        if (!events && !callback) delete listeners[object._listenerId];
      } else {
        for (var id in listeners) {
          listeners[id].off(null, null, this);
        }
        this._listeners = {};
      }
      return this;
    }

@Override
	public boolean unsubscribeAllChannels() {
        final Collection<BitfinexStreamSymbol> channels = getSubscribedChannels();
        final int channelsToUnsubscribe = channels.size();

        logger.debug("Calling unsubscribe for {} channels", channelsToUnsubscribe);
		final CountDownLatch countDownLatch = new CountDownLatch(channelsToUnsubscribe);

        try (Closeable c = callbackRegistry.onUnsubscribeChannelEvent(s -> countDownLatch.countDown())) {
            channels.forEach(symbol -> sendCommand(new UnsubscribeChannelCommand(symbol)));

            // Await the unsubscription
            countDownLatch.await(30, TimeUnit.SECONDS);

            return true;
        } catch (final InterruptedException | IOException e) {
            Thread.currentThread().interrupt();
            return false;
        }
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the evaluated view contents for the given view.

@param  string  $view
@param  array   $data
@param  array   $mergeData
@return \Illuminate\View\View

public function render($view, $data = [], $mergeData = [])
    {
        if (isset($this->aliases[$view])) {
            $view = $this->aliases[$view];
        }

        $view = $this->normalizeName($view);

        return $this->factory->render($view, $data, $mergeData);
    }

public function addReturning(string ...$expression) : self
    {
        $this->returningExpressions = array_merge($this->returningExpressions, $expression);

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // EvalReal returns real representation of Column.

func (col *Column) EvalReal(ctx sessionctx.Context, row chunk.Row) (float64, bool, error) {
	if row.IsNull(col.Index) {
		return 0, true, nil
	}
	if col.GetType().Tp == mysql.TypeFloat {
		return float64(row.GetFloat32(col.Index)), false, nil
	}
	return row.GetFloat64(col.Index), false, nil
}

public function setScale($scale)
    {
        if (($scale !== null) && (!is_int($scale) || ($scale < 0))) {
            throw SchemaException::invalidColumnScale($this->getName());
        }

        $this->scale = $scale;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *JSONSchemaPropsOrStringArray) DeepCopyInto(out *JSONSchemaPropsOrStringArray) {
	*out = *in
	if in.Schema != nil {
		in, out := &in.Schema, &out.Schema
		*out = (*in).DeepCopy()
	}
	if in.Property != nil {
		in, out := &in.Property, &out.Property
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	return
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

Instruction: Given a code description, retrieve the corresponding code.


Question: File approve event handler

def OnApprove(self, event):
        """"""

        if not self.main_window.safe_mode:
            return

        msg = _(u"You are going to approve and trust a file that\n"
                u"you have not created yourself.\n"
                u"After proceeding, the file is executed.\n \n"
                u"It may harm your system as any program can.\n"
                u"Please check all cells thoroughly before\nproceeding.\n \n"
                u"Proceed and sign this file as trusted?")

        short_msg = _("Security warning")

        if self.main_window.interfaces.get_warning_choice(msg, short_msg):
            # Leave safe mode
            self.main_window.grid.actions.leave_safe_mode()

            # Display safe mode end in status bar

            statustext = _("Safe mode deactivated.")
            post_command_event(self.main_window, self.main_window.StatusBarMsg,
                               text=statustext)

public List<SuggestedFix> drive(Scanner scanner, Pattern includeFilePattern) {
    JsFlumeCallback callback = new JsFlumeCallback(scanner, includeFilePattern);
    NodeTraversal.traverse(compiler, rootNode, callback);
    List<SuggestedFix> fixes = callback.getFixes();
    fixes.addAll(scanner.processAllMatches(callback.getMatches()));
    return fixes;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set this property to all views inside `_content`
@param {string} name Property name
@param {*} value Property value

function(name, value) {

		for (var i = 0; i < this._count; i++) {

			if (this._content[i].isView) {

				this._content[i].set(name, value);

			}

		}

	}

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
//Hash creates a random 16 character salt and creates a key using this salt
//Key generation function: SHA512 with 5000 iterations
// If you want to generate the same key on the commandline:
// `echo "user:password" | chpasswd -c SHA512 -S | cut -d: -f 2`

func Hash(password string) (key string, err error) {
	c := sha512crypt.New()
	key, err = c.Generate([]byte(password), []byte(""))

	return
}

protected function passwordHash(Entity\Users $usersEntity)
    {
        if ($usersEntity->getPassword() !== null) {
            $usersEntity->setPassword($this->getValidHash($usersEntity->getPassword()));
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns array representation of DTO properties.

@return mixed[]

public function toArray(): array
    {
        $result = [];
        foreach (static::getInstanceProperties() as $key) {
            $result[$key] = $this->$key;
        }

        return $result;
    }

public static function ddp($obj = NULL)
	{
		try
		{
			$json_str = json_encode($obj, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
			echo $json_str;
			die();
		}
		catch(SangriaException $e)
		{
			/**
			 * Default to dd if there is an exception while encoding to JSON
			 */
			var_dump($obj);
			die();
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Dispatches a request.

@param RequestContextInterface $request
@param MatchContextInterface $match

@return mixed the request response.

public function dispatchMatch(MatchContextInterface $match)
    {
        // store the previous request context.
        $request = $this->url->getRequestContext();

        $this->url->setRequestContext($match->getRequest());
        $this->routeStack->push($match->getName());

        $response = $this->mapper->mapResponse($this->dispatcher->dispatch($match));

        $this->routeStack->pop();

        // restore the previous request context.
        if (null !== $request) {
            $this->url->setRequestContext($request);
        }

        return $response;
    }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Auto Generated Code

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_time_since_last_change = ET.SubElement(fcoe_intf_list, "fcoe-intf-time-since-last-change")
        fcoe_intf_time_since_last_change.text = kwargs.pop('fcoe_intf_time_since_last_change')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// GetRequestPostData invokes the Network method. Returns post data sent with
// the request. Returns an error when no data was sent with the request.

func (d *domainClient) GetRequestPostData(ctx context.Context, args *GetRequestPostDataArgs) (reply *GetRequestPostDataReply, err error) {
	reply = new(GetRequestPostDataReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Network.getRequestPostData", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Network.getRequestPostData", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Network", Op: "GetRequestPostData", Err: err}
	}
	return
}

public static function data($key=null,$default=null){
    if (null===static::$body){
      $json = (false !== stripos(empty($_SERVER['HTTP_CONTENT_TYPE'])?'':$_SERVER['HTTP_CONTENT_TYPE'],'json'))
           || (false !== stripos(empty($_SERVER['CONTENT_TYPE'])?'':$_SERVER['CONTENT_TYPE'],'json'));
      if ($json) {
        static::$body = json_decode(file_get_contents("php://input"));
      } else {
       if (empty($_POST)) {
          static::$body = file_get_contents("php://input");
        } else {
          static::$body = (object)$_POST;
        }
      }
    }
    return $key ? (isset(static::$body->$key) ? static::$body->$key : (is_callable($default)?call_user_func($default):$default))  : static::$body;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: filecache is called and the decorator should be returned.

def filecache(seconds_of_validity=None, fail_silently=False):
    '''

    '''
    def filecache_decorator(function):
        @_functools.wraps(function)
        def function_with_cache(*args, **kwargs):
            try:
                key = _args_key(function, args, kwargs)

                if key in function._db:
                    rv = function._db[key]
                    if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity:
                        return rv.data
            except Exception:
                # in any case of failure, don't let filecache break the program
                error_str = _traceback.format_exc()
                _log_error(error_str)
                if not fail_silently:
                    raise

            retval = function(*args, **kwargs)

            # store in cache
            # NOTE: no need to _db.sync() because there was no mutation
            # NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break!
            try:
                function._db[key] = _retval(_time.time(), retval)
                function._db.sync()
            except Exception:
                # in any case of failure, don't let filecache break the program
                error_str = _traceback.format_exc()
                _log_error(error_str)
                if not fail_silently:
                    raise

            return retval

        # make sure cache is loaded
        if not hasattr(function, '_db'):
            cache_name = _get_cache_name(function)
            if cache_name in OPEN_DBS:
                function._db = OPEN_DBS[cache_name]
            else:
                function._db = _shelve.open(cache_name)
                OPEN_DBS[cache_name] = function._db
                atexit.register(function._db.close)

            function_with_cache._db = function._db

        return function_with_cache

    if type(seconds_of_validity) == types.FunctionType:
        # support for when people use '@filecache.filecache' instead of '@filecache.filecache()'
        func = seconds_of_validity
        seconds_of_validity = None
        return filecache_decorator(func)

    return filecache_decorator

function() {
              bundle.browserify.pipeline.get('deps').push(through.obj(function(row, enc, next) {
                var file = row.expose ? bundle.browserify._expose[row.id] : row.file;

                if (self.cache) {
                  bundle.browserifyOptions.cache[file] = {
                    source: row.source,
                    deps: xtend({}, row.deps)
                  };
                }

                this.push(row);
                next();
              }));
            }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Parse the site-text string and return a list of sites.

        Returns
        -------
        sites : list[Site]
            A list of position-residue pairs corresponding to the site-text

def get_sites(self):

        st = self.site_text
        suffixes = [' residue', ' residues', ',', '/']
        for suffix in suffixes:
            if st.endswith(suffix):
                st = st[:-len(suffix)]
        assert(not st.endswith(','))

        # Strip parentheses
        st = st.replace('(', '')
        st = st.replace(')', '')
        st = st.replace(' or ', ' and ')  # Treat end and or the same

        sites = []
        parts = st.split(' and ')
        for part in parts:
            if part.endswith(','):
                part = part[:-1]
            if len(part.strip()) > 0:
                sites.extend(ReachProcessor._parse_site_text(part.strip()))
        return sites

def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []

    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities

Instruction: Given a code description, retrieve the corresponding code.


Question: // DescribeVolumes is specified on the storage.VolumeSource interface.

func (v *ebsVolumeSource) DescribeVolumes(ctx context.ProviderCallContext, volIds []string) ([]storage.DescribeVolumesResult, error) {
	// TODO(axw) invalid volIds here should not cause the whole
	// operation to fail. If we get an invalid volume ID response,
	// fall back to querying each volume individually. That should
	// be rare.
	resp, err := v.env.ec2.Volumes(volIds, nil)
	if err != nil {
		return nil, maybeConvertCredentialError(err, ctx)
	}
	byId := make(map[string]ec2.Volume)
	for _, vol := range resp.Volumes {
		byId[vol.Id] = vol
	}
	results := make([]storage.DescribeVolumesResult, len(volIds))
	for i, volId := range volIds {
		vol, ok := byId[volId]
		if !ok {
			results[i].Error = errors.NotFoundf("%s", volId)
			continue
		}
		results[i].VolumeInfo = &storage.VolumeInfo{
			Size:       gibToMib(uint64(vol.Size)),
			VolumeId:   vol.Id,
			Persistent: true,
		}
		for _, attachment := range vol.Attachments {
			if attachment.DeleteOnTermination {
				results[i].VolumeInfo.Persistent = false
				break
			}
		}
	}
	return results, nil
}

public function getDescription()
    {
        return vsprintf(
            'The value is expected to be between %f and %f'
            . ' (%f <= x <= %f).',
            [$this->min, $this->max, $this->min, $this->max]
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the renderer for this location in the table.
From the TableCellRenderer interface.
Sets the value of this control and returns this.
@return this.

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        this.setControlValue(value);
        if (isSelected && !hasFocus) {
            this.setForeground(table.getSelectionForeground());
            this.setBackground(table.getSelectionBackground());
        }
        else {
            this.setForeground(table.getForeground());
            this.setBackground(table.getBackground());
        }
        return this;
    }

public void setText(final String TEXT) {
        if (null == text) {
            _text = TEXT;
            fireUpdateEvent(REDRAW_EVENT);
        } else {
            text.set(TEXT);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets the index to the given index without validating. If the index is out of bound the consecutive token() call
will throw a runtime exception.

@param indexToNavigateTo value to set the cursor's index to.

void index(int indexToNavigateTo) {
        this.index = 0;
        this.offset = 0;
        this.nextSplit = StringUtil.indexOf(path, '.', 0);
        this.token = null;

        for (int i = 1; i <= indexToNavigateTo; i++) {
            if (!advanceToNextToken()) {
                throw new IndexOutOfBoundsException("Index out of bound " + indexToNavigateTo + " in " + path);
            }
        }
    }

def lookup_ids(self, keys):
        """"""
        keys_len = len(keys)
        ids = {namespace_key: None for namespace_key in keys}
        start = 0
        bulk_insert = self.bulk_insert
        query = 'SELECT namespace, key, id FROM gauged_keys WHERE '
        check = '(namespace = %s AND key = %s) '
        cursor = self.cursor
        execute = cursor.execute
        while start < keys_len:
            rows = keys[start:start+bulk_insert]
            params = [param for params in rows for param in params]
            id_query = query + (check + ' OR ') * (len(rows) - 1) + check
            execute(id_query, params)
            for namespace, key, id_ in cursor:
                ids[(namespace, key)] = id_
            start += bulk_insert
        return ids

Instruction: Given a code description, retrieve the corresponding code.


Question: Clear the contents of the build area.

def clean(self):
        """"""
        if os.path.exists(self.buildroot):
            log.info('Clearing the build area.')
            log.debug('Deleting: %s', self.buildroot)
            shutil.rmtree(self.buildroot)
            os.makedirs(self.buildroot)

function reset() {
		globalConfig = {};
		modules = {};
		services = {};
		behaviors = {};
		instances = {};
		initialized = false;

		for (var i = 0; i < exports.length; i++) {
			delete application[exports[i]];
			delete Box.Context.prototype[exports[i]];
		}
		exports = [];
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Generate a telegraf tag suffix

func t(tags []string) string {
	for i, v := range tags {
		tags[i] = strings.Replace(v, ":", "=", 1)
	}
	t := ""
	if len(tags) > 0 {
		t = "" + strings.Join(tags, ",")
	}
	return t
}

def _agl_compliant_name(glyph_name):
    """"""
    MAX_GLYPH_NAME_LENGTH = 63
    clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name)
    if len(clean_name) > MAX_GLYPH_NAME_LENGTH:
        return None
    return clean_name

Instruction: Given a code description, retrieve the corresponding code.


Question:
validation
@param $type
@param $data
@param $mayBeNull
@param $mayBeEmpty
@param $exceptions
@return bool

protected function validation($type, $data, $mayBeNull, $mayBeEmpty, $exceptions)
    {
        if ($mayBeNull == false) {
            if ($this->isNull($data, $exceptions))
            {
                return false;
            }

            if ($this->isOfCorrectType($data, $type, $exceptions) != true)
            {
                return false;
            }
            if ($mayBeEmpty == false) {
                if ($this->isEmpty($data, $exceptions)) {
                    return false;
                }
            }
        }
        return true;
    }

function set($attribute, $value = null) {
    $attributes = is_array($attribute)
                ? $attribute
                : [$attribute => $value];

    foreach ($attributes as $attr => $val) {

      if ($this->getPropertyFor($attr, 'accepts')) {
          $acceptsConstraint = new Attributes\Constraint\Accepts($this->getPropertyFor($attr, 'accepts'));
          if (!$acceptsConstraint->isValid($val)) {
              throw new InvalidArgumentException(__CLASS__ . " does not accept {$val} as value for the property {$attr}");
          }
      }

      if ($this->getPropertyFor($attr, 'minimum')) {
          $minimumConstraint = new Attributes\Constraint\Minimum($this->getPropertyFor($attr, 'minimum'));
          if (!$minimumConstraint->isValid($val)) {
              throw new InvalidArgumentException(__CLASS__ . " does not accept {$val} as value for the property {$attr}");
          }
      }

      if ($this->getPropertyFor($attr, 'maximum')) {
          $maximumConstraint = new Attributes\Constraint\Maximum($this->getPropertyFor($attr, 'maximum'));
          if (!$maximumConstraint->isValid($val)) {
              throw new InvalidArgumentException(__CLASS__ . " does not accept {$val} as value for the property {$attr}");
          }
      }

      $this->setPropertyFor($attr, 'value', $val, 'set');
    }

    return $this;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: // clear all pending *Calls.

func (cp *callPool) Clear(fn func(c *Call)) {
	cp.Lock()
	for k, c := range cp.pending {
		fn(c)
		delete(cp.pending, k)
	}
	cp.Unlock()
}

private function getEndCall(Expr $arg = null)
    {
        if ($arg === null) {
            $arg = NoReturnValue::create();
        }

        return new StaticCall(new FullyQualifiedName('Psy\Command\TimeitCommand'), 'markEnd', [new Arg($arg)]);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param string $name

@return string

public function getRiakField($name)
    {
        return isset($this->riakProperties[$name])
            ? $this->riakProperties[$name]
            : null;
    }

func (s *DescribeDBParametersInput) SetSource(v string) *DescribeDBParametersInput {
	s.Source = &v
	return s
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // UpdateWAF updates a specific WAF.

func (c *Client) UpdateWAF(i *UpdateWAFInput) (*WAF, error) {
	if i.Service == "" {
		return nil, ErrMissingService
	}

	if i.Version == 0 {
		return nil, ErrMissingVersion
	}

	if i.ID == "" {
		return nil, ErrMissingWAFID
	}

	path := fmt.Sprintf("/service/%s/version/%d/wafs/%s", i.Service, i.Version, i.ID)
	resp, err := c.PatchJSONAPI(path, i, nil)
	if err != nil {
		return nil, err
	}

	var waf WAF
	if err := jsonapi.UnmarshalPayload(resp.Body, &waf); err != nil {
		return nil, err
	}
	return &waf, nil
}

func (*SwitchesTable) needsUpdate(row, cfg *Switch) bool {
	return row.Ports != cfg.Ports || row.Description != cfg.Description || row.State != cfg.State || row.RackId != cfg.RackId
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Determines and returns the progressive approximation for the knn distances
of this node as the maximum of the progressive approximations of all
entries.

@param k_max the maximum k parameter
@return the conservative approximation for the knn distances

protected ApproximationLine progressiveKnnDistanceApproximation(int k_max) {
    if(!isLeaf()) {
      throw new UnsupportedOperationException("Progressive KNN-distance approximation " + "is only vailable in leaf nodes!");
    }

    // determine k_0, y_1, y_kmax
    int k_0 = 0;
    double y_1 = Double.POSITIVE_INFINITY;
    double y_kmax = Double.POSITIVE_INFINITY;

    for(int i = 0; i < getNumEntries(); i++) {
      MkCoPLeafEntry entry = (MkCoPLeafEntry) getEntry(i);
      ApproximationLine approx = entry.getProgressiveKnnDistanceApproximation();
      k_0 = Math.max(approx.getK_0(), k_0);
    }

    for(int i = 0; i < getNumEntries(); i++) {
      MkCoPLeafEntry entry = (MkCoPLeafEntry) getEntry(i);
      ApproximationLine approx = entry.getProgressiveKnnDistanceApproximation();
      y_1 = Math.min(approx.getValueAt(k_0), y_1);
      y_kmax = Math.min(approx.getValueAt(k_max), y_kmax);
    }

    // determine m and t
    double m = (y_kmax - y_1) / (FastMath.log(k_max) - FastMath.log(k_0));
    double t = y_1 - m * FastMath.log(k_0);

    return new ApproximationLine(k_0, m, t);
  }

def __get_max_min_time_1(self, table):

        try:
            # find the values and units we need to calculate
            vals, units = self.__get_max_min_time_2(table, ["age", "yearbp", "yrbp"], True)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["year", "yr"], True)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["age", "yearbp", "yrbp"], False)

            if not vals and not units:
                vals, units = self.__get_max_min_time_2(table, ["year", "yr"], False)

            # now put this data into the noaa data sorted self for writing to file.
            # year farthest in the past
            _max = max(vals)
            _min = min(vals)
            if _min or _min in [0, 0.0]:
                self.noaa_data_sorted["Data_Collection"]["Earliest_Year"] = str(_min)
            if _max or _max in [0, 0.0]:
                self.noaa_data_sorted["Data_Collection"]["Most_Recent_Year"] = str(_max)
            # AD or... yrs BP?
            self.noaa_data_sorted["Data_Collection"]["Time_Unit"] = units

        except Exception as e:
            logger_lpd_noaa.debug("get_max_min_time_2: {}".format(e))

        return

Instruction: Given a code description, retrieve the corresponding code.


Question:
Reads the given template (SMTP formatted) and sets all fields
        accordingly.

        :type  string: string
        :param string: The template.

def set_from_template_string(self, string):

        in_header = True
        body = ''
        for line in string.split('\n'):
            if not in_header:
                body += line + '\n'
                continue
            if not _is_header_line(line):
                body += line + '\n'
                in_header = False
                continue
            key, value = _get_var_from_header_line(line)
            if key == 'from':
                self.set_sender(value)
            elif key == 'to':
                self.add_to(value)
            elif key == 'cc':
                self.add_cc(value)
            elif key == 'bcc':
                self.add_bcc(value)
            elif key == 'subject':
                self.set_subject(value)
            else:
                raise Exception('Invalid header field "%s"' % key)
        self.set_body(body.strip())

private function buildPayload(Swift_Mime_Message $message)
    {
        try {
            return $this->payloadBuilder->buildPayload($message);
        } catch (AnyException $exception) {
            throw $this->createAndDispatchTransportException(
                'Failed to build payload for a SparkPost transmission',
                $exception
            );
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// New EvtxFile structure initialized from file
// @filepath : filepath of the evtx file to parse
// return File : File structure initialized

func New(filepath string) (ef File, err error) {
	file, err := os.Open(filepath)
	if err != nil {
		return
	}
	ef.file = file
	ef.ParseFileHeader()
	return
}

def _ParseShellItemPathSegment(self, shell_item):

    path_segment = None

    if isinstance(shell_item, pyfwsi.root_folder):
      description = shell_folder_ids.DESCRIPTIONS.get(
          shell_item.shell_folder_identifier, None)

      if description:
        path_segment = description
      else:
        path_segment = '{{{0:s}}}'.format(shell_item.shell_folder_identifier)

      path_segment = '<{0:s}>'.format(path_segment)

    elif isinstance(shell_item, pyfwsi.volume):
      if shell_item.name:
        path_segment = shell_item.name
      elif shell_item.identifier:
        path_segment = '{{{0:s}}}'.format(shell_item.identifier)

    elif isinstance(shell_item, pyfwsi.file_entry):
      long_name = ''
      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name

      if long_name:
        path_segment = long_name
      elif shell_item.name:
        path_segment = shell_item.name

    elif isinstance(shell_item, pyfwsi.network_location):
      if shell_item.location:
        path_segment = shell_item.location

    if path_segment is None and shell_item.class_type == 0x00:
      # TODO: check for signature 0x23febbee
      pass

    if path_segment is None:
      path_segment = '<UNKNOWN: 0x{0:02x}>'.format(shell_item.class_type)

    return path_segment

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets the name of the property which contains the raw value.

@param string $valuePropertyName

@return static
@throws InvalidArgumentException On invalid argument

public function setValuePropertyName($valuePropertyName)
    {
        if (!is_string($valuePropertyName) || $valuePropertyName === '') {
            throw new InvalidArgumentException('"Value property name" argument must be a string and must not empty.');
        }

        if (!property_exists($this, $valuePropertyName)) {
            throw new InvalidArgumentException(sprintf('Property "%s" does not exist.', $valuePropertyName));
        }

        $this->valuePropertyName = $valuePropertyName;

        return $this;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // MustParseV4 parses a node URL. It panics if the URL is not valid.

func MustParseV4(rawurl string) *Node {
	n, err := ParseV4(rawurl)
	if err != nil {
		panic("invalid node URL: " + err.Error())
	}
	return n
}

public function asEndpoint()
    {
        $graphVersionPrefix = '';
        if ($this->graphVersion) {
            $graphVersionPrefix = '/'.$this->graphVersion;
        }

        return $graphVersionPrefix.$this->graphNode->asUrl($this->appSecret);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Timeouts can be overwritten in properties.yml under the `timeout` key.

@param string $setting

@return int

protected function getTimeoutSetting($setting)
    {
        $timeoutSettings = $this->getTimeoutSettings();
        return isset($timeoutSettings[$setting]) ? $timeoutSettings[$setting] : static::DEFAULT_TIMEOUT;
    }

def main(operation, profile, auto, debug, user_name=''):

    if user_name:
        logger.info('user_name parameter given (%s) as surrogate' % user_name)
    try:
        if operation in VALID_INSTALL:
            print(operation)
        elif operation == 'list':
            print(operation)
            return True
        elif not operation:
            msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET)
            msg = """You must provide a valid OPERATION for --operation parameter:

                    --operation { """ + msg_accent + """ }
            """
            stdout_message(msg)
            logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
        else:
            msg = 'Unknown operation. Exit'
            stdout_message(msg)
            logger.warning('%s: %s' % (msg, inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
    except KeyError as e:
        logger.critical(
            '%s: Cannot find Key %s' %
            (inspect.stack()[0][3], str(e)))
        return False
    except OSError as e:
        logger.critical(
            '%s: problem writing to file %s. Error %s' %
            (inspect.stack()[0][3], output_file, str(e)))
        return False
    except Exception as e:
        logger.critical(
            '%s: Unknown error. Error %s' %
            (inspect.stack()[0][3], str(e)))
        raise e

Instruction: Given a code description, retrieve the corresponding code.


Question:
Find all content for a given user and replace him by another.

@param User $from
@param User $to

@return int

public function replaceCommentUser(User $from, User $to)
    {
        $comments = $this->commentRepo->findByUser($from);

        if (count($comments) > 0) {
            foreach ($comments as $comment) {
                $comment->setUser($to);
            }

            $this->om->flush();
        }

        return count($comments);
    }

private void synchronizeElement(
        CmsObject cms,
        String elementPath,
        Collection<String> skipPaths,
        Locale sourceLocale) {

        if (elementPath.contains("/")) {
            String parentPath = CmsXmlUtils.removeLastXpathElement(elementPath);
            List<I_CmsXmlContentValue> parentValues = getValuesByPath(parentPath, sourceLocale);
            String elementName = CmsXmlUtils.getLastXpathElement(elementPath);
            for (I_CmsXmlContentValue parentValue : parentValues) {
                String valuePath = CmsXmlUtils.concatXpath(parentValue.getPath(), elementName);
                boolean skip = false;
                for (String skipPath : skipPaths) {
                    if (valuePath.startsWith(skipPath)) {
                        skip = true;
                        break;
                    }
                }
                if (!skip) {
                    if (hasValue(valuePath, sourceLocale)) {
                        List<I_CmsXmlContentValue> subValues = getValues(valuePath, sourceLocale);
                        removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale);
                        for (I_CmsXmlContentValue value : subValues) {
                            if (value.isSimpleType()) {
                                setValueForOtherLocales(cms, value, CmsXmlUtils.removeLastXpathElement(valuePath));
                            } else {
                                List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value);
                                for (I_CmsXmlContentValue simpleValue : simpleValues) {
                                    setValueForOtherLocales(cms, simpleValue, parentValue.getPath());
                                }
                            }
                        }
                    } else {
                        removeValuesInOtherLocales(valuePath, sourceLocale);
                    }
                }
            }
        } else {
            if (hasValue(elementPath, sourceLocale)) {
                List<I_CmsXmlContentValue> subValues = getValues(elementPath, sourceLocale);
                removeSurplusValuesInOtherLocales(elementPath, subValues.size(), sourceLocale);
                for (I_CmsXmlContentValue value : subValues) {
                    if (value.isSimpleType()) {
                        setValueForOtherLocales(cms, value, null);
                    } else {
                        List<I_CmsXmlContentValue> simpleValues = getAllSimpleSubValues(value);
                        for (I_CmsXmlContentValue simpleValue : simpleValues) {
                            setValueForOtherLocales(cms, simpleValue, null);
                        }
                    }
                }
            } else {
                removeValuesInOtherLocales(elementPath, sourceLocale);
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Preserves the order of elements in the list

def remove_duplicates_from_list(array):
    ""
    output = []
    unique = set()
    for a in array:
        if a not in unique:
            unique.add(a)
            output.append(a)
    return output

def postorder(self, skip_seed=False):

        for node in self._tree.postorder_node_iter():
            if skip_seed and node is self._tree.seed_node:
                continue
            yield node

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the style of faulting factor, depending on the mechanism (rake)
        and top of rupture depth (equations (4) and (5), pages 145 - 146)

def _compute_style_of_faulting_term(self, C, rup):

        frv, fnm = self._get_fault_type_dummy_variables(rup.rake)

        if frv > 0.:
            # Top of rupture depth term only applies to reverse faults
            if rup.ztor < 1.:
                ffltz = rup.ztor
            else:
                ffltz = 1.
        else:
            ffltz = 0.
        return (C['c7'] * frv * ffltz) + (C['c8'] * fnm)

def message(topic, message = nil)
      raise ArgumentError, "block or message, not both" if block_given? && message

      message = yield if block_given?
      message = message.to_s.gsub(%r!\s+!, " ")
      topic = formatted_topic(topic, block_given?)
      out = topic + message
      messages << out
      out
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

@Override
	public EClass getRemoteServiceUpdate() {
		if (remoteServiceUpdateEClass == null) {
			remoteServiceUpdateEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(84);
		}
		return remoteServiceUpdateEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

Instruction: Given a code description, retrieve the corresponding code.


Question: // Configure provides a mock function with given fields: clusterId, isRoot, rawConfig

func (_m *MockProvider) Configure(clusterId string, isRoot bool, rawConfig map[string]interface{}) error {
	ret := _m.Called(clusterId, isRoot, rawConfig)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, bool, map[string]interface{}) error); ok {
		r0 = rf(clusterId, isRoot, rawConfig)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

public void bootStrap(String customClusterXml, String customStoresXml) {
        AbstractStoreClientFactory factory = (AbstractStoreClientFactory) this.storeFactory;
        this.store = factory.getRawStore(storeName, null, customStoresXml, customClusterXml, null);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Delegate to the appropriate method of the underlying logger.

public void trace(String format, Object... args) {
        if (!logger.isTraceEnabled())
            return;

        if (instanceofLAL) {
            String formattedMessage = MessageFormatter.arrayFormat(format, args).getMessage();
            ((LocationAwareLogger) logger).log(null, fqcn, LocationAwareLogger.TRACE_INT, formattedMessage, args, null);
        } else {
            logger.trace(format, args);
        }
    }

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Marshall the given parameter object.

public void marshall(StopAssessmentRunRequest stopAssessmentRunRequest, ProtocolMarshaller protocolMarshaller) {

        if (stopAssessmentRunRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(stopAssessmentRunRequest.getAssessmentRunArn(), ASSESSMENTRUNARN_BINDING);
            protocolMarshaller.marshall(stopAssessmentRunRequest.getStopAction(), STOPACTION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Note we can rely on the StepContext properties already having been set at this point.

@return global transaction timeout defined in step properties. default
timeout value is 180

private int initStepTransactionTimeout() {
        logger.entering(sourceClass, "initStepTransactionTimeout");
        Properties p = runtimeStepExecution.getProperties();
        int timeout = DEFAULT_TRAN_TIMEOUT_SECONDS; // default as per spec.
        if (p != null && !p.isEmpty()) {

            String propertyTimeOut = p.getProperty("javax.transaction.global.timeout");
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "javax.transaction.global.timeout = {0}", propertyTimeOut == null ? "<null>" : propertyTimeOut);
            }
            if (propertyTimeOut != null && !propertyTimeOut.isEmpty()) {
                timeout = Integer.parseInt(propertyTimeOut, 10);
            }
        }
        logger.exiting(sourceClass, "initStepTransactionTimeout", timeout);
        return timeout;
    }

func (s *RecordLifecycleActionHeartbeatInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RecordLifecycleActionHeartbeatInput"}
	if s.AutoScalingGroupName == nil {
		invalidParams.Add(request.NewErrParamRequired("AutoScalingGroupName"))
	}
	if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("AutoScalingGroupName", 1))
	}
	if s.InstanceId != nil && len(*s.InstanceId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("InstanceId", 1))
	}
	if s.LifecycleActionToken != nil && len(*s.LifecycleActionToken) < 36 {
		invalidParams.Add(request.NewErrParamMinLen("LifecycleActionToken", 36))
	}
	if s.LifecycleHookName == nil {
		invalidParams.Add(request.NewErrParamRequired("LifecycleHookName"))
	}
	if s.LifecycleHookName != nil && len(*s.LifecycleHookName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("LifecycleHookName", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Validate returns whether or not the given Event is valid

func (e *Event) Validate(v strfmt.Registry) error {
	if err := e.ID.Validate(v); err != nil {
		return err
	}

	if e.Version() != 1 {
		return manifold.NewError(errors.BadRequestError, "Expected version to be 1")
	}

	return e.Body.Validate(v)
}

public void addFatal( String key, Throwable throwable )
    {
        logEvent( FATAL, getString( key ), throwable );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Internal method to toggle autoescaping on or off. This function
    needs access to the caller, so the calling method must be
    decorated with @supports_caller.

def _toggle_autoescape(context, escape_on=True):
    '''

    '''
    previous = is_autoescape(context)
    setattr(context.caller_stack, AUTOESCAPE_KEY, escape_on)
    try:
        context['caller'].body()
    finally:
        setattr(context.caller_stack, AUTOESCAPE_KEY, previous)

def badge(self, *args, **kwargs):

        return self._makeApiCall(self.funcinfo["badge"], *args, **kwargs)

Instruction: Given a code description, retrieve the corresponding code.


Question: New in 6.0: Get current custom statistic settings

@Override
    public String getCustomSetString() {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "getCustomSetString");

        String ret = PmiRegistry.getInstrumentationLevelString60();

        if (tc.isEntryEnabled())
            Tr.exit(tc, "getCustomSetString");

        return ret;
    }

public function collStats($options)
    {
        $cmd = ['collStats' => $options['table']];
        $command = new Command($cmd);
        $this->log('cmd', 'collStats', $cmd);
        return $command;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // NewClientWithCreds creates client with credentials

func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error) {
	clt, err := i.NewUnauthenticatedClient(cfg)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	err = SetupUserCreds(clt, i.Config.Proxy.SSHAddr.Addr, creds)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return clt, nil
}

function(userId, appId) {
        if(!appId){
            return userId + '-' + config.creds.appId + '@' + config.endpoints.chat;
        }
        return userId + '-' + appId + '@' + config.endpoints.chat;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Create new rule.
@param inequalitySymbol inequality symbol.
@param value Symbolic name of comparison level.
@return instance of AbstractRule.

public static Rule getRule(final String inequalitySymbol,
                               final String value) {

        Level thisLevel;

        //if valid util.logging levels are used against events
        // with log4j levels, the
        //DEBUG level is used and an illegalargumentexception won't be generated

        //an illegalargumentexception is only generated
        // if the user types a level name
        //that doesn't exist as either a log4j or util.logging level name
        if (levelList.contains(value.toUpperCase())) {
            thisLevel = Level.toLevel(value.toUpperCase());
        } else if (utilLoggingLevelList.contains(value.toUpperCase())) {
            thisLevel = UtilLoggingLevel.toLevel(value.toUpperCase());
        } else {
            throw new IllegalArgumentException(
                    "Invalid level inequality rule - " + value
                            + " is not a supported level");
        }

        if ("<".equals(inequalitySymbol)) {
            return new LessThanRule(thisLevel);
        }
        if (">".equals(inequalitySymbol)) {
            return new GreaterThanRule(thisLevel);
        }
        if ("<=".equals(inequalitySymbol)) {
            return new LessThanEqualsRule(thisLevel);
        }
        if (">=".equals(inequalitySymbol)) {
            return new GreaterThanEqualsRule(thisLevel);
        }

        return null;
    }

function (input, stateMachine) {
      if (!input) { return []; }
      if (stateMachine === undefined) { stateMachine = 'ce'; }
      var state = '0';

      //
      // String buffers for parsing:
      //
      // buffer.a == amount
      // buffer.o == element
      // buffer.b == left-side superscript
      // buffer.p == left-side subscript
      // buffer.q == right-side subscript
      // buffer.d == right-side superscript
      //
      // buffer.r == arrow
      // buffer.rdt == arrow, script above, type
      // buffer.rd == arrow, script above, content
      // buffer.rqt == arrow, script below, type
      // buffer.rq == arrow, script below, content
      //
      // buffer.text_
      // buffer.rm
      // etc.
      //
      // buffer.parenthesisLevel == int, starting at 0
      // buffer.sb == bool, space before
      // buffer.beginsWithBond == bool
      //
      // These letters are also used as state names.
      //
      // Other states:
      // 0 == begin of main part (arrow/operator unlikely)
      // 1 == next entity
      // 2 == next entity (arrow/operator unlikely)
      // 3 == next atom
      // c == macro
      //
      /** @type {Buffer} */
      var buffer = {};
      buffer['parenthesisLevel'] = 0;

      input = input.replace(/\n/g, " ");
      input = input.replace(/[\u2212\u2013\u2014\u2010]/g, "-");
      input = input.replace(/[\u2026]/g, "...");

      //
      // Looks through mhchemParser.transitions, to execute a matching action
      // (recursive)
      //
      var lastInput;
      var watchdog = 10;
      /** @type {ParserOutput[]} */
      var output = [];
      while (true) {
        if (lastInput !== input) {
          watchdog = 10;
          lastInput = input;
        } else {
          watchdog--;
        }
        //
        // Find actions in transition table
        //
        var machine = mhchemParser.stateMachines[stateMachine];
        var t = machine.transitions[state] || machine.transitions['*'];
        iterateTransitions:
        for (var i=0; i<t.length; i++) {
          var matches = mhchemParser.patterns.match_(t[i].pattern, input);
          if (matches) {
            //
            // Execute actions
            //
            var task = t[i].task;
            for (var iA=0; iA<task.action_.length; iA++) {
              var o;
              //
              // Find and execute action
              //
              if (machine.actions[task.action_[iA].type_]) {
                o = machine.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
              } else if (mhchemParser.actions[task.action_[iA].type_]) {
                o = mhchemParser.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
              } else {
                throw ["MhchemBugA", "mhchem bug A. Please report. (" + task.action_[iA].type_ + ")"];  // Trying to use non-existing action
              }
              //
              // Add output
              //
              mhchemParser.concatArray(output, o);
            }
            //
            // Set next state,
            // Shorten input,
            // Continue with next character
            //   (= apply only one transition per position)
            //
            state = task.nextState || state;
            if (input.length > 0) {
              if (!task.revisit) {
                input = matches.remainder;
              }
              if (!task.toContinue) {
                break iterateTransitions;
              }
            } else {
              return output;
            }
          }
        }
        //
        // Prevent infinite loop
        //
        if (watchdog <= 0) {
          throw ["MhchemBugU", "mhchem bug U. Please report."];  // Unexpected character
        }
      }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Close closes the file, writing any remaining data out to disk and waiting
// for acknowledgements from the datanodes. It is important that Close is called
// after all data has been written.

func (f *FileWriter) Close() error {
	if f.closed {
		return io.ErrClosedPipe
	}

	var lastBlock *hdfs.ExtendedBlockProto
	if f.blockWriter != nil {
		lastBlock = f.blockWriter.Block.GetB()

		// Close the blockWriter, flushing any buffered packets.
		err := f.finalizeBlock()
		if err != nil {
			return err
		}
	}

	completeReq := &hdfs.CompleteRequestProto{
		Src:        proto.String(f.name),
		ClientName: proto.String(f.client.namenode.ClientName),
		Last:       lastBlock,
	}
	completeResp := &hdfs.CompleteResponseProto{}

	err := f.client.namenode.Execute("complete", completeReq, completeResp)
	if err != nil {
		return &os.PathError{"create", f.name, err}
	}

	return nil
}

def run_postdecode_hooks(decode_hook_args, dataset_split):
  """"""
  hooks = decode_hook_args.problem.decode_hooks
  if not hooks:
    return
  global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir)
  if global_step is None:
    tf.logging.info(
        "Skipping decode hooks because no checkpoint yet available.")
    return
  tf.logging.info("Running decode hooks.")
  parent_dir = os.path.join(decode_hook_args.output_dirs[0], os.pardir)
  child_dir = decode_hook_args.decode_hparams.summaries_log_dir
  if dataset_split is not None:
    child_dir += "_{}".format(dataset_split)
  final_dir = os.path.join(parent_dir, child_dir)
  summary_writer = tf.summary.FileWriter(final_dir)

  for hook in hooks:
    # Isolate each hook in case it creates TF ops
    with tf.Graph().as_default():
      summaries = hook(decode_hook_args)
    if summaries:
      summary = tf.Summary(value=list(summaries))
      summary_writer.add_summary(summary, global_step)
  summary_writer.close()
  tf.logging.info("Decode hooks done.")

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a compact representation of all of the tags the task has.

@param  task The task to get tags on.
@return Request object

public CollectionRequest<Task> tags(String task) {

        String path = String.format("/tasks/%s/tags", task);
        return new CollectionRequest<Task>(this, Task.class, path, "GET");
    }

public Observable<ServiceResponse<Void>> publishVideoReviewWithServiceResponseAsync(String teamName, String reviewId) {
        if (this.client.baseUrl() == null) {
            throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
        }
        if (teamName == null) {
            throw new IllegalArgumentException("Parameter teamName is required and cannot be null.");
        }
        if (reviewId == null) {
            throw new IllegalArgumentException("Parameter reviewId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{baseUrl}", this.client.baseUrl());
        return service.publishVideoReview(teamName, reviewId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = publishVideoReviewDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Service a request.

@param request the http request facade

@Override
  public void service(RequestWeb request)
  {
    try {
      if (! request.method().equals("OPTIONS")) {
        request.ok();
        return;
      }

      if (_crossOrigin.allowCredentials())
        request.header(ALLOW_CREDENTIALS, "true");

      //allow-origin
      String[] origin = _crossOrigin.value();

      if (origin.length == 0)
        origin = _crossOrigin.allowOrigin();

      if (origin.length > 0)
        request.header(ALLOW_ORIGIN, join(origin));

      //allow methods
      HttpMethod[] methods = _crossOrigin.allowMethods();

      if (methods.length > 0) {
        request.header(ALLOW_METHODS, join(methods));
      }
      else if (_httpMethod != null) {
        request.header(ALLOW_METHODS, _httpMethod.toString());
      }

      //allow headers
      String[] allowHeaders = _crossOrigin.allowHeaders();
      if (allowHeaders.length > 0)
        request.header(ALLOW_HEADERS, join(allowHeaders));

      //expose headers
      String[] exposeHeaders = _crossOrigin.exposeHeaders();
      if (exposeHeaders.length > 0)
        request.header(EXPOSE_HEADERS, join(exposeHeaders));

      //max age
      request.header(MAX_AGE, Long.toString(_crossOrigin.maxAge()));

      request.ok();
      request.halt();
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }
  }

func (s *GetSampledRequestsOutput) SetSampledRequests(v []*SampledHTTPRequest) *GetSampledRequestsOutput {
	s.SampledRequests = v
	return s
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the rules associated with status attribute.
@return array

public function getStatusRules()
    {
        if (!is_string($this->statusAttribute) || empty($this->statusAttribute)) {
            return [];
        }
        if (empty($this->statusRules)) {
            $this->statusRules = [
                [[$this->statusAttribute], 'required'],
                [[$this->statusAttribute], 'number', 'integerOnly' => true, 'min' => 0],
            ];
        }
        return $this->statusRules;
    }

public function err($message, $code = -1, $level = 'info')
    {
        return $this->ret->err($message, $code, $level);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Gets the list of class names in the given directory.

@param string $directory

@return array

private function getClasses($directory)
    {
        $classes = [];
        $directoryList = [];
        $includedFiles = [];

        $finder = new Finder();
        try {
            $finder->in($directory)->files()->name('*.php');
        } catch (\InvalidArgumentException $e) {
            return [[], []];
        }

        foreach ($finder as $file) {
            $directoryList[$file->getPath()] = true;
            $sourceFile = $file->getRealpath();
            if (!preg_match('(^phar:)i', $sourceFile)) {
                $sourceFile = realpath($sourceFile);
            }

            require_once $sourceFile;
            $includedFiles[$sourceFile] = true;
        }

        $declared = get_declared_classes();
        foreach ($declared as $className) {
            $reflectionClass = new \ReflectionClass($className);
            $sourceFile = $reflectionClass->getFileName();

            if ($reflectionClass->isAbstract()) {
                continue;
            }

            if (method_exists($reflectionClass, 'isAnonymous') && $reflectionClass->isAnonymous()) {
                continue;
            }

            if (isset($includedFiles[$sourceFile])) {
                $classes[$className] = true;
            }
        }

        return [array_keys($classes), $directoryList];
    }

public function dirs($resource, $recursive = false, $filter = null)
    {
        return $this->ls($resource, self::LS_MODE_DIR, $recursive, $filter);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the single String value representation for the given value map.<p>

@param valueMap the value map to create the single String value for

@return the single String value representation for the given value map

private String createValueFromMap(Map<String, String> valueMap) {

        if (valueMap == null) {
            return null;
        }
        StringBuffer result = new StringBuffer(valueMap.size() * 32);
        Iterator<Map.Entry<String, String>> i = valueMap.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, String> entry = i.next();
            String key = entry.getKey();
            String value = entry.getValue();
            key = replaceDelimiter(key, VALUE_LIST_DELIMITER, VALUE_LIST_DELIMITER_REPLACEMENT);
            key = replaceDelimiter(key, VALUE_MAP_DELIMITER, VALUE_MAP_DELIMITER_REPLACEMENT);
            value = replaceDelimiter(value, VALUE_LIST_DELIMITER, VALUE_LIST_DELIMITER_REPLACEMENT);
            value = replaceDelimiter(value, VALUE_MAP_DELIMITER, VALUE_MAP_DELIMITER_REPLACEMENT);
            result.append(key);
            result.append(VALUE_MAP_DELIMITER);
            result.append(value);
            if (i.hasNext()) {
                result.append(VALUE_LIST_DELIMITER);
            }
        }
        return result.toString();
    }

protected function mapSingleEntity(Element $entity)
    {
        $element = new \ReflectionObject($entity);
        $properties = $element->getProperties();
        $xml = '';
        foreach ($properties as $property) {
            $propName = $property->getName();
            $propValue = $entity->$propName;
            if ($propValue !== null) {
                $xml .= '<FL val="' . str_replace(['_', 'N36', 'E5F', '&', '98T'], [' ', '$', '_', 'and', '?'], $propName) . '">';
                // It's a list of entities
                if (is_array($propValue)) {
                    $tag = null;
                    list($key, $list) = each($propValue);
                    if (!is_numeric($key)) {
                        $tag = $key;
                        $propValue = $list;
                    }
                    $xml .= $this->mapEntityList($propValue, $tag);
                }
                // It's an entity
                elseif (is_object($propValue) && (!$propValue instanceof \DateTime)) {
                    $xml .= $this->mapSingleEntity($propValue);
                }
                else {
                    $propValue = (string) $propValue;
                    // Use Character Data for non integers
                    if (!ctype_digit($propValue)) {
                       $propValue = "<![CDATA[$propValue]]>";
                    }
                    $xml .= $propValue;
                }
                $xml .= '</FL>';
            }
        }
        return $xml;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// NewCheckout creates a new Checkout populated with the repositories and revision
// found in the GitilesCommits object.

func NewCheckout(commits notifypb.GitilesCommits) Checkout {
	results := make(Checkout, len(commits.GetCommits()))
	for _, gitilesCommit := range commits.GetCommits() {
		results[protoutil.GitilesRepoURL(gitilesCommit)] = gitilesCommit.Id
	}
	return results
}

def _next_file_gen(self, root):

    for e in root.getiterator(common._T_CONTENTS):
      st_ctime, size, etag, key = None, None, None, None
      for child in e.getiterator('*'):
        if child.tag == common._T_LAST_MODIFIED:
          st_ctime = common.dt_str_to_posix(child.text)
        elif child.tag == common._T_ETAG:
          etag = child.text
        elif child.tag == common._T_SIZE:
          size = child.text
        elif child.tag == common._T_KEY:
          key = child.text
      yield common.GCSFileStat(self._path + '/' + key,
                               size, etag, st_ctime)
      e.clear()
    yield None

Instruction: Given a code description, retrieve the corresponding code.


Question:
Write the xml data into the file.

        Parameters
        ----------
        filename: Name of the file.

        Examples
        -------
        >>> writer = UAIWriter(model)
        >>> writer.write_xmlbif(test_file)

def write_uai(self, filename):

        writer = self.__str__()
        with open(filename, 'w') as fout:
            fout.write(writer)

func ReadConfig(configFilePath string) (ConfigSetterWriter, error) {
	var (
		format formatter
		config *configInternal
	)
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot read agent config %q", configFilePath)
	}
	format, config, err = parseConfigData(configData)
	if err != nil {
		return nil, err
	}
	logger.Debugf("read agent config, format %q", format.version())
	config.configFilePath = configFilePath
	return config, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Method to create the URL formed string with the parameters.

@param   string  $url         The request URL.
@param   array   $parameters  Array containing request parameters.

@return  string  The formed URL.

@since   1.0

public function toUrl($url, $parameters)
	{
		foreach ($parameters as $key => $value)
		{
			if (\is_array($value))
			{
				foreach ($value as $k => $v)
				{
					if (strpos($url, '?') === false)
					{
						$url .= '?' . $key . '=' . $v;
					}
					else
					{
						$url .= '&' . $key . '=' . $v;
					}
				}
			}
			else
			{
				if (strpos($value, ' ') !== false)
				{
					$value = $this->safeEncode($value);
				}

				if (strpos($url, '?') === false)
				{
					$url .= '?' . $key . '=' . $value;
				}
				else
				{
					$url .= '&' . $key . '=' . $value;
				}
			}
		}

		return $url;
	}

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Unregisters error pages from web container.

@throws NullArgumentException if error page is null
@see WebAppVisitor#visit(WebAppErrorPage)

public void visit(final WebAppErrorPage webAppErrorPage) {
		NullArgumentException.validateNotNull(webAppErrorPage,
				"Web app error page");
		//CHECKSTYLE:OFF
		try {
			webContainer.unregisterErrorPage(webAppErrorPage.getError(),
					httpContext);
		} catch (Exception ignore) {
			LOG.warn("Unregistration exception. Skipping.", ignore);
		}
		//CHECKSTYLE:ON
	}

public static UnitResponse createMissingParam(Object theMissingParameters, String errMsg) {
        return UnitResponse.createError(Group.CODE_LACK_OF_PARAMETER, theMissingParameters, errMsg);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Computes the correlation between two datasets.
@param list1 The first dataset as a list.
@param list2 The second dataset as a list.
@return The correlation between the two datasets.

public static double computeCorrelation(final List<Double> list1, final List<Double> list2)
    {
        final SpearmansRankCorrelation_old src = new SpearmansRankCorrelation_old();
        for (int i = 0; i < list1.size(); i++) {
            src.addXValue(Integer.toString(i), list1.get(i));
            src.addYValue(Integer.toString(i), list2.get(i));
            i++;
        }
        return src.calculate();
    }

def intuition(args):
    '''

    '''

    # Use the provided context builder to fill:
    #   - config: General behavior
    #   - strategy: Modules properties
    #   - market: The universe we will trade on
    with setup.Context(args['context']) as context:

        # Backtest or live engine.
        # Registers configuration and setups data client
        simulation = Simulation()

        # Intuition building blocks
        modules = context['config']['modules']

        # Prepare benchmark, timezone, trading calendar
        simulation.configure_environment(
            context['config']['index'][-1],
            context['market'].benchmark,
            context['market'].timezone)

        # Wire togetether modules and initialize them
        simulation.build(args['session'],
                         modules,
                         context['strategy'])

        # Build data generator
        # NOTE How can I use several sources ?
        data = {'universe': context['market'],
                'index': context['config']['index']}
        # Add user settings
        data.update(context['strategy']['data'])
        # Load backtest and / or live module(s)
        if 'backtest' in modules:
            data['backtest'] = utils.intuition_module(modules['backtest'])
        if 'live' in modules:
            data['live'] = utils.intuition_module(modules['live'])

        # Run the simulation and return an intuition.core.analyzes object
        return simulation(datafeed.HybridDataFactory(**data), args['bot'])

Instruction: Given a code description, retrieve the corresponding code.


Question: // New - create an inventory service wrapper.

func (client *MyInventoryClient) New(appEnv *cfenv.App) *MyInventoryClient {

  if strings.ToUpper(os.Getenv("DISPLAY_NEW_SERVICES")) == "YES" {
    client.Enabled = true
    client.ServiceBaseURL = getServiceBinding("inventory-service", "target-url", appEnv)
  } else {
    client.Enabled = false
  }
  return client
}

func (s *server) RelayInventory(invVect *wire.InvVect, data interface{}) {
	s.relayInv <- relayMsg{invVect: invVect, data: data}
}

Instruction: Given a code description, retrieve the corresponding code.