Question: src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:285:1: equalityExpression returns [BaseDescr result] : left= instanceOfExpression ( (op= EQUALS |op= NOT_EQUALS ) right= instanceOfExpression )* ;

public final BaseDescr equalityExpression() throws RecognitionException {
		BaseDescr result = null;

		Token op=null;
		BaseDescr left =null;
		BaseDescr right =null;

		try {
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:286:3: (left= instanceOfExpression ( (op= EQUALS |op= NOT_EQUALS ) right= instanceOfExpression )* )
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:286:5: left= instanceOfExpression ( (op= EQUALS |op= NOT_EQUALS ) right= instanceOfExpression )*
			{
			pushFollow(FOLLOW_instanceOfExpression_in_equalityExpression1395);
			left=instanceOfExpression();
			state._fsp--;
			if (state.failed) return result;
			if ( state.backtracking==0 ) { if( buildDescr  ) { result = left; } }
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:287:3: ( (op= EQUALS |op= NOT_EQUALS ) right= instanceOfExpression )*
			loop32:
			while (true) {
				int alt32=2;
				int LA32_0 = input.LA(1);
				if ( (LA32_0==EQUALS||LA32_0==NOT_EQUALS) ) {
					alt32=1;
				}

				switch (alt32) {
				case 1 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:287:5: (op= EQUALS |op= NOT_EQUALS ) right= instanceOfExpression
					{
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:287:5: (op= EQUALS |op= NOT_EQUALS )
					int alt31=2;
					int LA31_0 = input.LA(1);
					if ( (LA31_0==EQUALS) ) {
						alt31=1;
					}
					else if ( (LA31_0==NOT_EQUALS) ) {
						alt31=2;
					}

					else {
						if (state.backtracking>0) {state.failed=true; return result;}
						NoViableAltException nvae =
							new NoViableAltException("", 31, 0, input);
						throw nvae;
					}

					switch (alt31) {
						case 1 :
							// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:287:7: op= EQUALS
							{
							op=(Token)match(input,EQUALS,FOLLOW_EQUALS_in_equalityExpression1407); if (state.failed) return result;
							}
							break;
						case 2 :
							// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:287:19: op= NOT_EQUALS
							{
							op=(Token)match(input,NOT_EQUALS,FOLLOW_NOT_EQUALS_in_equalityExpression1413); if (state.failed) return result;
							}
							break;

					}

					if ( state.backtracking==0 ) {  helper.setHasOperator( true );
					       if( input.LA( 1 ) != DRL5Lexer.EOF ) helper.emit( Location.LOCATION_LHS_INSIDE_CONDITION_ARGUMENT ); }
					pushFollow(FOLLOW_instanceOfExpression_in_equalityExpression1429);
					right=instanceOfExpression();
					state._fsp--;
					if (state.failed) return result;
					if ( state.backtracking==0 ) { if( buildDescr  ) {
					               result = new RelationalExprDescr( (op!=null?op.getText():null), false, null, left, right );
					           }
					         }
					}
					break;

				default :
					break loop32;
				}
			}

			}

		}

		catch (RecognitionException re) {
		    throw re;
		}

		finally {
			// do for sure before leaving
		}
		return result;
	}

def _match_replace_binary(cls, ops: list) -> list:
    """"""
    n = len(ops)
    if n <= 1:
        return ops
    ops_left = ops[:n // 2]
    ops_right = ops[n // 2:]
    return _match_replace_binary_combine(
        cls,
        _match_replace_binary(cls, ops_left),
        _match_replace_binary(cls, ops_right))

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


Question: Marshall the given parameter object.

public void marshall(StartTopicsDetectionJobRequest startTopicsDetectionJobRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getInputDataConfig(), INPUTDATACONFIG_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getOutputDataConfig(), OUTPUTDATACONFIG_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getDataAccessRoleArn(), DATAACCESSROLEARN_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getJobName(), JOBNAME_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getNumberOfTopics(), NUMBEROFTOPICS_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING);
            protocolMarshaller.marshall(startTopicsDetectionJobRequest.getVolumeKmsKeyId(), VOLUMEKMSKEYID_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: Writes an {@link HttpData}.

public final ChannelFuture writeData(int id, int streamId, HttpData data, boolean endStream) {

        assert eventLoop().inEventLoop();

        if (closed) {
            ReferenceCountUtil.safeRelease(data);
            return newClosedSessionFuture();
        }

        return doWriteData(id, streamId, data, endStream);
    }

protected String parseJspLinkMacros(String content, CmsFlexController controller) {

        CmsJspLinkMacroResolver macroResolver = new CmsJspLinkMacroResolver(controller.getCmsObject(), null, true);
        return macroResolver.resolveMacros(content);
    }

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


Question:
@param \Riak\Client\Core\Message\Search\PutIndexRequest $getRequest

@return \GuzzleHttp\Message\RequestInterface

private function createHttpRequest(PutIndexRequest $getRequest)
    {
        $request = $this->createIndexRequest('PUT', $getRequest->name);
        $data    = array_filter([
            'n_val'  => $getRequest->nVal,
            'schema' => $getRequest->schema,
        ]);

        $request->setBody(Stream::factory(json_encode($data)));
        $request->setHeader('Content-Type', 'application/json');
        $request->setHeader('Accept', 'application/json');

        return $request;
    }

func addQueryStructs(reqURL *url.URL, queryStructs []interface{}) error {
	urlValues, err := url.ParseQuery(reqURL.RawQuery)
	if err != nil {
		return err
	}
	// encodes query structs into a url.Values map and merges maps
	for _, queryStruct := range queryStructs {
		queryValues, err := goquery.Values(queryStruct)
		if err != nil {
			return err
		}
		for key, values := range queryValues {
			for _, value := range values {
				urlValues.Add(key, value)
			}
		}
	}
	// url.Values format to a sorted "url encoded" string, e.g. "key=val&foo=bar"
	reqURL.RawQuery = urlValues.Encode()
	return nil
}

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


Question:
Calculates path length
@param delta
@param controlPoints
@return

public double pathLength(double delta, Point2D.Double... controlPoints)
    {
        if (controlPoints.length != length)
        {
            throw new IllegalArgumentException("control-points length not "+length);
        }
        double[] cp = convert(controlPoints);
        return pathLength(delta, cp);
    }

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question: Listen for events that affect our ownership of a job

def listen(self, listener):
        ''''''
        for message in listener.listen():
            try:
                data = json.loads(message['data'])
                if data['event'] in ('canceled', 'lock_lost', 'put'):
                    self.kill(data['jid'])
            except:
                logger.exception('Pubsub error')

def _ensure_opened(self):

        if not self._opened:
            self._opened = True
            self._update_servers()

            # Start or restart the events publishing thread.
            if self._publish_tp or self._publish_server:
                self.__events_executor.open()

        # Ensure that the monitors are open.
        for server in itervalues(self._servers):
            server.open()

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


Question:
@param status       success/failure
@param statusString status string
@param behavior     control behavior

@return result with the given input

protected static WorkflowStatusDataResult workflowResult(
            boolean status,
            String statusString,
            ControlBehavior behavior,
            WFSharedContext sharedContext
    )
    {
        return new BaseWorkflowStatusResult(status, statusString, behavior, sharedContext);
    }

public void marshall(DeliveryChannelStatus deliveryChannelStatus, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deliveryChannelStatus.getName(), NAME_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigSnapshotDeliveryInfo(), CONFIGSNAPSHOTDELIVERYINFO_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigHistoryDeliveryInfo(), CONFIGHISTORYDELIVERYINFO_BINDING);
            protocolMarshaller.marshall(deliveryChannelStatus.getConfigStreamDeliveryInfo(), CONFIGSTREAMDELIVERYINFO_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param array              $expression
@param Call               $call
@param CompilationContext $context

@throws CompilerException

@return CompiledExpression|mixed

public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (isset($expression['parameters'])) {
            if (0 != \count($expression['parameters'])) {
                throw new CompilerException("This function doesn't require parameters", $expression);
            }
        }

        /*
         * Process the expected symbol to be returned
         */
        $call->processExpectedReturn($context);

        $symbolVariable = $call->getSymbolVariable(true, $context);
        if ($symbolVariable) {
            if (!$symbolVariable->isVariable()) {
                throw new CompilerException('Returned values by functions can only be assigned to variant variables', $expression);
            }
        }

        if ($call->mustInitSymbolVariable()) {
            $symbolVariable->initVariant($context);
        }

        $context->headersManager->add('kernel/memory');

        $context->codePrinter->output('zephir_create_symbol_table(TSRMLS_C);');
        $context->codePrinter->output('');

        return new CompiledExpression('null', null, $expression);
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
Create request signature

@param HttpRequest $request
@param string      $username
@param string      $timestamp
@param string      $secretKey

@return string

protected function signRequest(HttpRequest $request, $username, $timestamp, $secretKey)
    {
        $message = $username
                 . $timestamp
                 . $this->getRequestMessage($request)
        ;

        return $this->algorithm->sign($message, $secretKey);
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Generate an audible captcha in WAV format and send it to the browser with appropriate headers.
Example:

$img = new Securimage();
$img->outputAudioFile(); // outputs a wav file to the browser
exit;

@param string $format

public function outputAudioFile($format = null)
    {
        set_error_handler(array(&$this, 'errorHandler'));

        if (isset($_SERVER['HTTP_RANGE'])) {
            $range   = true;
            $rangeId = (isset($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) ?
                       'ID' . $_SERVER['HTTP_X_PLAYBACK_SESSION_ID']   :
                       'ID' . md5($_SERVER['REQUEST_URI']);
            $uniq    = $rangeId;
        } else {
            $uniq = md5(uniqid(microtime()));
        }

        try {
            if (!($audio = $this->getAudioData())) {
                // if previously generated audio not found for current captcha
                require_once dirname(__FILE__) . '/WavFile.php';
                $audio = $this->getAudibleCode();

                if (strtolower($format) == 'mp3') {
                    $audio = $this->wavToMp3($audio);
                }

                $this->saveAudioData($audio);
            }
        } catch (Exception $ex) {
            $log_file = rtrim($this->log_path, '/\\ ') . DIRECTORY_SEPARATOR . $this->log_file;

            if (($fp = fopen($log_file, 'a+')) !== false) {
                fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n");
                fclose($fp);
            }

            $audio = $this->audioError();
        }

        if ($this->no_session != true) {
            // close session to make it available to other requests in the event
            // streaming the audio takes sevaral seconds or more
            session_write_close();
        }

        if ($this->canSendHeaders() || $this->send_headers == false) {
            if ($this->send_headers) {
                if ($format == 'mp3') {
                    $ext  = 'mp3';
                    $type = 'audio/mpeg';
                } else {
                    $ext  = 'wav';
                    $type = 'audio/wav';
                }

                header('Accept-Ranges: bytes');
                header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.{$ext}\"");
                header('Cache-Control: no-store, no-cache, must-revalidate');
                header('Expires: Sun, 1 Jan 2000 12:00:00 GMT');
                header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
                header('Content-type: ' . $type);
            }

            $this->rangeDownload($audio);
        } else {
            echo '
'
                .'Failed to generate audio file, content has already been '
                .'output.
This is most likely due to misconfiguration or '
                .'a PHP error was sent to the browser.';
        }

        restore_error_handler();

        if (!$this->no_exit) exit;
    }

public static function _Save ($image, $path, $replace = FALSE)
	{

		// If a file with the same name already exists

		if ($replace === FALSE && parent::_Exists ($path))
		{
//			new \Sonic\Message ('error', 'An image with this filename already exists: ' . $path);
			return FALSE;
		}

		// Switch new path extension to save file

		switch (parent::_getExtension ($path))
		{

			// gif

			case 'gif':

				if (!imagegif ($image, $path))
				{
					return FALSE;
				}

				break;

			// png

			case 'png':

				if (!imagepng ($image, $path))
				{
					return FALSE;
				}

				break;

			// default

			default:

				if (!imagejpeg ($image, $path, 80))
				{
					return FALSE;
				}

				break;

		}

		// Successfully saved, return TRUE

		return TRUE;

	}

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


Question: do diff on words but return character offsets

def word_diff(a,b):
  ''
  return translate_diff(a,rediff(splitpreserve(a),splitpreserve(b)))

func NewEncoder(w io.Writer, s storer.EncodedObjectStorer, useRefDeltas bool) *Encoder {
	h := plumbing.Hasher{
		Hash: sha1.New(),
	}
	mw := io.MultiWriter(w, h)
	ow := newOffsetWriter(mw)
	zw := zlib.NewWriter(mw)
	return &Encoder{
		selector:     newDeltaSelector(s),
		w:            ow,
		zw:           zw,
		hasher:       h,
		useRefDeltas: useRefDeltas,
	}
}

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


Question: Set default rule of parameterize route.

protected function setDefaultRule()
    {
        if (Yii::$app->authManager->getRule(RouteRule::RULE_NAME) === null) {
            Yii::$app->authManager->add(Yii::createObject([
                    'class' => RouteRule::className(),
                    'name' => RouteRule::RULE_NAME]
            ));
        }
    }

public function callStaticRoute($uri)
    {
        $params = array_slice($this->getUrlSegments(), 2);

        return $this->callController([$uri, $params]);
    }

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


Question:
Reserve a dynamips id or raise an error

        :param project_id: UUID of the project
        :param dynamips_id: Asked id

def take_dynamips_id(self, project_id, dynamips_id):

        self._dynamips_ids.setdefault(project_id, set())
        if dynamips_id in self._dynamips_ids[project_id]:
            raise DynamipsError("Dynamips identifier {} is already used by another router".format(dynamips_id))
        self._dynamips_ids[project_id].add(dynamips_id)

func NewModel(cfg config.Wrapper, id protocol.DeviceID, clientName, clientVersion string, ldb *db.Lowlevel, protectedFiles []string) Model {
	m := &model{
		Supervisor: suture.New("model", suture.Spec{
			Log: func(line string) {
				l.Debugln(line)
			},
			PassThroughPanics: true,
		}),
		cfg:                 cfg,
		db:                  ldb,
		finder:              db.NewBlockFinder(ldb),
		progressEmitter:     NewProgressEmitter(cfg),
		id:                  id,
		shortID:             id.Short(),
		cacheIgnoredFiles:   cfg.Options().CacheIgnoredFiles,
		protectedFiles:      protectedFiles,
		clientName:          clientName,
		clientVersion:       clientVersion,
		folderCfgs:          make(map[string]config.FolderConfiguration),
		folderFiles:         make(map[string]*db.FileSet),
		deviceStatRefs:      make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
		folderIgnores:       make(map[string]*ignore.Matcher),
		folderRunners:       make(map[string]service),
		folderRunnerTokens:  make(map[string][]suture.ServiceToken),
		conn:                make(map[protocol.DeviceID]connections.Connection),
		connRequestLimiters: make(map[protocol.DeviceID]*byteSemaphore),
		closed:              make(map[protocol.DeviceID]chan struct{}),
		helloMessages:       make(map[protocol.DeviceID]protocol.HelloResult),
		deviceDownloads:     make(map[protocol.DeviceID]*deviceDownloadState),
		remotePausedFolders: make(map[protocol.DeviceID][]string),
		fmut:                sync.NewRWMutex(),
		pmut:                sync.NewRWMutex(),
	}
	m.Add(m.progressEmitter)
	scanLimiter.setCapacity(cfg.Options().MaxConcurrentScans)
	cfg.Subscribe(m)

	return m
}

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


Question: Get the blocks associated with the file.

Block[] getFileBlocks(String src) {
    waitForReady();
    byte[][] components = INodeDirectory.getPathComponents(src);
    readLock();
    try {
      INode targetNode = rootDir.getNode(components);
      if (targetNode == null)
        return null;
      if(targetNode.isDirectory())
        return null;
      return ((INodeFile)targetNode).getBlocks();
    } finally {
      readUnlock();
    }
  }

public static MBlockPos fromLong(long serialized)
	{
		int j = (int) (serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS);
		int k = (int) (serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS);
		int l = (int) (serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS);
		return new MBlockPos(j, k, l);
	}

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


Question:
Check the existence of the specified <strategy>'s credentials for the user <kuid>.

@param $strategy
@param $kuid
@param array $options
@return mixed

public function hasCredentials($strategy, $kuid, array $options = [])
    {
        $options['httpParams'][':strategy'] = $strategy;
        $options['httpParams'][':kuid'] = $kuid;

        return $this->kuzzle->query($this->buildQueryArgs('hasCredentials'), [], $options)['result'];
    }

public static function current($addAuth = false)
    {
        $current = (string)self::root($addAuth) . (string)self::path();
        return $current ?: null;
    }

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


Question:
@param DocumentManager $dm

@return QueryBuilder

private function prepareQuery(DocumentManager $dm)
    {
        $qb = $dm->createQueryBuilder($this->className);

        $qb->attr('hash')->equals($this->hash);
        $qb->attr('range')->equals($this->range);

        return $qb;
    }

public OQueryDataProvider<K> setContextVariable(String varName, IModel<?> value)
    {
    	model.setContextVariable(varName, value);
        super.detach();
        return this;
    }

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


Question:
Invoke bean's property.

@param object the object
@param propertyName the property name
@return the object

protected Object getBeanProperty(final Object object, String propertyName) {
        Object value;
        try {
            value = BeanUtils.getProperty(object, propertyName);
        } catch (InvocationTargetException e) {
            // ignore
            value = null;
        }
        return value;
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Get available admin interface languages

@return array

protected function _getAvailableLanguages()
    {
        $sDefLang = \OxidEsales\Eshop\Core\Registry::getUtilsServer()->getOxCookie('oxidadminlanguage');
        $sDefLang = $sDefLang ? $sDefLang : $this->_getBrowserLanguage();

        $aLanguages = \OxidEsales\Eshop\Core\Registry::getLang()->getAdminTplLanguageArray();
        foreach ($aLanguages as $oLang) {
            $oLang->selected = ($sDefLang == $oLang->abbr) ? 1 : 0;
        }

        return $aLanguages;
    }

public static function ini()
    {
        $lang = config('lang.default');

        self::$langFolder = dirname(dirname(__DIR__)).'/app/lang/'.$lang;
        self::$langFile = self::$langFolder.'/validator.php';
        if (is_file(self::$langFile)) {
            V::langDir(self::$langFolder);
            V::lang('validator');
        }
    }

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


Question:
Returns the unicode code point at specified index

@param int $index
@return int
@throws InvalidArgumentException
@throws OutOfBoundsException

public function codePointAt(int $index): int
    {
        return mb_ord((string) $this->charAt($index), $this->encoding);
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question: // SetGatewayGroups sets the GatewayGroups field's value.

func (s *ListGatewayGroupsOutput) SetGatewayGroups(v []*GatewayGroupSummary) *ListGatewayGroupsOutput {
	s.GatewayGroups = v
	return s
}

@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.MMT__RG:
				getRG().clear();
				getRG().addAll((Collection<? extends MMTRG>)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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


Question:
Store an item.

@param  string $key
@param  mixed $value
@return bool

@triggers setItem.pre(PreEvent)
@triggers setItem.post(PostEvent)
@triggers setItem.exception(ExceptionEvent)

public function setItem($key, $value)
    {
        if (!$this->getOptions()->getEnabled()) {
            return false;
        }

        $this->normalizeKey($key);

        $result = false;
        try {
            $result = $this->internalSetItem($key, $value);
        } catch (\Exception $e) {
        }

        return $result;
    }

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

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


Question:
Lets find and replace all instances of #AN
    This is a little different, as this depends on whether the next
    word starts with a vowel or a consonant.

    :param _sentence:

def __replace_an(sentence):

    if sentence is not None:
        while sentence.find('#AN') != -1:
            an_index = sentence.find('#AN')

            if an_index > -1:
                an_index += 4

                if sentence[an_index] in 'aeiouAEIOU':
                    sentence = sentence.replace('#AN', str('an'), 1)
                else:
                    sentence = sentence.replace('#AN', str('a'), 1)

            if sentence.find('#AN') == -1:
                return sentence
        return sentence
    else:
        return sentence

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question:
The IP address (IPv4 or IPv6) of the origin server that the request was
sent to.

string server_ip = 13;

public java.lang.String getServerIp() {
    java.lang.Object ref = serverIp_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      serverIp_ = s;
      return s;
    }
  }

def get_nameserver_detail_output_show_nameserver_nameserver_scr(self, **kwargs):

        config = ET.Element("config")
        get_nameserver_detail = ET.Element("get_nameserver_detail")
        config = get_nameserver_detail
        output = ET.SubElement(get_nameserver_detail, "output")
        show_nameserver = ET.SubElement(output, "show-nameserver")
        nameserver_portid_key = ET.SubElement(show_nameserver, "nameserver-portid")
        nameserver_portid_key.text = kwargs.pop('nameserver_portid')
        nameserver_scr = ET.SubElement(show_nameserver, "nameserver-scr")
        nameserver_scr.text = kwargs.pop('nameserver_scr')

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

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


Question: Clear the contents of the data structure

def clear(self):
        """"""
        self.title = None
        self.numbers = np.zeros(0, int)
        self.atom_types = [] # the atom_types in the second column, used to associate ff parameters
        self.charges = [] # ff charges
        self.names = [] # a name that is unique for the molecule composition and connectivity
        self.molecules = np.zeros(0, int) # a counter for each molecule
        self.bonds = np.zeros((0, 2), int)
        self.bends = np.zeros((0, 3), int)
        self.dihedrals = np.zeros((0, 4), int)
        self.impropers = np.zeros((0, 4), int)

        self.name_cache = {}

def reset(self, dim):

        self.dim = dim
        # Reset all child hashes
        for child_hash in self.child_hashes:
            child_hash['hash'].reset(dim)
            child_hash['bucket_keys'] = {}

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


Question:
Dispatches event

@param event
Event to dispatch

public void dispatchEvent(IEvent event) {
        if (event instanceof IRTMPEvent && !closed.get()) {
            switch (event.getType()) {
                case STREAM_CONTROL:
                case STREAM_DATA:
                    // create the event
                    IRTMPEvent rtmpEvent;
                    try {
                        rtmpEvent = (IRTMPEvent) event;
                    } catch (ClassCastException e) {
                        log.error("Class cast exception in event dispatch", e);
                        return;
                    }
                    int eventTime = rtmpEvent.getTimestamp();
                    // verify and / or set source type
                    if (rtmpEvent.getSourceType() != Constants.SOURCE_TYPE_LIVE) {
                        rtmpEvent.setSourceType(Constants.SOURCE_TYPE_LIVE);
                    }
                    /*
                    if (log.isTraceEnabled()) {
                        // If this is first packet save its timestamp; expect it is
                        // absolute? no matter: it's never used!
                        if (firstPacketTime == -1) {
                            firstPacketTime = rtmpEvent.getTimestamp();
                            log.trace(String.format("CBS=@%08x: rtmpEvent=%s creation=%s firstPacketTime=%d", System.identityHashCode(this), rtmpEvent.getClass().getSimpleName(), creationTime, firstPacketTime));
                        } else {
                            log.trace(String.format("CBS=@%08x: rtmpEvent=%s creation=%s firstPacketTime=%d timestamp=%d", System.identityHashCode(this), rtmpEvent.getClass().getSimpleName(), creationTime, firstPacketTime, eventTime));
                        }
                    }
                    */
                    //get the buffer only once per call
                    IoBuffer buf = null;
                    if (rtmpEvent instanceof IStreamData && (buf = ((IStreamData<?>) rtmpEvent).getData()) != null) {
                        bytesReceived += buf.limit();
                    }
                    // get stream codec
                    IStreamCodecInfo codecInfo = getCodecInfo();
                    StreamCodecInfo info = null;
                    if (codecInfo instanceof StreamCodecInfo) {
                        info = (StreamCodecInfo) codecInfo;
                    }
                    //log.trace("Stream codec info: {}", info);
                    if (rtmpEvent instanceof AudioData) {
                        //log.trace("Audio: {}", eventTime);
                        IAudioStreamCodec audioStreamCodec = null;
                        if (checkAudioCodec) {
                            // dont try to read codec info from 0 length audio packets
                            if (buf.limit() > 0) {
                                audioStreamCodec = AudioCodecFactory.getAudioCodec(buf);
                                if (info != null) {
                                    info.setAudioCodec(audioStreamCodec);
                                }
                                checkAudioCodec = false;
                            }
                        } else if (codecInfo != null) {
                            audioStreamCodec = codecInfo.getAudioCodec();
                        }
                        if (audioStreamCodec != null) {
                            audioStreamCodec.addData(buf);
                        }
                        if (info != null) {
                            info.setHasAudio(true);
                        }
                    } else if (rtmpEvent instanceof VideoData) {
                        //log.trace("Video: {}", eventTime);
                        IVideoStreamCodec videoStreamCodec = null;
                        if (checkVideoCodec) {
                            videoStreamCodec = VideoCodecFactory.getVideoCodec(buf);
                            if (info != null) {
                                info.setVideoCodec(videoStreamCodec);
                            }
                            checkVideoCodec = false;
                        } else if (codecInfo != null) {
                            videoStreamCodec = codecInfo.getVideoCodec();
                        }
                        if (videoStreamCodec != null) {
                            videoStreamCodec.addData(buf, eventTime);
                        }
                        if (info != null) {
                            info.setHasVideo(true);
                        }
                    } else if (rtmpEvent instanceof Invoke) {
                        //Invoke invokeEvent = (Invoke) rtmpEvent;
                        //log.debug("Invoke action: {}", invokeEvent.getAction());
                        // event / stream listeners will not be notified of invokes
                        return;
                    } else if (rtmpEvent instanceof Notify) {
                        Notify notifyEvent = (Notify) rtmpEvent;
                        String action = notifyEvent.getAction();
                        //if (log.isDebugEnabled()) {
                        //log.debug("Notify action: {}", action);
                        //}
                        if ("onMetaData".equals(action)) {
                            // store the metadata
                            try {
                                //log.debug("Setting metadata");
                                setMetaData(notifyEvent.duplicate());
                            } catch (Exception e) {
                                log.warn("Metadata could not be duplicated for this stream", e);
                            }
                        }
                    }
                    // update last event time
                    if (eventTime > latestTimeStamp) {
                        latestTimeStamp = eventTime;
                    }
                    // notify event listeners
                    checkSendNotifications(event);
                    // note this timestamp is set in event/body but not in the associated header
                    try {
                        // route to live
                        if (livePipe != null) {
                            // create new RTMP message, initialize it and push through pipe
                            RTMPMessage msg = RTMPMessage.build(rtmpEvent, eventTime);
                            livePipe.pushMessage(msg);
                        } else if (log.isDebugEnabled()) {
                            log.debug("Live pipe was null, message was not pushed");
                        }
                    } catch (IOException err) {
                        stop();
                    }
                    // notify listeners about received packet
                    if (rtmpEvent instanceof IStreamPacket) {
                        for (IStreamListener listener : getStreamListeners()) {
                            try {
                                listener.packetReceived(this, (IStreamPacket) rtmpEvent);
                            } catch (Exception e) {
                                log.error("Error while notifying listener {}", listener, e);
                                if (listener instanceof RecordingListener) {
                                    sendRecordFailedNotify(e.getMessage());
                                }
                            }
                        }
                    }
                    break;
                default:
                    // ignored event
                    //log.debug("Ignoring event: {}", event.getType());
            }
        } else {
            log.debug("Event was of wrong type or stream is closed ({})", closed);
        }
    }

func (s *CreateAssociationBatchRequestEntry) SetParameters(v map[string][]*string) *CreateAssociationBatchRequestEntry {
	s.Parameters = v
	return s
}

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


Question: Returns an unmodifiable collection view of the values from this map.

public final Collection<V> values() {
	return new AbstractCollection<V>() {
	    public Iterator<V> iterator() {
		final Iterator<Map.Entry<K,V>> ite = entryIterator();
		return new Iterator<V>() {
		    public boolean hasNext() { return ite.hasNext(); }
		    public void    remove()  { ite.remove(); }
		    public V       next()    { return ite.next().getValue(); }
		};
	    }
	    public int size() {
		return size;
	    }
	};
    }

public void updateMapping(String virtual, String physical, String archive, String primary, short inspect, boolean toplevel, int listenerMode, int listenerType,
	    boolean readOnly) throws ExpressionException, SecurityException {
	checkWriteAccess();
	_updateMapping(virtual, physical, archive, primary, inspect, toplevel, listenerMode, listenerType, readOnly);
    }

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


Question: Trimming with cutadapt.

def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):

    if all([utils.file_exists(x) for x in out_files]):
        return out_files
    cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
    if len(fastq_files) == 1:
        of = [out_files[0], log_file]
        message = "Trimming %s in single end mode with cutadapt." % (fastq_files[0])
        with file_transaction(data, of) as of_tx:
            of1_tx, log_tx = of_tx
            do.run(cmd.format(**locals()), message)
    else:
        of = out_files + [log_file]
        with file_transaction(data, of) as tx_out_files:
            of1_tx, of2_tx, log_tx = tx_out_files
            tmp_fq1 = utils.append_stem(of1_tx, ".tmp")
            tmp_fq2 = utils.append_stem(of2_tx, ".tmp")
            singles_file = of1_tx + ".single"
            message = "Trimming %s and %s in paired end mode with cutadapt." % (fastq_files[0],
                                                                                fastq_files[1])
            do.run(cmd.format(**locals()), message)
    return out_files

public function transform($response)
    {
        $binding = $this->getBinding($response);

        return $this->adapter->transform($response, $binding->resolveTransformer(), $binding, $this->getRequest());
    }

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


Question:
读取16进制字符串

@param in {@link InputStream}
@param length 长度
@param toLowerCase true 传换成小写格式 ， false 传换成大写格式
@return 16进制字符串
@throws IORuntimeException IO异常

public static String readHex(InputStream in, int length, boolean toLowerCase) throws IORuntimeException {
		return HexUtil.encodeHexStr(readBytes(in, length), toLowerCase);
	}

private Object parsePrimitive(Class<?> objectType, final String serializedObject) {
        Object res = null;

        if (Boolean.class.isAssignableFrom(objectType)) {
            res = Boolean.valueOf(serializedObject);
        } else if (String.class.isAssignableFrom(objectType)) {
            res = serializedObject;
        } else if (Character.class.isAssignableFrom(objectType)) {
            res = Character.valueOf(serializedObject.charAt(0));
        } else if (Byte.class.isAssignableFrom(objectType)) {
            res = Byte.parseByte(serializedObject);
        } else if (Short.class.isAssignableFrom(objectType)) {
            res = Short.parseShort(serializedObject);
        } else if (Integer.class.isAssignableFrom(objectType)) {
            res = Integer.parseInt(serializedObject);
        } else if (Long.class.isAssignableFrom(objectType)) {
            res = Long.parseLong(serializedObject);
        } else if (Float.class.isAssignableFrom(objectType)) {
            res = Float.parseFloat(serializedObject);
        } else if (Double.class.isAssignableFrom(objectType)) {
            res = Double.parseDouble(serializedObject);
        }
        return res;
    }

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


Question:
Returns the block manager.

@return Manager\BlockManager

public function getBlockManager()
    {
        if (null === $this->blockManager) {
            $this->blockManager = new Manager\BlockManager(
                $this->config['default_block_plugin']
            );
            $this->blockManager->setEditor($this);
        }

        return $this->blockManager;
    }

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question:
Returns the correct dataset path for the given name and root directory.

@param root A Path
@param name A String dataset name
@return the correct dataset Path

@edu.umd.cs.findbugs.annotations.SuppressWarnings(
      value="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
      justification="Checked in precondition")
  static Path pathForDataset(Path root, @Nullable String namespace, @Nullable String name) {
    Preconditions.checkNotNull(namespace, "Namespace cannot be null");
    Preconditions.checkNotNull(name, "Dataset name cannot be null");

    // Why replace '.' here? Is this a namespacing hack?
    return new Path(root, new Path(namespace, name.replace('.', Path.SEPARATOR_CHAR)));
  }

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question:
Fills an RpbYokozunaIndex message with the appropriate data.

        :param index: a yz index message
        :type index: riak.pb.riak_yokozuna_pb2.RpbYokozunaIndex
        :rtype dict

def decode_search_index(self, index):

        result = {}
        result['name'] = bytes_to_str(index.name)
        if index.HasField('schema'):
            result['schema'] = bytes_to_str(index.schema)
        if index.HasField('n_val'):
            result['n_val'] = index.n_val
        return result

def _validate_id_types(self):
        ''''''

        for sequences in [self.uniparc_sequences, self.fasta_sequences, self.seqres_sequences, self.rosetta_sequences]:
            for chain_id, sequence in sequences.iteritems():
                sequence_id_types = set(map(type, sequence.ids()))
                if sequence_id_types:
                    assert(len(sequence_id_types) == 1)
                    assert(sequence_id_types.pop() == types.IntType)

        for chain_id, sequence in self.atom_sequences.iteritems():
            sequence_id_types = set(map(type, sequence.ids()))
            assert(len(sequence_id_types) == 1)
            sequence_id_type = sequence_id_types.pop()
            assert(sequence_id_type == types.StringType or sequence_id_type == types.UnicodeType)

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


Question:
Get cache file name for this controller, action and set of params

@param Controller $controller
@param InlineAction $action

private function getFilePath($controller = false, $action = false){
		$controller = $controller ?: $this->_controller;
		$action = $action ?: $this->_action;

		$cacheFileName = $this->generateFileName($controller, $action);

		$path = $this->getAssetsUrl() . DIRECTORY_SEPARATOR . $this->folder . DIRECTORY_SEPARATOR . $cacheFileName;

		return $path;
	}

public static void configCacheSettings(String imFileDir, String docDir, String fileDir, String queryResultDir,
         String commandDir, String analyticsDir, SystemSetting setting) {
    importantFileDir = imFileDir;
    if (!importantFileDir.endsWith("/")) {
      importantFileDir += "/";
    }

    documentDir = docDir;
    if (!documentDir.endsWith("/")) {
      documentDir += "/";
    }

    fileCacheDir = fileDir;
    if (!fileCacheDir.endsWith("/")) {
      fileCacheDir += "/";
    }

    queryResultCacheDir = queryResultDir;
    if (!queryResultCacheDir.endsWith("/")) {
      queryResultCacheDir += "/";
    }

    commandCacheDir = commandDir;
    if (!commandCacheDir.endsWith("/")) {
      commandCacheDir += "/";
    }

    analyticsCacheDir = analyticsDir;
    if (!analyticsCacheDir.endsWith("/")) {
      analyticsCacheDir += "/";
    }

    makeSureCacheDirWorkable();
    defaultSetting = setting;
  }

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


Question:
getWebsiteMapper

@return websiteMapper

public function getWebsiteMapper()
    {
        if (null === $this->websiteMapper) {
            $this->websiteMapper = $this->serviceLocator->get('playgroundcore_website_mapper');
        }

        return $this->websiteMapper;
    }

def spider_url(zap_helper, url, context_name, user_name):
    """"""
    console.info('Running spider...')
    with helpers.zap_error_handler():
        zap_helper.run_spider(url, context_name, user_name)

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


Question: Use this API to fetch all the nsacl6 resources that are configured on netscaler.

public static nsacl6[] get(nitro_service service) throws Exception{
		nsacl6 obj = new nsacl6();
		nsacl6[] response = (nsacl6[])obj.get_resources(service);
		return response;
	}

def get_scaling_relation_tuple(msr_dict):
    '''

    '''

    # Convert MSR string name to openquake.hazardlib.scalerel object
    for iloc, value in enumerate(msr_dict['Value']):
        if not value in SCALE_REL_MAP.keys():
            raise ValueError('Scaling relation %s not supported!' % value)
        msr_dict['Value'][iloc] = SCALE_REL_MAP[value]()
    return weight_list_to_tuple(msr_dict,
                                'Magnitude Scaling Relation')

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


Question: Convert Image into raw dictionary data.

def to_dict(self):
        """"""
        if not self.url:
            return None
        return {
            'url': self.url,
            'width': self.width,
            'height': self.height
        }

@Override
    public boolean canImport(String mediaType) {
        return (MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.containsKey(mediaType) ||
                this.serviceTransformationEngine.canTransform(mediaType));
    }

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


Question: // hasTime returns true if a contains a non-nil time.

func hasTime(a []*time.Time) bool {
	for _, t := range a {
		if t != nil {
			return true
		}
	}
	return false
}

def _parseIsComment(self):

        self._iscomment = (
            self._element.startswith("<!--") and self._element.endswith("-->")
        )

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


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


Question: Default overview action

public function indexAction()
    {
        if ($this->checkForAnswersOnLoad) {
            $this->loader->getTracker()->processCompletedTokens(
                    null,
                    $this->currentUser->getUserId(),
                    $this->currentUser->getCurrentOrganizationId(),
                    true
                    );
        }

        parent::indexAction();
    }

public void setToDefault() {
		setToDefault(COLOR);
		setToDefault(CHARACTER);
		setToDefault(PARAGRAPH);
		setToDefault(SECTION);
		setToDefault(DOCUMENT);
	}

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


Question:
method to return hierarchical siblings of this resource.

		Args:
			as_resources (bool): if True, opens each as appropriate resource type instead of return URI only

		Returns:
			(list): list of resources

def siblings(self, as_resources=False):

		'''

		'''

		siblings = set()

		# loop through parents and get children
		for parent in self.parents(as_resources=True):
			for sibling in parent.children(as_resources=as_resources):
				siblings.add(sibling)

		# remove self
		if as_resources:
			siblings.remove(self)
		if not as_resources:
			siblings.remove(self.uri)

		return list(siblings)

def check_url(url_data, logger):
    """"""
    if url_data.has_result:
        logger.log_url(url_data.to_wire())
    else:
        cache = url_data.aggregate.result_cache
        key = url_data.cache_url
        result = cache.get_result(key)
        if result is None:
            # check
            check_start = time.time()
            try:
                url_data.check()
                do_parse = url_data.check_content()
                url_data.checktime = time.time() - check_start
                # Add result to cache
                result = url_data.to_wire()
                cache.add_result(key, result)
                for alias in url_data.aliases:
                    # redirect aliases
                    cache.add_result(alias, result)
                # parse content recursively
                # XXX this could add new warnings which should be cached.
                if do_parse:
                    parser.parse_url(url_data)
            finally:
                # close/release possible open connection
                url_data.close_connection()
        else:
            # copy data from cache and adjust it
            result = copy.copy(result)
            result.parent_url = url_data.parent_url
            result.base_ref = url_data.base_ref or u""
            result.base_url = url_data.base_url or u""
            result.line = url_data.line
            result.column = url_data.column
            result.level = url_data.recursion_level
            result.name = url_data.name
        logger.log_url(result)

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


Question:
/*
(non-Javadoc)

@see org.restcomm.protocols.ss7.tcap.api.tc.dialog.Dialog#sendComponent(org
.mobicents.protocols.ss7.tcap.api.tc.component.ComponentRequest)

public void sendComponent(Component componentRequest) throws TCAPSendException {

        if (this.previewMode)
            return;

        if (this.provider.getStack().getStatisticsEnabled()) {
            switch (componentRequest.getType()) {
                case InvokeNotLast:
                    this.provider.getStack().getCounterProviderImpl().updateInvokeNotLastSentCount(this,
                            (Invoke) componentRequest);

                    Invoke inv = (Invoke) componentRequest;
                    OperationCodeImpl oc = (OperationCodeImpl) inv.getOperationCode();
                    if (oc != null) {
                        this.provider.getStack().getCounterProviderImpl()
                                .updateOutgoingInvokesPerOperationCode(oc.getStringValue());
                    }
                    break;
                case InvokeLast:
                    this.provider.getStack().getCounterProviderImpl().updateInvokeLastSentCount(this,
                            (Invoke) componentRequest);

                    inv = (Invoke) componentRequest;
                    oc = (OperationCodeImpl) inv.getOperationCode();
                    if (oc != null) {
                        this.provider.getStack().getCounterProviderImpl()
                                .updateOutgoingInvokesPerOperationCode(oc.getStringValue());
                    }
                    break;
                case ReturnResultNotLast:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultNotLastSentCount(this);
                    break;
                case ReturnResultLast:
                    this.provider.getStack().getCounterProviderImpl().updateReturnResultLastSentCount(this);
                    break;
                case ReturnError:
                    this.provider.getStack().getCounterProviderImpl().updateReturnErrorSentCount(this);

                    ReturnError re = (ReturnError) componentRequest;
                    ErrorCodeImpl ec = (ErrorCodeImpl) re.getErrorCode();
                    if (ec != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingErrorsPerErrorCode(ec.getStringValue());
                    }
                    break;
                case Reject:
                    this.provider.getStack().getCounterProviderImpl().updateRejectSentCount(this);

                    Reject rej = (Reject) componentRequest;
                    RejectProblem prob = (RejectProblem) rej.getProblem();
                    if (prob != null) {
                        this.provider.getStack().getCounterProviderImpl().updateOutgoingRejectPerProblem(prob.toString());
                    }
                    break;
            }
        }

        try {
            this.dialogLock.lock();
            if (componentRequest.getType() == ComponentType.InvokeNotLast
                    || componentRequest.getType() == ComponentType.InvokeLast) {
                InvokeImpl invoke = (InvokeImpl) componentRequest;

                // check if its taken!
                int invokeIndex = getIndexFromInvokeId(invoke.getInvokeId());
                if (this.operationsSent[invokeIndex] != null) {
                    throw new TCAPSendException("There is already operation with such invoke id!");
                }

                invoke.setState(OperationState.Pending);
                invoke.setDialog(this);

                // if the Invoke timeout value has not be reset by TCAP-User
                // for this invocation we are setting it to the the TCAP stack
                // default value
                if (invoke.getTimeout() == TCAPStackImpl._EMPTY_INVOKE_TIMEOUT)
                    invoke.setTimeout(this.provider.getStack().getInvokeTimeout());
            } else {
                if (componentRequest.getType() != ComponentType.ReturnResultNotLast) {
                    // we are sending a response and removing invokeId from
                    // incomingInvokeList
                    this.removeIncomingInvokeId(componentRequest.getCorrelationId());
                }
            }
            this.scheduledComponentList.add(componentRequest);
        } finally {
            this.dialogLock.unlock();
        }
    }

public SendRequest getSendRequest() {
        Transaction tx = new Transaction(params);
        for (Protos.Output output : paymentDetails.getOutputsList())
            tx.addOutput(new TransactionOutput(params, tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray()));
        return SendRequest.forTx(tx).fromPaymentDetails(paymentDetails);
    }

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


Question:
Return the first truthy element of the target array.
If none of them is truthy, return a defaultResult.

@param  mixed $defaultResult
@return mixed

public function find($defaultResult = null)
    {
        foreach ($this->target as $value) {
            if ($value) {
                return $value;
            }
        }

        return $defaultResult;
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question: // Validate the data against the description of the parameter

func (p *ParamValidator) Validate(data interface{}) *Result {
	result := new(Result)
	tpe := reflect.TypeOf(data)
	kind := tpe.Kind()

	// TODO: validate type
	for _, validator := range p.validators {
		if validator.Applies(p.param, kind) {
			if err := validator.Validate(data); err != nil {
				result.Merge(err)
				if err.HasErrors() {
					return result
				}
			}
		}
	}
	return nil
}

private function parseRequiredValue($name, array $input)
    {
        if (isset($input[$name])) {
            return $input[$name];
        }

        throw new Exception(sprintf("'%s' is required.", $name));
    }

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


Question: Set the primary key.

protected function setPrimaryKey()
    {
        // making default primary key as id
        $primaryKey = isset($this->primaryKey) && is_null($this->primaryKey) ?
            static::$defaultPrimaryKey :
            $this->primaryKey;

        $this->primaryKey = $primaryKey;
    }

public function changePrimaryKey($columns)
    {
        $this->actions->addAction(new ChangePrimaryKey($this->table, $columns));

        return $this;
    }

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


Question: Returns the number of the machine which key gets sent to.

def get_machine(self, key):

        h = self.hash(key)

        # edge case where we cycle past hash value of 1 and back to 0.
        if h > self.hash_tuples[-1][2]:
            return self.hash_tuples[0][0]

        hash_values = map(lambda x: x[2], self.hash_tuples)
        index = bisect.bisect_left(hash_values, h)
        return self.hash_tuples[index][0]

func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
	bc.addBadBlock(block)

	var receiptString string
	for i, receipt := range receipts {
		receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
			i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
			receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
	}
	log.Error(fmt.Sprintf(`
########## BAD BLOCK #########
Chain config: %v

Number: %v
Hash: 0x%x
%v

Error: %v
##############################
`, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
}

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


Question:
Prefixes a table if it is not already prefixed
@param string $table
@return string

public function prefixTable(string $table): string
	{
		// Add the prefix to the table name
		// before quoting it
		if ( ! empty($this->tablePrefix))
		{
			// Split identifier by period, will split into:
			// database.schema.table OR
			// schema.table OR
			// database.table OR
			// table
			$identifiers = explode('.', $table);
			$segments = count($identifiers);

			// Quote the last item, and add the database prefix
			$identifiers[$segments - 1] = $this->_prefix(end($identifiers));

			// Rejoin
			$table = implode('.', $identifiers);
		}

		return $table;
	}

public function init(): void
    {
        parent::init();

        foreach (['useTablePrefix', 'showOnly', 'generalSchema', 'fixHistory'] as $property) {
            if ($this->$property !== true) {
                if ($this->$property === 'true' || $this->$property === 1) {
                    $this->$property = true;
                }

                $this->$property = (bool)$this->$property;
            }
        }
    }

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


Question: // BytesVar parses numeric byte units. eg. 1.5KB

func (p *parserMixin) BytesVar(target *units.Base2Bytes) {
	p.SetValue(newBytesValue(target))
}

public function sizedByteArray()
    {
        $start = $this->space;
        $length = $this->bb->capacity() - $this->space;

        $result = str_repeat("\0", $length);
        $this->bb->setPosition($start);
        $this->bb->getX($result);

        return $result;
    }

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


Question: Replace an object within the composite.

public boolean replace(Object oldObj, Object newObj)
    {
        if (nest != null)
        {
            return nest.replace(oldObj, newObj);
        }
        else
        {
            int sz = elements.size();
            for (int i = 0; i < sz; i++)
            {
                if (elements.get(i) == oldObj)
                {
                    elements.set(i,newObj);
                    return true;
                }
            }
        }

        return false;
    }

function (oldData) {
    var data = this.data;
    if (!this.shader || data.shader !== oldData.shader) {
      this.updateShader(data.shader);
    }
    this.shader.update(this.data);
    this.updateMaterial(oldData);
  }

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


Question: calls push() on success

function commit() {
            _spork('git', ['commit', '-m', 'Bumping to version ' + require(pkg).version], push,
                _.partial(fulfill, 'Could not commit \'' + chalk.cyan('package.json') + '\''));
          }

function lpushx(key, value, req) {
  var val = this.getKey(key, req);
  if(val === undefined) {
    return 0;
  }
  return val.lpush([value]);
}

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


Question: // SetArn sets the Arn field's value.

func (s *CreateConfigurationResponse) SetArn(v string) *CreateConfigurationResponse {
	s.Arn = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question: // Collect implements the prometheus.Collector interface.

func (n NodeCollector) Collect(ch chan<- prometheus.Metric) {
	wg := sync.WaitGroup{}
	wg.Add(len(n.collectors))
	for name, c := range n.collectors {
		go func(name string, c collector.Collector) {
			execute(name, c, ch)
			wg.Done()
		}(name, c)
	}
	wg.Wait()
	scrapeDurations.Collect(ch)
}

protected function resolveClass(?ContainerInterface $container = null, string $class)
    {
        if ($container instanceof ContainerInterface && $container->has($class)) {
            return $container->get($class);
        }

        return new $class();
    }

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


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

public void setGuardCondition(Condition newGuardCondition) {
		if (newGuardCondition != guardCondition) {
			NotificationChain msgs = null;
			if (guardCondition != null)
				msgs = ((InternalEObject)guardCondition).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - XtextPackage.GROUP__GUARD_CONDITION, null, msgs);
			if (newGuardCondition != null)
				msgs = ((InternalEObject)newGuardCondition).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - XtextPackage.GROUP__GUARD_CONDITION, null, msgs);
			msgs = basicSetGuardCondition(newGuardCondition, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, XtextPackage.GROUP__GUARD_CONDITION, newGuardCondition, newGuardCondition));
	}

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:
Execute aggregate function and return value

@param string $function
@return mixed

function aggregate( $function ) {

        if ( $this->parent_ ) {

            throw new \LogicException( 'Cannot aggregate referenced result' );

        }

        $statement = $this->db->select( $this->table, array(
            'expr' => $function,
            'where' => $this->where,
            'orderBy' => $this->orderBy,
            'limitCount' => $this->limitCount,
            'limitOffset' => $this->limitOffset,
            'params' => $this->whereParams
        ) );

        foreach ( $statement->fetch() as $return ) {

            return $return;

        }

    }

func (s *DescribeDBParameterGroupsOutput) SetDBParameterGroups(v []*DBParameterGroup) *DescribeDBParameterGroupsOutput {
	s.DBParameterGroups = v
	return s
}

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


Question:
Worker thread for disk
        :param Downloader self: this

def _worker_thread_disk(self):
        # type: (Downloader) -> None

        while not self.termination_check:
            try:
                dd, offsets, data = self._disk_queue.get(
                    block=False, timeout=0.1)
            except queue.Empty:
                continue
            try:
                self._process_data(dd, offsets, data)
            except Exception as e:
                with self._transfer_lock:
                    self._exceptions.append(e)

private ProcessingItem createPi(Processor processor, int parallelism) {
        ProcessingItem pi = this.componentFactory.createPi(processor, parallelism);
        this.topology.addProcessingItem(pi, parallelism);
        return pi;
    }

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


Question: // WithEndpointDiscovery will set whether or not to use endpoint discovery.

func (c *Config) WithEndpointDiscovery(t bool) *Config {
	c.EnableEndpointDiscovery = &t
	return c
}

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.GSCH__HX:
				return HX_EDEFAULT == null ? hx != null : !HX_EDEFAULT.equals(hx);
			case AfplibPackage.GSCH__HY:
				return HY_EDEFAULT == null ? hy != null : !HY_EDEFAULT.equals(hy);
		}
		return super.eIsSet(featureID);
	}

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


Question:
Division in polar notation.

@param a Complex number in polar notation. Not modified.
@param b Complex number in polar notation. Not modified.
@param result Storage for output.

public static void multiply(ComplexPolar_F64 a, ComplexPolar_F64 b, ComplexPolar_F64 result)
    {
        result.r = a.r*b.r;
        result.theta = a.theta + b.theta;
    }

func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
	input := i.Filters
	result := map[string]string{}
	pairings := map[string]interface{}{
		"filter[status]":           input.Status,
		"filter[rule][accuracy]":   input.Accuracy,
		"filter[rule][maturity]":   input.Maturity,
		"filter[rule][message]":    input.Message,
		"filter[rule][revision]":   input.Revision,
		"filter[rule][rule_id]":    input.RuleID,
		"filter[rule][tags]":       input.TagID,
		"filter[rule][tags][name]": input.TagName,
		"filter[rule][version]":    input.Version,
		"include":                  input.Tags,
		"page[size]":               input.MaxResults,
		"page[number]":             input.Page, // starts at 1, not 0
	}
	// NOTE: This setup means we will not be able to send the zero value
	// of any of these filters. It doesn't appear we would need to at present.
	for key, value := range pairings {
		switch t := reflect.TypeOf(value).String(); t {
		case "string":
			if value != "" {
				result[key] = value.(string)
			}
		case "int":
			if value != 0 {
				result[key] = strconv.Itoa(value.(int))
			}
		case "[]int":
			// convert ints to strings
			toStrings := []string{}
			values := value.([]int)
			for _, i := range values {
				toStrings = append(toStrings, strconv.Itoa(i))
			}
			// concat strings
			if len(values) > 0 {
				result[key] = strings.Join(toStrings, ",")
			}
		}
	}
	return result
}

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


Question:
:return: a Point corresponding to the absolute position of the center
        of the well relative to the deck (with the front-left corner of slot 1
        as (0,0,0))

def center(self) -> Location:

        top = self.top()
        center_z = top.point.z - (self._depth / 2.0)
        return Location(Point(x=top.point.x, y=top.point.y, z=center_z), self)

def search_db(self, search):

        def search_callback(_, address, balance):
            """

            :param _:
            :param address: The address of the contract with the code in search
            :param balance: The balance of the corresponding contract
            """
            print("Address: " + address + ", balance: " + str(balance))

        try:
            self.leveldb.search(search, search_callback)

        except SyntaxError:
            raise CriticalError("Syntax error in search expression.")

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


Question:
// StreamEvents about job state changes to ch. id may be "all" or a single
// job ID.

func (c *Host) StreamEvents(id string, ch chan *host.Event) (stream.Stream, error) {
	r := fmt.Sprintf("/host/jobs/%s", id)
	if id == "all" {
		r = "/host/jobs"
	}
	return c.c.ResumingStream("GET", r, ch)
}

def __batch_update(self, train_events, test_events, n_epoch):

        for epoch in range(n_epoch):
            # SGD requires us to shuffle events in each iteration
            # * if n_epoch == 1
            #   => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
            if n_epoch != 1:
                np.random.shuffle(train_events)

            # train
            for e in train_events:
                self.rec.update(e, batch_train=True)

            # test
            MPR = self.__batch_evaluate(test_events)
            if self.debug:
                logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))

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


Question:
Operation updateMemberDetailsAsync

Modify member details

@param  string $member_id (required)
@param  \faxplus\model\MemberDetail $payload_member_detail (required)

@throws \InvalidArgumentException
@return \GuzzleHttp\Promise\PromiseInterface

public function updateMemberDetailsAsync($member_id, $payload_member_detail)
    {
        return $this->updateMemberDetailsAsyncWithHttpInfo($member_id, $payload_member_detail)
            ->then(
                function ($response) {
                    return $response[0];
                }
            );
    }

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Add infos for front : urls of thumbnails and html value of media.

@param MediaInterface $media

@return MediaInterface

private function addInfosForFront(MediaInterface $media)
    {
        $mediaManager = $this->getMediaManager();

        $media->setUrls(array(
            'original' => $mediaManager->getUrl($media),
            '500x400' => $mediaManager->getUrl($media, '500x400'),
            '78x44_focus' => $mediaManager->getUrl($media, '78x44_focus'),
        ));

        $media->setHtml(
            $mediaManager->getHtml($media)
        );

        return $media;
    }

public function bootstrapModel($model)
    {
        if (! property_exists($model, 'rules')) {
            throw new ModelSanityException('Missing rules property for model '.get_class($model));
        }

        if (! $model instanceof AdminModel) {
            throw new ModelSanityException('Model '.get_class($model).' must be instanceof '.AdminModel::class);
        }

        $imageFields = $model->getImageFields();

        if (! is_array($imageFields)) {
            throw new ModelSanityException('No Image fields defined in config for model '.get_class($model));
        }

        // Check for fields collisions
        foreach ($imageFields as $imageFieldName => $imageField) {
            $imageMetaFields = $model->getImageMetaFields($imageFieldName);
            foreach ($imageMetaFields as $metaFieldName => $options) {
            }
        }

        $model->setRetinaFactor(config('ignicms.images.retina_factor'));

        foreach ($imageFields as $fieldName => $field) {
            $model->prepareImageRules($model, 'rules', $fieldName, $field);
        }
    }

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


Question:
Gets parameter by name

@param $name
@throws Exception\ParameterNotFoundException
@return mixed

public function getParameter($name)
	{
		$chunks = explode('.', $name);

		$name = $chunks[0] .
			(isset($chunks[1]) ? '.' . $chunks[1] : '');

		if (!isset($this->parameters[$name])) {
			throw new ReferenceException(sprintf('Parameter "%s" is not defined in the container', $name));
		}

		$value = $this->parameters[$name];

		if (count($chunks) > 2) {
			$path = array_slice($chunks, 2);

			while ($key = array_shift($path)) {
				if (!array_key_exists($key, $value)) {
					throw new ReferenceException(sprintf('Lost at sub-key "%s" for parameter "%s"', $key, $name));
				}

				$value = $value[$key];
			}
		}

		return $value;
	}

public static MultiMatcher<MethodTree, VariableTree> methodHasParameters(
      MatchType matchType, Matcher<VariableTree> parameterMatcher) {
    return new MethodHasParameters(matchType, parameterMatcher);
  }

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


Question:
Commit all written data to the physical disk

@throws IOException any io exception

public void flush() throws IOException {
        checkMutable();
        long startTime = System.currentTimeMillis();
        channel.force(true);
        long elapsedTime = System.currentTimeMillis() - startTime;
        LogFlushStats.recordFlushRequest(elapsedTime);
        logger.debug("flush time " + elapsedTime);
        setHighWaterMark.set(getSizeInBytes());
        logger.debug("flush high water mark:" + highWaterMark());
    }

public static TextProtocolBackendHandler newInstance(final String sql, final BackendConnection backendConnection) {
        if (sql.toUpperCase().startsWith(ShardingCTLBackendHandlerFactory.SCTL)) {
            return ShardingCTLBackendHandlerFactory.newInstance(sql, backendConnection);
        }
        // TODO use sql parser engine instead of string compare
        Optional<TransactionOperationType> transactionOperationType = TransactionOperationType.getOperationType(sql.toUpperCase());
        if (transactionOperationType.isPresent()) {
            return new TransactionBackendHandler(transactionOperationType.get(), backendConnection);
        }
        if (sql.toUpperCase().contains(SET_AUTOCOMMIT_1)) {
            return backendConnection.getStateHandler().isInTransaction() ? new TransactionBackendHandler(TransactionOperationType.COMMIT, backendConnection) : new SkipBackendHandler();
        }
        SQLStatement sqlStatement = new SQLJudgeEngine(sql).judge();
        return SQLType.DAL == sqlStatement.getType() ? createDALBackendHandler(sqlStatement, sql, backendConnection) : new QueryBackendHandler(sql, backendConnection);
    }

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


Question: // serviced service clone --config config { SERVICEID | SERVICENAME | [POOL/]...PARENTNAME.../SERVICENAME }

func (c *ServicedCli) cmdServiceClone(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "clone")
		c.exit(1)
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error searching for service: %s", err)
		c.exit(1)
		return
	}
	serviceID := svc.ID

	if copiedSvc, err := c.driver.CloneService(serviceID, ctx.String("suffix")); err != nil {
		fmt.Fprintf(os.Stderr, "%s: %s\n", serviceID, err)
		c.exit(1)
	} else if copiedSvc == nil {
		fmt.Fprintln(os.Stderr, "received nil service definition")
		c.exit(1)
	} else {
		fmt.Println(copiedSvc.ID)
	}
	return
}

func (in *ReplicationControllerConfiguration) DeepCopy() *ReplicationControllerConfiguration {
	if in == nil {
		return nil
	}
	out := new(ReplicationControllerConfiguration)
	in.DeepCopyInto(out)
	return out
}

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


Question:
@param  string|null   $namespace
@param  array<string> $aliased_classes
@param  string|null   $this_class
@param  bool          $use_phpdoc_format

@return string

public function toNamespacedString($namespace, array $aliased_classes, $this_class, $use_phpdoc_format)
    {
        if ($this->fq_classlike_name === 'static') {
            return 'static::' . $this->const_name;
        }

        if ($this->fq_classlike_name === $this_class) {
            return 'self::' . $this->const_name;
        }

        if ($namespace && stripos($this->fq_classlike_name, $namespace . '\\') === 0) {
            return preg_replace(
                '/^' . preg_quote($namespace . '\\') . '/i',
                '',
                $this->fq_classlike_name
            ) . '::' . $this->const_name;
        }

        if (!$namespace && stripos($this->fq_classlike_name, '\\') === false) {
            return $this->fq_classlike_name . '::' . $this->const_name;
        }

        if (isset($aliased_classes[strtolower($this->fq_classlike_name)])) {
            return $aliased_classes[strtolower($this->fq_classlike_name)] . '::' . $this->const_name;
        }

        return '\\' . $this->fq_classlike_name . '::' . $this->const_name;
    }

protected function computeInPathParameters()
	{
		foreach ($this->openApiFileContent['paths'] as $path => $operations) {
			foreach ($operations as $httpMethod => $operation) {
				if (isset($operation['tags'])) {
					$extractedTags = [];
					foreach ($operation['tags'] as $tag) {
						$split = explode(':', $tag);
						if (count($split) == 2) {
							switch ($split[0]) {
								case 'Manager' :
									if (!isset($extractedTags['Managers'])) {
										$extractedTags['Managers'] = [];
									}
									$extractedTags['Managers'][] = $split[1];
									break;
								case 'Resource' :
									if (!isset($extractedTags['Resources'])) {
										$extractedTags['Resources'] = [];
									}
									$extractedTags['Resources'][] = $split[1];
									break;
							}
						}
					}

					foreach ($extractedTags as $tagType => $typeTags) {
						foreach ($typeTags as $typeTag) {
							switch ($tagType) {
								case 'Managers' :
									$this->prepareManager($typeTag);
									$this->managersData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation);
									break;

								case 'Resources' :
									$this->prepareResource($typeTag);
									$this->resourcesData[ucfirst($typeTag)]['routes'][$operation['operationId']]['inPathParameters'] = $this->getRouteOperationInPathParameters($operation, ucfirst($typeTag), $this->resourcesData[ucfirst($typeTag)]['properties']);
									break;
							}
						}
					}
				}
			}
		}
	}

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


Question: // Route creates a new Route using the RouteBuilder and add to the ordered list of Routes.

func (w *WebService) Route(builder *RouteBuilder) *WebService {
	w.routesLock.Lock()
	defer w.routesLock.Unlock()
	builder.copyDefaults(w.produces, w.consumes)
	w.routes = append(w.routes, builder.Build())
	return w
}

protected function getOptions()
    {
        return [
            [
                'path',
                'p',
                InputOption::VALUE_OPTIONAL,
                sprintf('Path to the javscript assets directory (default: "%s")', $this->config->get('laroute.path'))
            ],
            [
                'filename',
                'f',
                InputOption::VALUE_OPTIONAL,
                sprintf('Filename of the javascript file (default: "%s")', $this->config->get('laroute.filename'))
            ],
            [
                'namespace',
                null,
                InputOption::VALUE_OPTIONAL, sprintf('Javascript namespace for the functions (think _.js) (default: "%s")', $this->config->get('laroute.namespace'))
            ],
            [
                'prefix',
                'pr',
                InputOption::VALUE_OPTIONAL, sprintf('Prefix for the generated URLs (default: "%s")', $this->config->get('laroute.prefix'))
            ],
        ];
    }

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


Question:
一次性读入纯文本

@param path
@return

public static String readTxt(String path)
    {
        if (path == null) return null;
        try
        {
            InputStream in = IOAdapter == null ? new FileInputStream(path) :
                    IOAdapter.open(path);
            byte[] fileContent = new byte[in.available()];
            int read = readBytesFromOtherInputStream(in, fileContent);
            in.close();
            // 处理 UTF-8 BOM
            if (read >= 3 && fileContent[0] == -17 && fileContent[1] == -69 && fileContent[2] == -65)
                return new String(fileContent, 3, fileContent.length - 3, Charset.forName("UTF-8"));
            return new String(fileContent, Charset.forName("UTF-8"));
        }
        catch (FileNotFoundException e)
        {
            logger.warning("找不到" + path + e);
            return null;
        }
        catch (IOException e)
        {
            logger.warning("读取" + path + "发生IO异常" + e);
            return null;
        }
    }

def allpathsX(args):

    p = OptionParser(allpathsX.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    folder, tag = args
    tag = tag.split(",")
    for p, pf in iter_project(folder):
        assemble_pairs(p, pf, tag)

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


Question:
Create lock file filled with :attr:`LOCK_FILE_CONTENT
    <ftp.settings.LOCK_FILE_CONTENT>`.

    Args:
        path (str): Path to the lock file. Made from users home directory and
                    :attr:`LOCK_FILENAME <ftp.settings.LOCK_FILENAME>`.

def create_lock_file(path):

    with open(path, "w") as f:
        f.write(settings.LOCK_FILE_CONTENT)

    passwd_reader.set_permissions(path, gid=settings.PROFTPD_USERS_GID)

def put_stream(self, rel_path, metadata=None, cb=None):

        from io import IOBase

        if not isinstance(rel_path, basestring):
            rel_path = rel_path.cache_key

        repo_path = os.path.join(self.cache_dir, rel_path.strip("/"))

        if not os.path.isdir(os.path.dirname(repo_path)):
            os.makedirs(os.path.dirname(repo_path))

        if os.path.exists(repo_path):
            os.remove(repo_path)

        sink = open(repo_path, 'wb')

        upstream = self.upstream

        class flo(IOBase):

            '''This File-Like-Object class ensures that the file is also
            sent to the upstream after it is stored in the FSCache. '''

            def __init__(self, sink, upstream, repo_path, rel_path):

                self._sink = sink
                self._upstream = upstream
                self._repo_path = repo_path
                self._rel_path = rel_path

            @property
            def rel_path(self):
                return self._rel_path

            def write(self, str_):
                self._sink.write(str_)

            def close(self):
                if not self._sink.closed:
                    # print "Closing put_stream.flo {}
                    # is_closed={}!".format(self._repo_path, self._sink.closed)

                    self._sink.close()

                    if self._upstream and not self._upstream.readonly and not self._upstream.usreadonly:
                        self._upstream.put(
                            self._repo_path,
                            self._rel_path,
                            metadata=metadata)

            def __enter__(self): # Can be used as a context!
                return self

            def __exit__(self, type_, value, traceback):
                if type_:
                    return False

                self.close()

        self.put_metadata(rel_path, metadata)

        return flo(sink, upstream, repo_path, rel_path)

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


Question:
Return the item view type used by the adapter to implement recycle mechanism.

@param content to be rendered.
@return an integer that represents the renderer inside the adapter.

int getItemViewType(T content) {
    Class prototypeClass = getPrototypeClass(content);
    validatePrototypeClass(prototypeClass);
    return getItemViewType(prototypeClass);
  }

func (s *Service) Layouts(w http.ResponseWriter, r *http.Request) {
	// Construct a filter sieve for both applications and measurements
	filtered := map[string]bool{}
	for _, a := range r.URL.Query()["app"] {
		filtered[a] = true
	}

	for _, m := range r.URL.Query()["measurement"] {
		filtered[m] = true
	}

	ctx := r.Context()
	layouts, err := s.Store.Layouts(ctx).All(ctx)
	if err != nil {
		Error(w, http.StatusInternalServerError, "Error loading layouts", s.Logger)
		return
	}

	filter := func(layout *chronograf.Layout) bool {
		// If the length of the filter is zero then all values are acceptable.
		if len(filtered) == 0 {
			return true
		}

		// If filter contains either measurement or application
		return filtered[layout.Measurement] || filtered[layout.Application]
	}

	res := getLayoutsResponse{
		Layouts: []layoutResponse{},
	}

	seen := make(map[string]bool)
	for _, layout := range layouts {
		// remove duplicates
		if seen[layout.Measurement+layout.ID] {
			continue
		}
		// filter for data that belongs to provided application or measurement
		if filter(&layout) {
			res.Layouts = append(res.Layouts, newLayoutResponse(layout))
		}
	}
	encodeJSON(w, http.StatusOK, res, s.Logger)
}

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


Question: Make a list value containing the specified values.

public static Value.Builder makeValue(Value value1, Value value2, Value... rest) {
    ArrayValue.Builder arrayValue = ArrayValue.newBuilder();
    arrayValue.addValues(value1);
    arrayValue.addValues(value2);
    arrayValue.addAllValues(Arrays.asList(rest));
    return Value.newBuilder().setArrayValue(arrayValue);
  }

def get_wcs(self):

        wcslist = []
        for chip in self.chip_catalogs:
            wcslist.append(self.chip_catalogs[chip]['wcs'])
        return wcslist

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