Question:
Get the associated repository for a specific key.

@since 0.1.0

@param string $key Key to fetch the repository for.

@return OptionRepository The repository that is associated with the requested key.

public function getRepository(string $key): OptionRepository
    {
        if (! $this->has($key)) {
            throw UnknownOptionKey::fromKey($key);
        }

        return $this->map[$key][self::SUBKEY_REPOSITORY];
    }

public <T> T as(Class<T> type) {
        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getDeclaringClass() == Object.class)
                    return method.invoke(this, args);

                Configuration cn = method.getAnnotation(Configuration.class);

                Class<?> r = method.getReturnType();
                String key = getKey(method,cn);

                String v = source.apply(key);
                if (v==null && cn!=null && !cn.defaultValue().equals(UNSPECIFIED))
                    v = cn.defaultValue();

                if (v==null)    return null;    // TODO: check how the primitive types are handled here

                return ConvertUtils.convert(v,r);
            }

            private String getKey(Method method, Configuration c) {
                if (c!=null && !c.name().equals(UNSPECIFIED))
                    return c.name();        // name override

                String n = method.getName();
                for (String p : GETTER_PREFIX) {
                    if (n.startsWith(p))
                        return Introspector.decapitalize(n.substring(p.length()));
                }
                return n;
            }
        }));
    }

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


Question: // SetImageSizeInBytes sets the ImageSizeInBytes field's value.

func (s *ImageDetail) SetImageSizeInBytes(v int64) *ImageDetail {
	s.ImageSizeInBytes = &v
	return s
}

def calculate_size(name, key, thread_id):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += calculate_size_data(key)
    data_size += LONG_SIZE_IN_BYTES
    return data_size

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


Question:
Deletes all database records related to the field value ID
@param int $field_value_id

protected function deleteLinked($field_value_id)
    {
        $this->db->delete('product_field', array('field_value_id' => $field_value_id));
        $this->db->delete('field_value_translation', array('field_value_id' => $field_value_id));
        $this->db->delete('file', array('entity' => 'field_value', 'entity_id' => $field_value_id));
    }

public function buildUpdateSQL($table = null, $data = array())
	{
		$sql = 'update ' . $this->parseTable($table) . ' set ';
		if(is_string($data))
		{
			$sql .= $data . ' ';
		}
		else
		{
			$data = $this->parseParams($data);
			foreach($data as $key => $value)
			{
				$sql .= $this->parseKeyword($key) . '=:' . $this->parseParamName($key) . ',';
			}
		}
		$where = $this->parseCondition(isset($this->operationOption['where']) ? $this->operationOption['where'] : '');
		if ('' !== $where)
		{
			$where = 'where ' . $where . ' ';
		}
		return substr($sql,0,-1) . ' '
				. $where
				. $this->parseOrder()
				. $this->parseLimit()
				. $this->parseLock()
				;
	}

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


Question:
Handles session start

@param \Thruway\ClientSession $session
@param \Thruway\Transport\TransportProviderInterface $transport

public function onSessionStart($session, $transport)
    {
        $session->register(
            "thruway.auth.{$this->getMethodName()}.onhello",
            [$this, 'processHello'],
            ['replace_orphaned_session' => 'yes']
        )
            ->then(function () use ($session) {
                $session->register(
                    "thruway.auth.{$this->getMethodName()}.onauthenticate",
                    [$this, 'preProcessAuthenticate'],
                    ['replace_orphaned_session' => 'yes']
                )->then(function () use ($session) {

                    $registrations                 = new \stdClass();
                    $registrations->onhello        = "thruway.auth.{$this->getMethodName()}.onhello";
                    $registrations->onauthenticate = "thruway.auth.{$this->getMethodName()}.onauthenticate";

                    $session->call('thruway.auth.registermethod',
                        [
                            $this->getMethodName(),
                            $registrations,
                            $this->getAuthRealms()
                        ]
                    )->then(function ($args) {
                        Logger::debug($this, "Authentication Method Registration Successful: {$this->getMethodName()}");
                    });
                });
            });
    }

protected HttpMethodBase createMethod(String url,HTTPMethod httpMethod)
    {
        if(httpMethod==null)
        {
            throw new FaxException("HTTP method not provided.");
        }
        if((url==null)||(url.length()==0))
        {
            throw new FaxException("HTTP URL not provided.");
        }

        //create method
        HttpMethodBase httpMethodClient=null;
        switch(httpMethod)
        {
            case POST:
                httpMethodClient=new PostMethod(url);
                break;
            case GET:
                httpMethodClient=new GetMethod(url);
                break;
            case PUT:
                httpMethodClient=new PutMethod(url);
                break;
        }

        return httpMethodClient;
    }

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


Question:
Save uploaded files

@param  array
@return array
@author Dmitry (dio) Levashov

protected function upload($args) {
		$target = $args['target'];
		$volume = $this->volume($target);
		$files  = isset($args['FILES']['upload']) && is_array($args['FILES']['upload']) ? $args['FILES']['upload'] : array();
		$result = array('added' => array(), 'header' => empty($args['html']) ? false : 'Content-Type: text/html; charset=utf-8');
		$paths  = $args['upload_path']? $args['upload_path'] : array();
		$chunk  = $args['chunk']? $args['chunk'] : '';
		$cid    = $args['cid']? (int)$args['cid'] : '';

		if (!$volume) {
			return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_TRGDIR_NOT_FOUND, '#'.$target), 'header' => $header);
		}

		// regist Shutdown function
		$GLOBALS['elFinderTempFiles'] = array();
// 		if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
// 			$shutdownfunc = function(){ // <- Parse error on PHP < 5.3 ;-(
// 				foreach(array_keys($GLOBALS['elFinderTempFiles']) as $f){
// 					@unlink($f);
// 				}
// 			};
// 		} else {
			$shutdownfunc = create_function('', '
				foreach(array_keys($GLOBALS[\'elFinderTempFiles\']) as $f){
					@unlink($f);
				}
			');
//		}
		register_shutdown_function($shutdownfunc);

		// file extentions table by MIME
		$extTable = array_flip(array_unique($volume->getMimeTable()));

		if (empty($files)) {
			if (isset($args['upload']) && is_array($args['upload']) && ($tempDir = $this->getTempDir($volume->getTempPath()))) {
				$names = array();
				foreach($args['upload'] as $i => $url) {
					// check chunked file upload commit
					if ($args['chunk']) {
						if ($url === 'chunkfail' && $args['mimes'] === 'chunkfail') {
							$this->checkChunkedFile(null, $chunk, $cid, $tempDir);
							if (preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m)) {
								$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $m[1], self::ERROR_UPLOAD_TRANSFER);
							}
							return $result;
						} else {
							$tmpfname = $tempDir . '/' . $args['chunk'];
							$files['tmp_name'][$i] = $tmpfname;
							$files['name'][$i] = $url;
							$files['error'][$i] = 0;
							$GLOBALS['elFinderTempFiles'][$tmpfname] = true;
							break;
						}
					}

					$tmpfname = $tempDir . DIRECTORY_SEPARATOR . 'ELF_FATCH_' . md5($url.microtime(true));

					// check is data:
					if (substr($url, 0, 5) === 'data:') {
						list($data, $args['name'][$i]) = $this->parse_data_scheme($url, $extTable);
					} else {
						$fp = fopen($tmpfname, 'wb');
						$data = $this->get_remote_contents($url, 30, 5, 'Mozilla/5.0', $fp);
					}
					if ($data) {
						$_name = isset($args['name'][$i])? $args['name'][$i] : preg_replace('~^.*?([^/#?]+)(?:\?.*)?(?:#.*)?$~', '$1', rawurldecode($url));
						if ($_name) {
							$_ext = '';
							if (preg_match('/(\.[a-z0-9]{1,7})$/', $_name, $_match)) {
								$_ext = $_match[1];
							}
							if ((is_resource($data) && fclose($data)) || file_put_contents($tmpfname, $data)) {
								$GLOBALS['elFinderTempFiles'][$tmpfname] = true;
								$_name = preg_replace('/[\/\\?*:|"<>]/', '_', $_name);
								list($_a, $_b) = array_pad(explode('.', $_name, 2), 2, '');
								if ($_b === '') {
									if ($_ext) {
										rename($tmpfname, $tmpfname . $_ext);
										$tmpfname = $tmpfname . $_ext;
									}
									$_b = $this->detectFileExtension($tmpfname);
									$_name = $_a.$_b;
								} else {
									$_b = '.'.$_b;
								}
								if (isset($names[$_name])) {
									$_name = $_a.'_'.$names[$_name]++.$_b;
								} else {
									$names[$_name] = 1;
								}
								$files['tmp_name'][$i] = $tmpfname;
								$files['name'][$i] = $_name;
								$files['error'][$i] = 0;
							} else {
								@ unlink($tmpfname);
							}
						}
					}
				}
			}
			if (empty($files)) {
				return array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_UPLOAD_NO_FILES), 'header' => $header);
			}
		}

		foreach ($files['name'] as $i => $name) {
			if (($error = $files['error'][$i]) > 0) {
				$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE ? self::ERROR_UPLOAD_FILE_SIZE : self::ERROR_UPLOAD_TRANSFER);
				$this->uploadDebug = 'Upload error code: '.$error;
				break;
			}

			$tmpname = $files['tmp_name'][$i];
			$path = ($paths && !empty($paths[$i]))? $paths[$i] : '';
			if ($name === 'blob') {
				if ($chunk) {
					if ($tempDir = $this->getTempDir($volume->getTempPath())) {
						list($tmpname, $name) = $this->checkChunkedFile($tmpname, $chunk, $cid, $tempDir);
						if ($name) {
							$result['_chunkmerged'] = basename($tmpname);
							$result['_name'] = $name;
						}
					} else {
						$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $chunk, self::ERROR_UPLOAD_TRANSFER);
						$this->uploadDebug = 'Upload error: unable open tmp file';
					}
					return $result;
				} else {
					// for form clipboard with Google Chrome
					$type = $files['type'][$i];
					$ext = isset($extTable[$type])? '.' . $extTable[$type] : '';
					$name = substr(md5(basename($tmpname)), 0, 8) . $ext;
				}
			}

			// do hook function 'upload.presave'
			if (! empty($this->listeners['upload.presave'])) {
				foreach($this->listeners['upload.presave'] as $handler) {
					call_user_func_array($handler, array(&$path, &$name, $tmpname, $this, $volume));
				}
			}

			if (($fp = fopen($tmpname, 'rb')) == false) {
				$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, self::ERROR_UPLOAD_TRANSFER);
				$this->uploadDebug = 'Upload error: unable open tmp file';
				if (! is_uploaded_file($tmpname)) {
					if (@ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpfname]);
					continue;
				}
				break;
			}
			if ($path) {
				$_target = $volume->getUploadTaget($target, $path, $result);
			} else {
				$_target = $target;
			}
			if (! $_target || ($file = $volume->upload($fp, $_target, $name, $tmpname)) === false) {
				$result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $volume->error());
				fclose($fp);
				if (! is_uploaded_file($tmpname)) {
					if (@ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpname]);;
					continue;
				}
				break;
			}

			is_resource($fp) && fclose($fp);
			if (! is_uploaded_file($tmpname) && @ unlink($tmpname)) unset($GLOBALS['elFinderTempFiles'][$tmpname]);
			$result['added'][] = $file;
		}
		if ($GLOBALS['elFinderTempFiles']) {
			foreach(array_keys($GLOBALS['elFinderTempFiles']) as $_temp) {
				@ unlink($_temp);
			}
		}
		$result['removed'] = $volume->removed();
		return $result;
	}

public function submit($options = [])
    {
        if (is_string($options)) {
            $options = ['value' => $options];
        }

        if (!Arr::has($options, 'type')) {
            Arr::set($options, 'type', 'submit');
        }

        $input = new Input($this->expression('input'), $options);

        return $input;
    }

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


Question:
Resolve 将model中的数据注入到context中
@param context 控件上下文
@param model 注入模型,若为null,则清空context中的控件

function Resolve(context, model) {
        if (model == null) {
            // 清空context
            for (var prop in context) {
                var target = context[prop];
                if (target instanceof view_4.View) {
                    var propName = target.PropertyName();
                    if (propName) {
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.Clear();
                        }
                        else if (target instanceof list_2.ListView) {
                            target.SetData([]);
                        }
                        else {
                            console.warn(propName + " clear failed, missing clear method!");
                        }
                    }
                }
            }
            return;
        }
        for (var prop in context) {
            var target = context[prop];
            if (target instanceof view_4.View) {
                var propName = target.PropertyName();
                if (propName) {
                    var value = model[propName];
                    if (value) {
                        // 注入
                        if (target instanceof text_3.TextView || target instanceof choice_1.ChoiceView) {
                            target.SetValue(value);
                        }
                        else if (target instanceof list_2.ListView && $.isArray(value)) {
                            target.SetData(value);
                        }
                        else {
                            console.warn(propName + " resolve failed, control type is mismatching!");
                        }
                    }
                    else {
                        console.warn(propName + " resolve failed, value invalid!");
                    }
                }
            }
        }
    }

function (text) {

                var dataModel = this._dataModel;

                if (text !== '' && text !== dataModel.text) {
                    dataModel.text = text;

                    this._pendingRequestNb += 1;
                    this._resourcesHandler.getSuggestions(text, {
                        fn : this._suggestionsCallback,
                        scope : this,
                        args : {
                            nextValue : text,
                            triggerDropDown : false
                        }
                    });

                    // return null as there is asynchrone handling
                    return null;
                }

                // returned object
                var report = new ariaWidgetsControllersReportsDropDownControllerReport();

                // an empty field is usually not considered as an error
                if (text === '') {
                    dataModel.value = null;
                    dataModel.text = '';
                    report.ok = true;
                    report.value = null;
                } else {
                    if (this.freeText) {
                        report.ok = true;
                        if (this._pendingRequestNb > 0 && !dataModel.value) {
                            report.value = dataModel.text;
                        }
                    } else {
                        if (!dataModel.value) {

                            if (this.expandButton && dataModel.listContent && this._checkValueList()) {
                                report.ok = true;
                            } else {
                                report.ok = false;
                                report.value = null;
                                report.errorMessages.push(this.getErrorMessage("validation"));
                            }
                        }

                    }
                    // if there is no value in the dataModel, user was just browsing selections
                    if (dataModel.value) {
                        report.value = dataModel.value;
                    }

                }
                return report;
            }

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


Question:
Parses a single tweet object

 Returns a dict of things.

def parse_one(tweet)
      puts "==> #{tweet['id']}" if @options.verbose
      retdict = {
        mentions: {},
        hashtags: {},
        time_of_day: 0,
        retweet: false,
        client: {
          name: "",
          url: "",
        },
        smileys: {}
      }

      # check if the tweet is actually a retweet and ignore the status text
      unless tweet['retweeted_status'].nil?
        retdict[:retweet] = true
      else
        # scan for mentions
        tweet['text'].scan USERNAME_REGEX do |user|
          hash_user = user[0].downcase
          puts "===> mentioned: #{user[0]}" if @options.verbose
          unless @config[:ignored_users].include? hash_user
            if @config[:renamed_users].include? hash_user.to_sym
              hash_user = @config[:renamed_users][hash_user.to_sym]
            end
            retdict[:mentions][hash_user] ||= {}
            retdict[:mentions][hash_user][:name] ||= user[0]
            retdict[:mentions][hash_user][:count] = retdict[:mentions][hash_user][:count].to_i.succ
            retdict[:mentions][hash_user][:example] ||= { text: tweet['text'], id: tweet['id'] }
          end
        end

        # scan for hashtags
        tweet['text'].scan HASHTAG_REGEX do |hashtag|
          hash_hashtag = hashtag[0].downcase
          puts "===> hashtag: ##{hashtag[0]}" if @options.verbose
          retdict[:hashtags][hash_hashtag] ||= {}
          retdict[:hashtags][hash_hashtag][:hashtag] ||= hashtag[0]
          retdict[:hashtags][hash_hashtag][:count] = retdict[:hashtags][hash_hashtag][:count].to_i.succ
          retdict[:hashtags][hash_hashtag][:example] ||= { text: tweet['text'], id: tweet['id'] }
        end

        # Smileys :^)
        eyes = "[xX8;:=%]"
        nose = "[-oc*^]"
        smile_regex = /(>?#{eyes}'?#{nose}[\)pPD\}\]>]|[\(\{\[<]#{nose}'?#{eyes}<?|[;:][\)pPD\}\]\>]|\([;:]|\^[_o-]*\^[';]|\\[o.]\/)/
        frown_regex = /(#{eyes}'?#{nose}[\(\[\\\/\{|]|[\)\]\\\/\}|]#{nose}'?#{eyes}|[;:][\(\/]|[\)D]:|;_+;|T_+T|-[._]+-)/

        unescaped_tweet = tweet['text'].gsub("&", "&").gsub("<", "<").gsub(">", ">")

        unescaped_tweet.scan smile_regex do |smile|
          smile = smile[0]
          puts "===> smile: #{smile}" if @options.verbose
          retdict[:smileys][smile] ||= {frown: false}
          retdict[:smileys][smile][:smiley] ||= smile
          retdict[:smileys][smile][:count] = retdict[:smileys][smile][:count].to_i.succ
          retdict[:smileys][smile][:example] ||= { text: tweet['text'], id: tweet['id'] }
        end

        unescaped_tweet.scan frown_regex do |frown|
          break unless unescaped_tweet !~ /\w+:\/\// # http:// :^)
          frown = frown[0]
          puts "===> frown: #{frown}" if @options.verbose
          retdict[:smileys][frown] ||= {frown: true}
          retdict[:smileys][frown][:smiley] ||= frown
          retdict[:smileys][frown][:count] = retdict[:smileys][frown][:count].to_i.succ
          retdict[:smileys][frown][:example] ||= { text: tweet['text'], id: tweet['id'] }
        end
      end

      # Tweet source (aka. the client the (re)tweet was made with)
      source_matches = tweet['source'].match SOURCE_REGEX
      retdict[:client][:url]  = source_matches[1]
      retdict[:client][:name] = source_matches[2]

      # Time of day
      retdict[:time_of_day] = (tweet['created_at'].match(/^\d{4}-\d{2}-\d{2} (\d{2})/)[1].to_i + @config[:timezone_difference]) % 24

      retdict
    end

def _api_help(self):

        response.content_type = 'application/json; charset=utf-8'

        # Update the stat
        view_data = self.stats.get_plugin("help").get_view_data()
        try:
            plist = json.dumps(view_data, sort_keys=True)
        except Exception as e:
            abort(404, "Cannot get help view data (%s)" % str(e))
        return plist

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


Question: // BuildContent provides a mock function with given fields: ctx, scm, opts

func (_m *API) BuildContent(ctx context.Context, scm source.Source, opts *types.BuildOptions) (io.ReadCloser, error) {
	ret := _m.Called(ctx, scm, opts)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, source.Source, *types.BuildOptions) io.ReadCloser); ok {
		r0 = rf(ctx, scm, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, source.Source, *types.BuildOptions) error); ok {
		r1 = rf(ctx, scm, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

func (mcs *ConsenterSupport) WriteBlock(block *cb.Block, encodedMetadataValue []byte) {
	if encodedMetadataValue != nil {
		block.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
	}
	mcs.Append(block)
}

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


Question: Check if word require precedence adjustment or not Adjustment means remove prefix then suffix instead of remove suffix then prefix

function precedenceAdjustmentSpecification(word){
    var regex_rules = [
        /^be(.*)lah$/,
        /^be(.*)an$/,
        /^me(.*)i$/,
        /^di(.*)i$/,
        /^pe(.*)i$/,
        /^ter(.*)i$/,
    ];

    for(var i in regex_rules){
        if(word.match(regex_rules[i])){
            return true;
        }
    }
    return false;
}

public function optimize (stdClass $data)
    {
        $data->translationFilePrefix = $this->stringWithUnderscore ($data->serviceURL);

        $data->translationFilePrefix = $this->stringWithUnderscore ($data->translationFilePrefix);
        $data->translationsLocation = $this->getTranslationPrefix ($data) . $data->translationFilePrefix;

        return $data;
    }

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


Question:
Ajusta o Nosso Numero antes de seta-lo no objeto Convenio.

@param ArrayObject $data
@return ArrayObject

public function ajustarNossoNumero(ArrayObject $data)
    {
        $carteira = $this->carteira;

        switch (strlen($this->convenio)) {
            case 6:
                if (!$carteira instanceof Carteira21) {
                    $data['NossoNumero'] = $this->convenio . $data['NossoNumero'];
                }
                break;
            case 4:
            case 7:
                $data['NossoNumero'] = $this->convenio . $data['NossoNumero'];
                break;
            default:
                throw new \LogicException('O codigo do convenio precisa ter 4, 6 ou 7 digitos!');
        }

        return $data;
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Record the current store and, if applicable, if it's the best score
        yet.

def _record_score(self, history, current_score):

        history.record(self.name_, current_score)

        is_best = self._is_best_score(current_score)
        if is_best is None:
            return

        history.record(self.name_ + '_best', bool(is_best))
        if is_best:
            self.best_score_ = current_score

def dump(self):

        # Find all nodes manually, as the Keep object isn't aware of new ListItems
        # until they've been synced to the server.
        nodes = []
        for node in self.all():
            nodes.append(node)
            for child in node.children:
                nodes.append(child)
        return {
            'keep_version': self._keep_version,
            'labels': [label.save(False) for label in self.labels()],
            'nodes': [node.save(False) for node in nodes]
        }

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


Question: Marshall the given parameter object.

public void marshall(DescribeInstancePatchStatesForPatchGroupRequest describeInstancePatchStatesForPatchGroupRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeInstancePatchStatesForPatchGroupRequest.getPatchGroup(), PATCHGROUP_BINDING);
            protocolMarshaller.marshall(describeInstancePatchStatesForPatchGroupRequest.getFilters(), FILTERS_BINDING);
            protocolMarshaller.marshall(describeInstancePatchStatesForPatchGroupRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeInstancePatchStatesForPatchGroupRequest.getMaxResults(), MAXRESULTS_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:
创建单表操作的 insert 语句（单条）
@return string
@throws Exception

protected function buildSql()
    {
        $query = $this->getQuery();
        if (
            !isset($query['table']) || empty($query['table'])
            || !isset($query['columns']) || empty($query['columns'])
        ) {
            throw new Exception(str_cover('"{type}"查询参数不完整', [
                '{type}' => 'insert'
            ]), 101300301);
        }
        $KS = $VS = [];
        foreach ($query['columns'] as $k => $v) {
            if ($v instanceof Expression) {
                $KS[] = $this->quoteColumnName($k);
                $VS[] = $v->expression;
                continue;
            }
            $KS[] = $this->quoteColumnName($k);
            $VS[] = $bk = $this->getBindKey();
            $this->addParam($bk, $v);
        }
        $sql = 'INSERT INTO '
            . $this->quoteTableName($query['table'])
            . ' (' . implode(',', $KS) . ') VALUES (' . implode(',', $VS) . ')';
        return $sql;
    }

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question:
获取组合成的SQL语句字符串
@param $ifreturn
@return string | null

function getsql($ifreturn = true)
    {
        $this->sql = "select {$this->select} from {$this->table}";
        $this->sql .= implode(' ',
            array(
                $this->join,
                $this->use_index,
                $this->where,
                $this->union,
                $this->group,
                $this->having,
                $this->order,
                $this->limit,
                $this->for_update,
            ));

        if ($this->if_union)
        {
            $this->sql = str_replace('{#union_select#}', $this->union_select, $this->sql);
        }
        if ($ifreturn)
        {
            return $this->sql;
        }
    }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question:
// NewEncoder creates a new packfile encoder using a specific Writer and
// EncodedObjectStorer. By default deltas used to generate the packfile will be
// OFSDeltaObject. To use Reference deltas, set useRefDeltas to true.

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,
	}
}

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:
The properties property.

        Returns:
            (hash). the property value. (defaults to: {})

def properties(self):

        if 'properties' in self._values:
            return self._values['properties']
        self._values['properties'] = copy.deepcopy(self._defaults['properties'])
        return self._values['properties']

function(spaces) {
			var prop, def, metas = document.querySelectorAll('meta[name]');
			Array.forEach(metas, function(meta) {
				prop = meta.getAttribute('name');
				spaces.forEach(function(ns) {
					if (prop.startsWith(ns + '.')) {
						def = gui.Object.lookup(prop);
						if (gui.Type.isDefined(def)) {
							gui.Object.assert(prop,
								gui.Type.cast(meta.getAttribute('content'))
							);
						} else {
							console.error('No definition for "' + prop + '"');
						}
					}
				});
			});
		}

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


Question:
Execute the console command.

@return mixed

public function handle()
    {

        $this->connection = $this->option("connection") ? $this->option("connection") : config("es.default");

        $this->size = (int)$this->option("bulk-size");

        $this->scroll = $this->option("scroll");

        if ($this->size <= 0 or !is_numeric($this->size)) {
            return $this->warn("Invalide size value");
        }

        $original_index = $this->argument('index');

        $new_index = $this->argument('new_index');

        if (!in_array($original_index, array_keys(config("es.indices")))) {
            return $this->warn("Missing configuration for index: {$original_index}");
        }

        if (!in_array($new_index, array_keys(config("es.indices")))) {
            return $this->warn("Missing configuration for index: {$new_index}");
        }

        $this->migrate($original_index, $new_index);
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question: Change directories and optionally make the directory if it doesn't exist.

def chdir(self, directory_path, make=False):
        """"""
        if os.sep in directory_path:
            for directory in directory_path.split(os.sep):
                if make and not self.directory_exists(directory):
                    try:
                        self.session.mkd(directory)
                    except ftplib.error_perm:
                        # Directory already exists
                        pass
                self.session.cwd(directory)
        else:
            self.session.cwd(directory_path)

public function chdir($dir)
    {
        return ($this->isConnected() === true) ? ftp_chdir($this->getConnection(), $dir) : false;
    }

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


Question: Retrieves information for an IP4 address.

def RetrieveIP4Info(self, ip):
    """"""
    if ip.is_private:
      return (IPInfo.INTERNAL, "Internal IP address.")
    try:
      # It's an external IP, let's try to do a reverse lookup.
      res = socket.getnameinfo((str(ip), 0), socket.NI_NAMEREQD)
      return (IPInfo.EXTERNAL, res[0])
    except (socket.error, socket.herror, socket.gaierror):
      return (IPInfo.EXTERNAL, "Unknown IP address.")

func New(addr string) (Client, error) {
	factory, ok := factories[*protocol]
	if !ok {
		return nil, fmt.Errorf("unknown throttler client protocol: %v", *protocol)
	}
	return factory(addr)
}

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


Question:
Get the ran mappings.

@return array

public function getRan()
    {
        $result = $this->table()
            ->orderBy('batch', 'asc')
            ->orderBy('mapping', 'asc')
            ->pluck('mapping');

        if (is_array($result)) {
            return $result;
        }

        return $result->toArray();
    }

private function createMaps(RouteCollectionInterface $routes)
    {
        foreach ($routes->all() as $name => $route) {
            foreach ($route->getMethods() as $method) {
                $this->mMap[$method][] = $name;
            }

            foreach ($route->getSchemes() as $scheme) {
                $this->scMap[$scheme][] = $name;
            }

            $this->spMap[$route->getContext()->getStaticPath()][] = $name;
        }
    }

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


Question:
// Detach detaches from the target process.
// If `kill` is true we will kill the process after
// detaching.

func (d *Debugger) Detach(kill bool) error {
	d.processMutex.Lock()
	defer d.processMutex.Unlock()

	return d.detach(kill)
}

def conditions(self, start, last_attempt):

        if time.time() - start > self.timeout:
            yield WaitCondition.Timedout
            return

        if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts:
            yield WaitCondition.KeepWaiting
            return

        if self.greps is not NotSpecified:
            for name, val in self.greps.items():
                yield 'grep "{0}" "{1}"'.format(val, name)

        if self.file_value is not NotSpecified:
            for name, val in self.file_value.items():
                command = 'diff <(echo {0}) <(cat {1})'.format(val, name)
                if not self.harpoon.debug:
                    command = "{0} > /dev/null".format(command)
                yield command

        if self.port_open is not NotSpecified:
            for port in self.port_open:
                yield 'nc -z 127.0.0.1 {0}'.format(port)

        if self.curl_result is not NotSpecified:
            for url, content in self.curl_result.items():
                yield 'diff <(curl "{0}") <(echo {1})'.format(url, content)

        if self.file_exists is not NotSpecified:
            for path in self.file_exists:
                yield 'cat {0} > /dev/null'.format(path)

        if self.command not in (None, "", NotSpecified):
            for command in self.command:
                yield command

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


Question:
Similar to {@link PropertyUtils#getProperty(Object, String)} but returns the property value for the tail of the given
property path.

@param bean         bean to be accessed
@param propertyPath property path
@return value

public static Object getProperty(Object bean, List<String> propertyPath) {
		Object current = bean;
		for (String propertyName : propertyPath) {
			if (current == null) {
				return null;
			}
			if (current instanceof Iterable) {
				// follow multi-valued property
				List<Object> result = new ArrayList<>();
				Iterable<?> iterable = (Iterable<?>) current;
				for (Object currentElem : iterable) {
					result.add(getProperty(currentElem, propertyName));
				}
				current = result;
			} else {
				// follow single-valued property
				current = getProperty(current, propertyName);
			}
		}
		return current;
	}

public static MBeanParameterInfo[] extractParameterInfo(Method m) {
        Class<?>[] types = m.getParameterTypes();
        Annotation[][] annotations = m.getParameterAnnotations();
        MBeanParameterInfo[] params = new MBeanParameterInfo[types.length];
        for(int i = 0; i < params.length; i++) {
            boolean hasAnnotation = false;
            for(int j = 0; j < annotations[i].length; j++) {
                if(annotations[i][j] instanceof JmxParam) {
                    JmxParam param = (JmxParam) annotations[i][j];
                    params[i] = new MBeanParameterInfo(param.name(),
                                                       types[i].getName(),
                                                       param.description());
                    hasAnnotation = true;
                    break;
                }
            }
            if(!hasAnnotation) {
                params[i] = new MBeanParameterInfo("", types[i].getName(), "");
            }
        }

        return params;
    }

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


Question: Deletes dotfiles and machine-id for fresh registration

def clear_local_registration(self):
        '''

        '''
        delete_registered_file()
        delete_unregistered_file()
        write_to_disk(constants.machine_id_file, delete=True)
        logger.debug('Re-register set, forcing registration.')
        logger.debug('New machine-id: %s', generate_machine_id(new=True))

def _read_potentials(self, pot_dir):

        if self.assignments['potentials'] is not None:
            print('Potentials already imported. Will not overwrite!')
            return
        else:
            self.assignments['potentials'] = {}

        pot_files = sorted(glob(pot_dir + os.sep + 'pot*.dat'))
        for nr, filename in enumerate(pot_files):
            with open(filename, 'r') as fid:
                pot_data = np.loadtxt(fid)

                nids = self.nodeman.add_data(
                    pot_data[:, 2:4],
                )
                # store cids for later retrieval
                self.assignments['potentials'][nr] = nids

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


Question: Log current settings.

def log(self):
        """"""
        log.info('PyPhi v%s', __about__.__version__)
        if self._loaded_files:
            log.info('Loaded configuration from %s', self._loaded_files)
        else:
            log.info('Using default configuration (no configuration file '
                     'provided)')
        log.info('Current PyPhi configuration:\n %s', str(self))

func (cl *CoLog) SetFlags(flags int) {
	cl.mu.Lock()
	defer cl.mu.Unlock()
	if cl.formatter == nil {
		return
	}

	cl.formatter.SetFlags(flags)
}

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


Question:
Gets the options as string for the textarea value
@return string The string representation of the options

private function OptionsString()
    {
        if (!$this->select->Exists())
        {
            return '';
        }
        $list = new SelectListProvider($this->select);
        $options = $list->ToArray();
        $lines = array();
        foreach ($options as $key=>$value)
        {
            $lines[] = $key . ':' . $value;
        }
        return join("\r\n", $lines);
    }

public function renderField()
    {
        list($name, $id) = $this->resolveNameID();

        TbArray::defaultValue('id', $id, $this->htmlOptions);
        TbArray::defaultValue('name', $name, $this->htmlOptions);

        // fixes #32: 'multiple' will be forced later in jQuery plugin
        $this->htmlOptions['multiple'] = 'multiple';

        if ($this->hasModel()) {
            echo CHtml::activeDropDownList($this->model, $this->attribute, $this->data, $this->htmlOptions);
        } else {
            echo CHtml::dropDownList($this->name, $this->value, $this->data, $this->htmlOptions);
        }
    }

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


Question:
@param ContainerInterface $container

@return DelegatingLoader

protected function getContainerLoader(ContainerInterface $container)
    {
        $locator = new FileLocator($this);
        $resolver = new LoaderResolver([
            new XmlFileLoader($container, $locator),
            new YamlFileLoader($container, $locator),
            new IniFileLoader($container, $locator),
            new PhpFileLoader($container, $locator),
            new DirectoryLoader($container, $locator),
            new ClosureLoader($container),
        ]);

        return new DelegatingLoader($resolver);
    }

func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
	jobOpts = applyDefaultsAndValidate(jobOpts)

	vfn := reflect.ValueOf(fn)
	validateHandlerType(wp.contextType, vfn)
	jt := &jobType{
		Name:           name,
		DynamicHandler: vfn,
		JobOptions:     jobOpts,
	}
	if gh, ok := fn.(func(*Job) error); ok {
		jt.IsGeneric = true
		jt.GenericHandler = gh
	}

	wp.jobTypes[name] = jt

	for _, w := range wp.workers {
		w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
	}

	return wp
}

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


Question:
Applies an assigner to the method delegation that is used for assigning method return and parameter types.

@param assigner The assigner to apply.
@return A method delegation implementation that makes use of the given designer.

public Implementation.Composable withAssigner(Assigner assigner) {
        return new MethodDelegation(implementationDelegate,
                parameterBinders,
                ambiguityResolver,
                terminationHandler,
                bindingResolver,
                assigner);
    }

private Node inlineFunction(Reference ref, Node fnNode, String fnName) {
    Node callNode = ref.callNode;
    Node parent = callNode.getParent();
    Node grandParent = parent.getParent();

    // TODO(johnlenz): Consider storing the callSite classification in the
    // reference object and passing it in here.
    CallSiteType callSiteType = classifyCallSite(ref);
    checkArgument(callSiteType != CallSiteType.UNSUPPORTED);

    // Store the name for the result. This will be used to
    // replace "return expr" statements with "resultName = expr"
    // to replace
    String resultName = null;
    boolean needsDefaultReturnResult = true;
    switch (callSiteType) {
      case SIMPLE_ASSIGNMENT:
        resultName = parent.getFirstChild().getString();
        removeConstantVarAnnotation(ref.scope, resultName);
        break;

      case VAR_DECL_SIMPLE_ASSIGNMENT:
        resultName = parent.getString();
        removeConstantVarAnnotation(ref.scope, resultName);
        break;

      case SIMPLE_CALL:
        resultName = null;  // "foo()" doesn't need a result.
        needsDefaultReturnResult = false;
        break;

      case EXPRESSION:
        throw new IllegalStateException(
            "Movable expressions must be moved before inlining.");

      case DECOMPOSABLE_EXPRESSION:
        throw new IllegalStateException(
            "Decomposable expressions must be decomposed before inlining.");

      default:
        throw new IllegalStateException("Unexpected call site type.");
    }

    FunctionToBlockMutator mutator = new FunctionToBlockMutator(compiler, this.safeNameIdSupplier);

    boolean isCallInLoop = NodeUtil.isWithinLoop(callNode);
    Node newBlock = mutator.mutate(
        fnName, fnNode, callNode, resultName,
        needsDefaultReturnResult, isCallInLoop);
    NodeUtil.markNewScopesChanged(newBlock, compiler);

    // TODO(nicksantos): Create a common mutation function that
    // can replace either a VAR name assignment, assignment expression or
    // a EXPR_RESULT.
    Node greatGrandParent = grandParent.getParent();
    switch (callSiteType) {
      case VAR_DECL_SIMPLE_ASSIGNMENT:
        // Remove the call from the name node.
        Node firstChild = parent.removeFirstChild();
        NodeUtil.markFunctionsDeleted(firstChild, compiler);
        Preconditions.checkState(parent.getFirstChild() == null);
        // Add the call, after the VAR.
        greatGrandParent.addChildAfter(newBlock, grandParent);
        break;

      case SIMPLE_ASSIGNMENT:
        // The assignment is now part of the inline function so
        // replace it completely.
        Preconditions.checkState(grandParent.isExprResult());
        greatGrandParent.replaceChild(grandParent, newBlock);
        NodeUtil.markFunctionsDeleted(grandParent, compiler);
        break;

      case SIMPLE_CALL:
        // If nothing is looking at the result just replace the call.
        Preconditions.checkState(parent.isExprResult());
        grandParent.replaceChild(parent, newBlock);
        NodeUtil.markFunctionsDeleted(parent, compiler);
        break;

      default:
        throw new IllegalStateException("Unexpected call site type.");
    }

    return newBlock;
  }

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


Question:
Returns complete CRL URLs - does not include delta CRLs

        :return:
            A list of zero or more DistributionPoint objects

def crl_distribution_points(self):

        if self._crl_distribution_points is None:
            self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value)
        return self._crl_distribution_points

def get_routing_tuples(cls):
        ''''''
        for callback in cls.callbacks:
            ep_name = '{}.{}'.format(cls.api.__name__, callback.__name__)
            yield (Rule(cls.endpoint_path,
                        endpoint=ep_name,
                        methods=callback.swagger_ops),
                   callback)

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


Question:
Success
@param Form $form
@throws \Propel\Runtime\Exception\PropelException

public function success(Form $form) : void
    {
        if ($this->presenter->isAjax())
        {
            $values = $form->getValues();

            try
            {
                $redirect = NULL;
                $page = $this->pageRepository->findOneById($values->pageId);

                if ($this->redirectId)
                {
                    $redirect = $this->onPageRepository->findOneRedirectById($this->redirectId);
                }

                $this->onPageManager->saveRedirect($redirect, $page, $values->oldUrl);

                $form->reset();

                $this->presenter->notificationAjax(
                    'URL přesměrována',
                    'URL byla úspěšně přesměrována.',
                    'success',
                    FALSE
                );

                $this->onSave();
            }
            catch (DatabaseException $exception)
            {
                $this->presenter->notificationAjax(
                    'Chyba',
                    $exception->getMessage(),
                    'error'
                );
            }
        }
    }

def _send p, sys=false
            if not sys and p.src.nil?
                # do not route non system orphan particles !!
                p.error! Edoors::ERROR_ROUTE_NS, @spin
            elsif p.dst
                # direct routing through pointer
                return
            elsif p.door
                # direct routing through path
                _route p
            elsif p.next_dst
                p.split_dst!
                if p.door
                    _route p
                elsif not sys
                    # boomerang
                    p.dst_routed! p.src
                elsif p.action
                    p.dst_routed! @spin
                end
            elsif not sys and _try_links p
                return
            else
                p.error!( sys ? Edoors::ERROR_ROUTE_SND : Edoors::ERROR_ROUTE_NDNL)
            end
        end

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


Question:
Return the tile image GID for this location

        :param x: x coordinate
        :param y: y coordinate
        :param layer: layer number
        :rtype: python dict if found, otherwise None

def get_tile_properties(self, x, y, layer):

        try:
            assert (x >= 0 and y >= 0 and layer >= 0)
        except AssertionError:
            raise ValueError

        try:
            gid = self.layers[int(layer)].data[int(y)][int(x)]
        except (IndexError, ValueError):
            msg = "Coords: ({0},{1}) in layer {2} is invalid."
            logger.debug(msg.format(x, y, layer))
            raise Exception

        else:
            try:
                return self.tile_properties[gid]
            except (IndexError, ValueError):
                msg = "Coords: ({0},{1}) in layer {2} has invalid GID: {3}"
                logger.debug(msg.format(x, y, layer, gid))
                raise Exception
            except KeyError:
                return None

def gen_lazy_function(self):

        # If value argument to __init__ was None, draw value from random
        # method.
        if self._value is None:

            # Use random function if provided
            if self._random is not None:
                self.value = self._random(**self._parents.value)

            # Otherwise leave initial value at None and warn.
            else:
                raise ValueError(
                    'Stochastic ' +
                    self.__name__ +
                    "'s value initialized to None; no initial value or random method provided.")

        arguments = {}
        arguments.update(self.parents)
        arguments['value'] = self
        arguments = DictContainer(arguments)

        self._logp = LazyFunction(fun=self._logp_fun,
                                  arguments=arguments,
                                  ultimate_args=self.extended_parents | set(
                                      [self]),
                                  cache_depth=self._cache_depth)
        self._logp.force_compute()

        self._logp_partial_gradients = {}

        for parameter, function in six.iteritems(self._logp_partial_gradient_functions):
            lazy_logp_partial_gradient = LazyFunction(fun=function,
                                                      arguments=arguments,
                                                      ultimate_args=self.extended_parents | set(
                                                          [self]),
                                                      cache_depth=self._cache_depth)
            # lazy_logp_partial_gradient.force_compute()
            self._logp_partial_gradients[parameter] = lazy_logp_partial_gradient

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


Question:
Retrieve the remote name
@returns {Function}

function gitRemote() {
      return function() {
        var deferred = Q.defer();
        Q.fcall(command('git remote', 'Git remote'))
          .then(function( data ) {
            if ( !data || !data.trim() ) {
              deferred.reject(new Error('Error in step [Git remote]. No remotes founds.'));
            }
            var remotes = data.trim().split('\n');
            if ( remotes.length == 1 ) {
              grunt.option('remote', remotes[0]);
              deferred.resolve(grunt.option('remote'));
            }
            else {
              remotes.forEach(function( item, index, list ) {
                list[index] = format('[%s]-%s', index + 1, item);
              });
              var resp = 0;
              grunt.log.writeln(format('%s ', '\n\nThere are more than 1 remote associate with this repo, please choose the one to push into.\n\n' + remotes.join('\n')));
              while ( isNaN(resp) || resp === 0 || resp > remotes.length ) {
                resp = readlinesync.question('\nYour choice?');
                if ( resp === '' ) {
                  grunt.option('remote', undefined);
                  throw new Error('Error in step [Git remote]. No response from user.');
                }
                resp = parseInt(resp);
              }
              grunt.option('remote', data.trim().split('\n')[resp-1]);//using original output
              deferred.resolve(grunt.option('remote'));
            }

          })
          .catch(function( err ) {
            grunt.option('remote', undefined);
            deferred.reject(err);
          });
        return deferred.promise;
      };
    }

func (pb *prober) runProbeWithRetries(probeType probeType, p *v1.Probe, pod *v1.Pod, status v1.PodStatus, container v1.Container, containerID kubecontainer.ContainerID, retries int) (probe.Result, string, error) {
	var err error
	var result probe.Result
	var output string
	for i := 0; i < retries; i++ {
		result, output, err = pb.runProbe(probeType, p, pod, status, container, containerID)
		if err == nil {
			return result, output, nil
		}
	}
	return result, output, err
}

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


Question:
This code can evaluate the data from the parser. It sorts out which object type we are dealing with and passes
this to the PhpClass

@param Node $node
@return false|null|Node|\PhpParser\Node[]|void

public function leaveNode(Node $node) {
        if ($this->phpClass instanceof PhpClass) {
            if ($node instanceof Class_) {
                if (!empty($node->extends) && count($node->extends->parts) > 0) {
                    $this->phpClass->setExtends(implode('\\', $node->extends->parts));
                }

                if (!empty($node->implements) && is_array($node->implements)) {
                    foreach ($node->implements as $implements) {
                        $this->phpClass->setImplements(implode('\\', $implements->parts));
                    }
                }

                if ($node->type === 0) {
                    $this->phpClass->setClassType(PhpClass::TYPE_CLASS);
                } elseif ($node->type === 16) {
                    $this->phpClass->setClassType(PhpClass::TYPE_ABSTRACT_CLASS);
                } elseif ($node->type === 32) {
                    $this->phpClass->setClassType(PhpClass::TYPE_FINAL_CLASS);
                }

                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Interface_) {
                if (!empty($node->extends) && is_array($node->extends)) {
                    foreach ($node->extends as $implements) {
                        $this->phpClass->setImplements(implode('\\', $implements->parts));
                    }
                }

                $this->phpClass->setClassType(PhpClass::TYPE_INTERFACE);
                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Trait_) {
                $this->phpClass->setClassType(PhpClass::TYPE_TRAIT);
                $this->phpClass->setClass($node->name);
            } elseif ($node instanceof Namespace_) {
                $this->phpClass->setNamespace(implode('\\', $node->name->parts));
            } elseif ($node instanceof TraitUse) {
                if (!empty($node->traits) && is_array($node->traits)) {
                    foreach ($node->traits as $trait) {
                        $this->phpClass->setTraits(implode('\\', $trait->parts));
                    }
                }
            }
        }
    }

public static function addNodePathSegment($nodePath, $nodePathSegment)
    {
        $nodePath = rtrim($nodePath, '/');
        if ($nodePathSegment !== '' || $nodePath === '') {
            $nodePath .= '/' . trim($nodePathSegment, '/');
        }

        return $nodePath;
    }

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


Question:
// FindInstanceTemplates finds all instance templates that are associated with the current cluster
// It matches them by looking for instance metadata with key='cluster-name' and value of our cluster name

func FindInstanceTemplates(c GCECloud, clusterName string) ([]*compute.InstanceTemplate, error) {
	findClusterName := strings.TrimSpace(clusterName)
	var matches []*compute.InstanceTemplate
	ctx := context.Background()

	err := c.Compute().InstanceTemplates.List(c.Project()).Pages(ctx, func(page *compute.InstanceTemplateList) error {
		for _, t := range page.Items {
			match := false
			for _, item := range t.Properties.Metadata.Items {
				if item.Key == "cluster-name" {
					value := fi.StringValue(item.Value)
					if strings.TrimSpace(value) == findClusterName {
						match = true
					} else {
						match = false
						break
					}
				}
			}

			if !match {
				continue
			}

			matches = append(matches, t)
		}
		return nil
	})
	if err != nil {
		return nil, fmt.Errorf("error listing instance templates: %v", err)
	}

	return matches, nil
}

def get_create_options(self):
        """"""
        package = self._get_package()
        # Locations
        locations = []
        for region in package['regions']:
            locations.append({
                'name': region['location']['location']['longName'],
                'key': region['location']['location']['name'],
            })
        # flavors
        dedicated_host = []
        for item in package['items']:
            if item['itemCategory']['categoryCode'] == \
                    'dedicated_virtual_hosts':
                dedicated_host.append({
                    'name': item['description'],
                    'key': item['keyName'],
                })

        return {'locations': locations, 'dedicated_host': dedicated_host}

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


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

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AfplibPackage.STO__IORNTION:
				setIORNTION(IORNTION_EDEFAULT);
				return;
			case AfplibPackage.STO__BORNTION:
				setBORNTION(BORNTION_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

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:
See {@link Files#newBufferedReader(Path, Charset)}.

@param path See {@link Files#newBufferedReader(Path, Charset)}
@param cs See {@link Files#newBufferedReader(Path, Charset)}
@return See {@link Files#newBufferedReader(Path, Charset)}

public BufferedReader newBufferedReader(Path path, Charset cs)
    {
        try {
            return Files.newBufferedReader(path, cs);
        } catch (IOException e) {
            return null;
        }
    }

func (c *Custom) Parse(files *map[string]*file.File, dirs **dir.Dir, config *SharedConfig) error {
	to := *files
	dirList := *dirs

	var newList []string
	for _, customFile := range c.Files {
		// get files from glob
		list, err := doublestar.Glob(customFile)
		if err != nil {
			return err
		}

		// insert files from glob into the new list
		newList = append(newList, list...)
	}

	// copy new list
	c.Files = newList

	// 0 files in the list
	if len(c.Files) == 0 {
		return errors.New("No files found")
	}

	// loop through files from glob
	for _, customFile := range c.Files {
		// gives error when file doesn't exist
		if !utils.Exists(customFile) {
			return fmt.Errorf("File [%s] doesn't exist", customFile)
		}

		cb := func(fpath string, d *godirwalk.Dirent) error {
			if config.Updater.Empty && !config.Updater.IsUpdating {
				log.Println("empty mode")
				return nil
			}

			// only files will be processed
			if d != nil && d.IsDir() {
				return nil
			}

			originalPath := fpath
			fpath = utils.FixPath(fpath)

			var fixedPath string
			if c.Prefix != "" || c.Base != "" {
				c.Base = strings.TrimPrefix(c.Base, "./")

				if strings.HasPrefix(fpath, c.Base) {
					fixedPath = c.Prefix + fpath[len(c.Base):]
				} else {
					if c.Base != "" {
						fixedPath = c.Prefix + fpath
					}
				}

				fixedPath = utils.FixPath(fixedPath)
			} else {
				fixedPath = utils.FixPath(fpath)
			}

			// check for excluded files
			for _, excludedFile := range c.Exclude {
				m, err := doublestar.Match(c.Prefix+excludedFile, fixedPath)
				if err != nil {
					return err
				}

				if m {
					return nil
				}
			}

			info, err := os.Stat(fpath)
			if err != nil {
				return err
			}

			if info.Name() == config.Output {
				return nil
			}

			// get file's content
			content, err := ioutil.ReadFile(fpath)
			if err != nil {
				return err
			}

			replaced := false

			// loop through replace list
			for _, r := range c.Replace {
				// check if path matches the pattern from property: file
				matched, err := doublestar.Match(c.Prefix+r.File, fixedPath)
				if err != nil {
					return err
				}

				if matched {
					for pattern, word := range r.Replace {
						content = []byte(strings.Replace(string(content), pattern, word, -1))
						replaced = true
					}
				}
			}

			// compress the content
			if config.Compression.Options != nil {
				content, err = config.Compression.Compress(content)
				if err != nil {
					return err
				}
			}

			dst := make([]byte, len(content)*4)
			for i := 0; i < len(content); i++ {
				dst[i*4] = byte('\\')
				dst[i*4+1] = byte('x')
				dst[i*4+2] = hextable[content[i]>>4]
				dst[i*4+3] = hextable[content[i]&0x0f]
			}

			f := file.NewFile()
			f.OriginalPath = originalPath
			f.ReplacedText = replaced
			f.Data = `[]byte("` + string(dst) + `")`
			f.Name = info.Name()
			f.Path = fixedPath
			f.Tags = c.Tags
			f.Base = c.Base
			f.Prefix = c.Prefix
			f.Modified = info.ModTime().String()

			if _, ok := to[fixedPath]; ok {
				f.Tags = to[fixedPath].Tags
			}

			// insert dir to dirlist so it can be created on b0x's init()
			dirList.Insert(path.Dir(fixedPath))

			// insert file into file list
			to[fixedPath] = f
			return nil
		}

		customFile = utils.FixPath(customFile)

		// unlike filepath.walk, godirwalk will only walk dirs
		f, err := os.Open(customFile)
		if err != nil {
			return err
		}

		defer f.Close()

		fs, err := f.Stat()
		if err != nil {
			return err
		}

		if fs.IsDir() {
			if err := godirwalk.Walk(customFile, &godirwalk.Options{
				Unsorted: true,
				Callback: cb,
			}); err != nil {
				return err
			}

		} else {
			if err := cb(customFile, nil); err != nil {
				return err
			}
		}
	}

	return nil
}

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


Question: Get KL loss for all the predicted Gaussians.

def get_kl_loss(self, means, log_vars, means_p=None, log_vars_p=None):
    """"""
    kl_loss = 0.0
    if means_p is None:
      means_p = tf.unstack(tf.zeros_like(means))
    if log_vars_p is None:
      log_vars_p = tf.unstack(tf.zeros_like(log_vars))
    enumerated_inputs = enumerate(zip(means, log_vars, means_p, log_vars_p))
    if self.is_training and self.hparams.stochastic_model:
      for i, (mean, log_var, mean_p, log_var_p) in enumerated_inputs:
        kl_loss += common_layers.kl_divergence(mean, log_var, mean_p, log_var_p)
        tf.summary.histogram("posterior_mean_%d" % i, mean)
        tf.summary.histogram("posterior_log_var_%d" % i, log_var)
        tf.summary.histogram("prior_mean_%d" % i, mean_p)
        tf.summary.histogram("prior_log_var_%d" % i, log_var_p)
      tf.summary.scalar("kl_raw", tf.reduce_mean(kl_loss))

    beta = self.get_beta(kl_loss)
    # information capacity from "Understanding disentangling in beta-VAE"
    if self.hparams.information_capacity > 0.0:
      kl_loss = tf.abs(kl_loss - self.hparams.information_capacity)
    return beta * kl_loss

def density_2d(self, r, kwargs_profile):

        kwargs = copy.deepcopy(kwargs_profile)
        try:
            del kwargs['center_x']
            del kwargs['center_y']
        except:
            pass
        # integral of self._profile.density(np.sqrt(x^2+r^2))* dx, 0, infty
        out = integrate.quad(lambda x: 2*self._profile.density(np.sqrt(x**2+r**2), **kwargs), 0, 100)
        return out[0]

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


Question: returns the 'query' from the request

def get_query():

    q = get("q", "")

    qs = q.lstrip("*.!$%&/()=#-+:'`´^")
    if qs and not qs.endswith("*"):
        qs += "*"
    return qs

func newOpClientRequest(reqType opClientRequestType, args interface{}) opClientRequest {
	return opClientRequest{
		op:       reqType,
		args:     args,
		response: make(chan interface{}),
	}
}

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


Question: Alter data in dm format devices

def alter(data, system):
    """"""
    device = data[0]
    action = data[1]
    if data[2] == '*':
        data[2] = '.*'
    regex = re.compile(data[2])
    prop = data[3]
    value = float(data[4])
    if action == 'MUL':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] *= value
    elif action == 'REP':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] = value
    elif action == 'DIV':
        if not value:
            return
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] /= value
    elif action == 'SUM':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] += value
    elif action == 'SUB':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] -= value
    elif action == 'POW':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] **= value
    else:
        print('ALTER action <%s> is not defined', action)

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question:
Adds the given factory to the cache and associates it with the given
type name.

@param <T> Should match {@code typeName}.
@param typeName The fully qualified name of the type.
@param factory The factory to associate with {@code typeName}

public <T> void put(String typeName, PrefabValueFactory<T> factory) {
        if (typeName != null) {
            cache.put(typeName, factory);
        }
    }

public static TemplateMetadata fromTemplate(TemplateNode template) {
    TemplateMetadata.Builder builder =
        builder()
            .setTemplateName(template.getTemplateName())
            .setSourceLocation(template.getSourceLocation())
            .setSoyFileKind(SoyFileKind.SRC)
            .setContentKind(template.getContentKind())
            .setStrictHtml(template.isStrictHtml())
            .setDelPackageName(template.getDelPackageName())
            .setVisibility(template.getVisibility())
            .setParameters(Parameter.directParametersFromTemplate(template))
            .setDataAllCallSituations(DataAllCallSituation.fromTemplate(template));
    switch (template.getKind()) {
      case TEMPLATE_BASIC_NODE:
        builder.setTemplateKind(Kind.BASIC);
        break;
      case TEMPLATE_DELEGATE_NODE:
        builder.setTemplateKind(Kind.DELTEMPLATE);
        TemplateDelegateNode deltemplate = (TemplateDelegateNode) template;
        builder.setDelTemplateName(deltemplate.getDelTemplateName());
        builder.setDelTemplateVariant(deltemplate.getDelTemplateVariant());
        break;
      case TEMPLATE_ELEMENT_NODE:
        builder.setTemplateKind(Kind.ELEMENT);
        break;
      default:
        throw new AssertionError("unexpected template kind: " + template.getKind());
    }
    return builder.build();
  }

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


Question:
Generate steps

@param float $latitude
@param float $longitude
@param int $steps
@param float $radius
@param bool $walkBack

@return array

public static function generateSteps(float $latitude, float $longitude, int $steps, float $radius = 0.07, $walkBack = false)
    {
        $result = [[
            $latitude,
            $longitude,
            self::BEARING_NORTH
        ]];
        $pulse = $radius;
        $xDistance = sqrt(3) * $pulse;
        $yDistance = 3 * ($pulse / 2);
        $location = [$latitude, $longitude];

        for ($step = 1; $step < $steps; $step++) {
            $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_NORTH);
            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_WEST);

            for ($direction = 0; $direction < 6; $direction++) {
                for ($s = 0; $s < $step; $s++){
                    switch($direction) {
                        case 0:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance, self::BEARING_EAST);
                            break;
                        case 1:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_SOUTH);
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_EAST);
                            break;
                        case 2:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_SOUTH);
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_WEST);
                            break;
                        case 3:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance, self::BEARING_WEST);
                            break;
                        case 4:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_NORTH);
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_WEST);
                            break;
                        case 5:
                            $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_NORTH);
                            $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_EAST);
                            break;
                    }

                    $result[] = [
                        $location[0],
                        $location[1],
                        self::BEARING_NORTH
                    ];
                }
            }
        }

        /* Walk back to center */
        if ($walkBack === true) {
            for ($step = 1; $step < ($steps - 1); $step++) {
                $location = self::calculateNewCoordinates($location[0], $location[1], $yDistance, self::BEARING_SOUTH);
                $location = self::calculateNewCoordinates($location[0], $location[1], $xDistance / 2, self::BEARING_EAST);
                $result[] = [
                    $location[0],
                    $location[1],
                    self::BEARING_NORTH
                ];
            }
        }

        return $result;
    }

function parseSetFunction( $funcName, &$args, $tpl, &$text, &$text_len, &$cur_pos,
                               $relatedTemplateName, $startLine, $startColumn, $rootNamespace )
    {
        while ( $cur_pos < $text_len )
        {
            $dollarSignFound = false;

            // skip optional dollar sign
            if ( $text[$cur_pos] == '$' )
            {
                $dollarSignFound = true;
                $cur_pos++;
            }

            // parse variable name
            $wordEndPos = $this->ElementParser->identifierEndPosition( $tpl, $text, $cur_pos, $text_len );
            $varName = substr( $text, $cur_pos, $wordEndPos-$cur_pos );
            $cur_pos = $wordEndPos;

            if ( !$varName )
            {
                $this->showParseErrorMessage( $tpl, $text, $text_len, $cur_pos, $relatedTemplateName, $startLine, $startColumn,
                                              $funcName, 'Empty variable name' );
                return;
            }

            /*
             * If parameter 'name' or 'scope' was passed without dollar sign
             * change its name to '-name' or '-scope', respectively.
             * In this case it is treated specially in the {set}/{let}/{default} functions.
             */
            if ( !$dollarSignFound && ( $varName == 'name' || $varName == 'scope' ) )
                $varName = "-$varName";

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

            // if no value, assume boolean true
            if ( $cur_pos >= $text_len or
                 ( $text[$cur_pos] != '=' /*and preg_match( "/[ \t\r\n]/", $text[$cur_pos] )*/ ) )
            {
                unset( $var_data );
                $var_data = array();
                $args[$varName] = array( array( eZTemplate::TYPE_NUMERIC, // type
                                                true, // content
                                                false // debug
                                                ) );
                continue;
            }

            if ( $cur_pos >= $text_len )
                break;

            $cur_pos++;

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );

            $args[$varName] = $this->ElementParser->parseVariableTag( $tpl, $relatedTemplateName, $text, $cur_pos, $cur_pos, $text_len, $rootNamespace );

            // skip whitespaces
            $cur_pos = $this->ElementParser->whitespaceEndPos( $tpl, $text, $cur_pos, $text_len );
        }
    }

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


Question:
Set the group associated with a given path.

@param fs the {@link FileSystem} instance used to perform the file operation
@param path the given path
@param group the group associated with the path
@throws IOException

public static void setGroup(FileSystem fs, Path path, String group) throws IOException {
    fs.setOwner(path, fs.getFileStatus(path).getOwner(), group);
  }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
// WaitForStaticPodSingleHash returns an empty hash
// but the empty strings there are needed

func (w *Waiter) WaitForStaticPodSingleHash(_ string, _ string) (string, error) {
	return "", nil
}

def _detect(self):

        results = []

        self.results = []
        self.visited_all_paths = {}

        for contract in self.slither.contracts:
            for function in contract.functions:
                if function.is_implemented:
                    uninitialized_storage_variables = [v for v in function.local_variables if v.is_storage and v.uninitialized]
                    function.entry_point.context[self.key] = uninitialized_storage_variables
                    self._detect_uninitialized(function, function.entry_point, [])

        for(function, uninitialized_storage_variable) in self.results:
            var_name = uninitialized_storage_variable.name

            info = "{} in {}.{} ({}) is a storage variable never initialiazed\n"
            info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str)

            json = self.generate_json_result(info)
            self.add_variable_to_json(uninitialized_storage_variable, json)
            self.add_function_to_json(function, json)
            results.append(json)

        return results

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


Question:
// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint  variable that stores the value of the flag.

func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
	p := new(uint)
	f.UintVar(p, name, value, usage)
	return p
}

func Validate(m []Validation) error {
	for _, item := range m {
		v := reflect.ValueOf(item.TargetValue)
		for _, constraint := range item.Constraints {
			var err error
			switch v.Kind() {
			case reflect.Ptr:
				err = validatePtr(v, constraint)
			case reflect.String:
				err = validateString(v, constraint)
			case reflect.Struct:
				err = validateStruct(v, constraint)
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				err = validateInt(v, constraint)
			case reflect.Float32, reflect.Float64:
				err = validateFloat(v, constraint)
			case reflect.Array, reflect.Slice, reflect.Map:
				err = validateArrayMap(v, constraint)
			default:
				err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind()))
			}

			if err != nil {
				return err
			}
		}
	}
	return nil
}

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


Question: // SetRegisteredTime sets the RegisteredTime field's value.

func (s *AgentInfo) SetRegisteredTime(v string) *AgentInfo {
	s.RegisteredTime = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
Return collection of loaded parameters

@return \Cake\Collection\Collection

public function collection($collectionMethod = null)
    {
        $collection = collection($this->_loaded);
        if (is_callable($collectionMethod)) {
            return $collectionMethod($collection);
        }

        return $collection;
    }

func (p *Params) Bind(dest interface{}, name string) {
	value := reflect.ValueOf(dest)
	if value.Kind() != reflect.Ptr {
		paramsLogger.Panic("Bind: revel/params: non-pointer passed to Bind: " + name)
	}
	value = value.Elem()
	if !value.CanSet() {
		paramsLogger.Panic("Bind: revel/params: non-settable variable passed to Bind: " + name)
	}

	// Remove the json from the Params, this will stop the binder from attempting
	// to use the json data to populate the destination interface. We do not want
	// to do this on a named bind directly against the param, it is ok to happen when
	// the action is invoked.
	jsonData := p.JSON
	p.JSON = nil
	value.Set(Bind(p, name, value.Type()))
	p.JSON = jsonData
}

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


Question: // serviced service run SERVICEID [COMMAND [ARGS ...]]

func (c *ServicedCli) cmdServiceRun(ctx *cli.Context) error {
	// set up signal handler to stop the run
	stopChan := make(chan struct{})
	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigChan
		log.Debug("Received stop signal")
		close(stopChan)
		log.Info("Stopped service run")
	}()

	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		return c.exit(1)
	}

	if len(args) < 2 {
		for _, s := range c.serviceCommands(args[0]) {
			fmt.Println(s)
		}
		fmt.Fprintf(os.Stderr, "serviced service run")
		return c.exit(1)
	}

	// Bash completion, CC-892
	if args[len(args)-1] == "--generate-bash-completion" {
		// if "serviced service run SERVICE_ID --generate-bash-completion" is executed
		if len(args) == 2 {
			svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
			if err == nil {
				for _, cmd := range c.serviceCommands(svcDetails.ID) {
					fmt.Println(cmd)
				}
			} else {
				return c.exit(1)
			}
		}
		return c.exit(0)
	}

	var (
		command string
		argv    []string
	)

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(1)
	}

	svc, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return c.exit(1)
	}

	if returncode := c.printHelpForRun(svc, args[1]); returncode >= 0 {
		return c.exit(returncode)
	}

	command = args[1]
	if len(args) > 2 {
		argv = args[2:]
	}

	uuid, _ := utils.NewUUID62()

	config := api.ShellConfig{
		ServiceID:        svc.ID,
		Command:          command,
		Username:         ctx.GlobalString("user"),
		Args:             argv,
		SaveAs:           uuid,
		IsTTY:            ctx.GlobalBool("interactive"),
		Mounts:           ctx.GlobalStringSlice("mount"),
		ServicedEndpoint: fmt.Sprintf("localhost:%s", api.GetOptionsRPCPort()),
		LogToStderr:      ctx.GlobalBool("logtostderr"),
	}

	config.LogStash.Enable = ctx.GlobalBool("logstash")
	config.LogStash.SettleTime = ctx.GlobalString("logstash-settle-time")

	exitcode := 1
	if exitcode, err = c.driver.RunShell(config, stopChan); err != nil {
		fmt.Fprintln(os.Stderr, err)
	}

	return c.exit(exitcode)
}

func Add(desc string, cmd *exec.Cmd) int64 {
	counter.Lock()
	defer counter.Unlock()

	pid := counter.PID()
	Processes = append(Processes, &Process{
		PID:         pid,
		Description: desc,
		Start:       time.Now(),
		Cmd:         cmd,
	})
	return pid
}

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


Question: Calls `fn` until it returns True, with an exponentially increasing wait time between calls

def exponential_backoff(fn, sleeptime_s_max=30 * 60):
    """"""

    sleeptime_ms = 500
    while True:
        if fn():
            return True
        else:
            print('Sleeping {} ms'.format(sleeptime_ms))
            time.sleep(sleeptime_ms / 1000.0)
            sleeptime_ms *= 2

        if sleeptime_ms / 1000.0 > sleeptime_s_max:
            return False

func (c *Client) WatchRetryStrategy(agentTag names.Tag) (watcher.NotifyWatcher, error) {
	var results params.NotifyWatchResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: agentTag.String()}},
	}
	err := c.facade.FacadeCall("WatchRetryStrategy", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result)
	return w, nil
}

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


Question:
Print statement out. If the supplied message ends with a space or
 tab character, a new line will not be appended.

 @example
   say("Simple things.", color: :red)

 @param [String] message

 @return [String]

 @api public

def say(message = '', options = {})
      message = message.to_s
      return if message.empty?

      statement = Statement.new(self, options)
      statement.call(message)
    end

def send_command_return_multilines(self, command, *arguments):

        return self.api.send_command_return_multilines(self, command, *arguments)

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


Question: // tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout.

func tryDialPipe(ctx context.Context, path *string) (syscall.Handle, error) {
	for {
		select {
		case <-ctx.Done():
			return syscall.Handle(0), ctx.Err()
		default:
			h, err := createFile(*path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
			if err == nil {
				return h, nil
			}
			if err != cERROR_PIPE_BUSY {
				return h, &os.PathError{Err: err, Op: "open", Path: *path}
			}
			// Wait 10 msec and try again. This is a rather simplistic
			// view, as we always try each 10 milliseconds.
			time.Sleep(time.Millisecond * 10)
		}
	}
}

def visit_Call(self, node, **kwargs):

        lineNum = node.lineno - 1
        # Function calls have one Doxygen-significant special case:  interface
        # implementations.
        match = AstWalker.__implementsRE.match(self.lines[lineNum])
        if match:
            self.lines[lineNum] = '{0}## @implements {1}{2}{0}{3}{2}'.format(
                match.group(1), match.group(2), linesep,
                self.lines[lineNum].rstrip())
            if self.options.debug:
                stderr.write("# Implements {0}{1}".format(match.group(1),
                                                          linesep))
        # Visit any contained nodes.
        self.generic_visit(node, containingNodes=kwargs['containingNodes'])

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


Question: // Retrieve Members assigned to load balancer.

func (r Network_LBaaS_LoadBalancer) GetMembers() (resp []datatypes.Network_LBaaS_Member, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_LBaaS_LoadBalancer", "getMembers", nil, &r.Options, &resp)
	return
}

protected function registerBindings(Application $app) {
        $app->bind('bitbucket.connection', function ($app) {
            $manager = $app['bitbucket'];
            return $manager->connection();
        });
        $app->alias('bitbucket.connection', Api::class);
    }

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


Question:
Outputs the pieces as a snak case string.

@return string
The resulting string.

public function snake() {
    if ($this->areTitleCase) {
      foreach ($this->pieces as &$piece) {
        if (preg_match('@^[[:upper:]]+$@', $piece)) {
          // Leave an entirely uppercase piece alone.
          continue;
        }

        $piece = lcfirst($piece);
      }
    }

    return implode('_', $this->pieces);
  }

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: FileBackedMemoryGraphStore

public void commit(ICommitChanges changes, boolean incrementVersions, Runnable r) {
        beginWrite();

        try {
            checkForConcurrentModifications(changes, incrementVersions);

            saveChanges(changes);

            if (r != null) {
                r.run();
            }
        } finally {
            endWrite();
        }
    }

public function getFiles($ids)
    {
        settype($ids, 'array');

        $libraries = $this->getList();
        $sorted = $this->graph->sort($ids, $libraries);

        if (empty($sorted)) {
            return array();
        }

        return $this->prepareFiles($sorted, $libraries);
    }

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


Question:
<p>
The names of the containers.
</p>

@param containers
The names of the containers.

public void setContainers(java.util.Collection<Container> containers) {
        if (containers == null) {
            this.containers = null;
            return;
        }

        this.containers = new java.util.ArrayList<Container>(containers);
    }

protected Parameter[] createDefaultParameters(Class[] parameters) {
		Parameter[] componentParameters = new Parameter[parameters.length];
		for (int i = 0; i < parameters.length; i++) {
			componentParameters[i] = ComponentParameter.DEFAULT;
		}
		return componentParameters;
	}

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


Question:
// IsDownloadDeclinedError indicates that the smudge operation should not download.
// TODO: I don't really like using errors to control that flow, it should be refactored.

func IsDownloadDeclinedError(err error) bool {
	if e, ok := err.(interface {
		DownloadDeclinedError() bool
	}); ok {
		return e.DownloadDeclinedError()
	}
	if parent := parentOf(err); parent != nil {
		return IsDownloadDeclinedError(parent)
	}
	return false
}

func (c oauthClient) DeleteTask(task wl.Task) error {
	url := fmt.Sprintf(
		"%s/tasks/%d?revision=%d",
		c.apiURL,
		task.ID,
		task.Revision,
	)

	req, err := c.newDeleteRequest(url)
	if err != nil {
		return err
	}

	resp, err := c.do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusNoContent)
	}

	return nil
}

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