Question:
Converts {@link DMatrixRBlock} into {@link DMatrixRMaj}

@param src Input matrix.
@param dst Output matrix.  If null a new matrix will be declared.
@return Converted matrix.

public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst ) {
        if( dst != null ) {
            dst.reshape(src.getNumRows(),src.getNumCols());
        } else {
            dst = new DMatrixRMaj(src.numRows,src.numCols);
        }

        for( int i = 0; i < src.numRows; i += src.blockLength ) {
            int blockHeight = Math.min( src.blockLength , src.numRows - i);

            for( int j = 0; j < src.numCols; j += src.blockLength ) {
                int blockWidth = Math.min( src.blockLength , src.numCols - j);

                int indexSrc = i*src.numCols + blockHeight*j;
                int indexDstRow = i*dst.numCols + j;

                for( int k = 0; k < blockHeight; k++ ) {
                    System.arraycopy(src.data,indexSrc,dst.data,indexDstRow,blockWidth);
                    indexSrc += blockWidth;
                    indexDstRow += dst.numCols;
                }
            }
        }

        return dst;
    }

private Class<?> convertType(Class<?> old)
   {
      if (Boolean.class.equals(old))
      {
         return boolean.class;
      }
      else if (boolean.class.equals(old))
      {
         return Boolean.class;
      }
      else if (Byte.class.equals(old))
      {
         return byte.class;
      }
      else if (byte.class.equals(old))
      {
         return Byte.class;
      }
      else if (Short.class.equals(old))
      {
         return short.class;
      }
      else if (short.class.equals(old))
      {
         return Short.class;
      }
      else if (Integer.class.equals(old))
      {
         return int.class;
      }
      else if (int.class.equals(old))
      {
         return Integer.class;
      }
      else if (Long.class.equals(old))
      {
         return long.class;
      }
      else if (long.class.equals(old))
      {
         return Long.class;
      }
      else if (Float.class.equals(old))
      {
         return float.class;
      }
      else if (float.class.equals(old))
      {
         return Float.class;
      }
      else if (Double.class.equals(old))
      {
         return double.class;
      }
      else if (double.class.equals(old))
      {
         return Double.class;
      }
      else if (Character.class.equals(old))
      {
         return char.class;
      }
      else if (char.class.equals(old))
      {
         return Character.class;
      }

      return null;
   }

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


Question:
/*
(non-Javadoc)

@see net.rubyeye.xmemcached.MemcachedClient#get(java.lang.String)

@SuppressWarnings("unchecked")
  public final <T> T get(final String key)
      throws TimeoutException, InterruptedException, MemcachedException {
    return (T) this.get(key, this.opTimeout);
  }

def check_eyaml_data(name, val)
      error = nil
      if val.is_a? String
        err = check_eyaml_blob(val)
        error = "Key #{name} #{err}" if err
      elsif val.is_a? Array
        val.each_with_index do |v, idx|
          error = check_eyaml_data("#{name}[#{idx}]", v)
          break if error
        end
      elsif val.is_a? Hash
        val.each do |k,v|
          error = check_eyaml_data("#{name}['#{k}']", v)
          break if error
        end
      end
      error
    end

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


Question:
Edit a page contents.

@param int $pageid The page ID.
@param string $content Page contents.
@param int $section Section to be edited.
@return array of warnings and page data.
@since Moodle 3.1

public static function edit_page($pageid, $content, $section = null) {
        global $USER;

        $params = self::validate_parameters(self::edit_page_parameters(),
                                            array(
                                                'pageid' => $pageid,
                                                'content' => $content,
                                                'section' => $section
                                            )
            );
        $warnings = array();

        // Get wiki page.
        if (!$page = wiki_get_page($params['pageid'])) {
            throw new moodle_exception('incorrectpageid', 'wiki');
        }

        // Get wiki instance.
        if (!$wiki = wiki_get_wiki_from_pageid($params['pageid'])) {
            throw new moodle_exception('incorrectwikiid', 'wiki');
        }

        // Get subwiki instance.
        if (!$subwiki = wiki_get_subwiki($page->subwikiid)) {
            throw new moodle_exception('incorrectsubwikiid', 'wiki');
        }

        // Permission validation.
        $cm = get_coursemodule_from_instance('wiki', $wiki->id, $wiki->course);
        $context = context_module::instance($cm->id);
        self::validate_context($context);

        if (!wiki_user_can_edit($subwiki)) {
            throw new moodle_exception('cannoteditpage', 'wiki');
        }

        if (wiki_is_page_section_locked($page->id, $USER->id, $params['section'])) {
            throw new moodle_exception('pageislocked', 'wiki');
        }

        // Save content.
        if (!is_null($params['section'])) {
            $version = wiki_get_current_version($page->id);
            $content = wiki_parser_proxy::get_section($version->content, $version->contentformat, $params['section'], false);
            if (!$content) {
                throw new moodle_exception('invalidsection', 'wiki');
            }

            $save = wiki_save_section($page, $params['section'], $params['content'], $USER->id);
        } else {
            $save = wiki_save_page($page, $params['content'], $USER->id);
        }

        wiki_delete_locks($page->id, $USER->id, $params['section']);

        if (!$save) {
            throw new moodle_exception('savingerror', 'wiki');
        }

        $result = array();
        $result['pageid'] = $page->id;
        $result['warnings'] = $warnings;
        return $result;
    }

function updateMeta (args) {
    // data for new revision
    var data
    // check whether access is allowed
    if (!args.allow) {
        // get global access control instance
        var accessControl = ImmutableAccessControl.getGlobal()
        // bulid args for access check
        var allowArgs = {
            action: 'update',
            model: this.model.name,
            scope: this.scope,
            session: args.session || this.session,
        }
        // get name of access id column for model
        var accessIdName = this.model.accessIdName
        // check access for update
        var allow = accessControl.allowModel(allowArgs)
        // access id value being set in update if any
        var updateAccessId
        // access id set in args
        if (defined(args[accessIdName])) {
            updateAccessId = args[accessIdName]
        }
        // access id is set in data
        else if (defined(args.data) && args.data !== null && defined(args.data[accessIdName])) {
            updateAccessId = args.data[accessIdName]
        }
        // if access id is being set and does not match current access id then
        // change ownership permission is required as well
        if (defined(updateAccessId) && updateAccessId !== this.accessId) {
            allowArgs.action = 'chown'
            // checked allowed
            allow = accessControl.allowModel(allowArgs)
        }
        // throw access denied error if not allowed
        if (!allow) {
            httpError(403, null, accessControl.audit)
        }
    }
    // if data was passed in args then merge into existing data - if data
    // is set to null then object will be emptied
    if (defined(this.data) && args.data !== null) {
        // if data is being set check
        if (defined(args.data)) {
            // map of updated firstOnly conlumns
            var updateColumns = {}
            // check firstOnly and immutable for extra columns
            _.each(this.model.extraColumns, (spec, name) => {
                // if property is immutable do not allow value to change
                if (spec.immutable && defined(this.data[name]) && (defined(args.data[name]) || args.merge === false)) {
                    this.assert(args.data[name] === this.data[name], `cannot modify immutable property ${name}`)
                }
                // if property is set on first insert only and it has changed
                // then add to list to update
                if (spec.firstOnly && args.data[name] !== undefined && args.data[name] !== this.data[name]) {
                    // and to map of firstOnly columns to update
                    updateColumns[name] = true
                }
            })
        }
        // if merge is disabled then overwrite existing data
        if (args.merge === false) {
            data = args.data
        }
        // merge update args to existing data by default
        else {
            // create clone of existing object data to merge update into
            data = _.cloneDeep(this.data)
            // merge update data into existing data
            deepExtend(data, args.data)
        }
    }
    // args for create
    var createArgs = {
        // use accountId from original object unless accountId in args
        accountId: args.accountId || this.accountId,
        // skip create access check since update is allowed
        allow: true,
        // object data
        data: data,
        // set original id from current instance
        originalId: this.originalId,
        // id of this instance is parentId for revision
        parentId: this.id,
        // use session from this instance unless set in args
        session: args.session || this.session,
        // map of firstOnly columns to update
        updateColumns: updateColumns,
        // perform validation
        validate: args.validate,
    }
    // if object does not have data then add any extra columns directly to args
    if (!defined(this.data)) {
        // check firstOnly and immutable for extra columns
        _.each(this.model.extraColumns, (spec, name) => {
            // if property is immutable do not allow value to change
            if (spec.immutable && defined(this[name] && defined(args[name]))) {
                this.assert(args[name] === this.data[name], `cannot modify immutable property ${name}`)
            }
            // if property is set on first insert only and it has changed
            // then add to list to update
            if (spec.firstOnly && defined(args[name]) && args[name] !== this[name]) {
                // and to map of firstOnly columns to update
                updateColumns[name] = true
            }
            // set value from args
            if (defined(args[name])) {
                createArgs[name] = args[name]
            }
            // set value from current instance unless column is firstOnly
            else if (!spec.firstOnly) {
                createArgs[name] = this[name]
            }
        })
    }
    // if delete arg is set use
    if (typeof args.delete === 'boolean') {
        createArgs.d = args.delete
    }
    // otherwise use current value
    else {
        createArgs.d = this.isDeleted ? true : false
    }
    // attempt to create new instance
    return this.model.createMeta(createArgs)
    // catch errors
    .catch(err => {
        // if force is not set then throw error
        if (!args.force) {
            throw err
        }
        // only force retry on revision conflicts not other errors
        if (!this.isConflictError(err)) {
            throw err
        }
        // should retry now so make sure that retry counter is set
        if (!args.retry) {
            args.retry = 0
        }
        // increment retry counter
        args.retry++
        // do not retry if limit exceeded
        if (args.retry > MAX_RETRY) {
            throw err
        }
        // get current instance
        return this.model.query({
            current: 1,
            limit: 1,
            session: createArgs.session,
            where: {originalId: createArgs.originalId},
        })
        .then(current => {
            // call updateMeta on the current instance with the same args
            // and retry incremented
            return current.updateMeta(args)
        })
    })
}

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


Question: Marshall the given parameter object.

public void marshall(DescribeTrustedAdvisorCheckSummariesRequest describeTrustedAdvisorCheckSummariesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeTrustedAdvisorCheckSummariesRequest.getCheckIds(), CHECKIDS_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:
Return the node corresponding with name `nodename`

        :params nodename: Name of the node
        :type nodename: str

def get_node_by_name(self, nodename):

        nodes = dict((n.name, n) for n in self.get_all_nodes())
        try:
            return nodes[nodename]
        except KeyError:
            raise NodeNotFound("Node %s not found" % nodename)

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

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


Question:
Are the aliase valid?<p>

@return true if ok

boolean isValidAliase() {

        boolean ret = true;

        for (I_CmsEditableGroupRow row : m_aliasGroup.getRows()) {
            FormLayout layout = (FormLayout)(row.getComponent());
            TextField field = (TextField)layout.getComponent(0);
            ret = ret & field.isValid();
        }
        return ret;
    }

public function setAllowReview($allowReview)
    {
        if (is_bool($allowReview)) {
            $this->allowReview = $allowReview;
        } else {
            $msg = "AllowReview must be a boolean, '" . gettype($allowReview) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question: // CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'nl_NL'

func (nl *nl_NL) CardinalPluralRule(num float64, v uint64) locales.PluralRule {

	n := math.Abs(num)
	i := int64(n)

	if i == 1 && v == 0 {
		return locales.PluralRuleOne
	}

	return locales.PluralRuleOther
}

protected function _rule($rule, $error_message = null) {
        if (!$this->field) {
            throw new \Exception('Not specified fieldname');
        }
        $this->rules[$this->field][$rule] = $rule;
        if ($error_message) {
            $this->message($rule, $error_message, $this->field);
        }

        return $this;
    }

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


Question:
{@inheritDoc}

@param config {@inheritDoc}
@throws InitializationException {@inheritDoc}
@throws InterruptedException {@inheritDoc}

@Override
    public void init(final CONFIG config) throws InitializationException, InterruptedException {
        synchronized (CONFIG_LOCK) {
            try {
                if (config == null) {
                    throw new NotAvailableException("config");
                }
                currentScope = detectScope(config);
                try {
                    applyConfigUpdate(config);
                } catch (CouldNotPerformException ex) {
                    ExceptionPrinter.printHistory("Could not apply config update for " + this, ex, logger);
                    try {
                        if (JPService.getProperty(JPTestMode.class).getValue()) {
                            throw new FatalImplementationErrorException("Could not apply config update for " + this, this, ex);
                        }
                    } catch (JPNotAvailableException ex1) {
                        // to nothing if property could not be resovled.
                    }
                }
                super.init(currentScope);
            } catch (CouldNotPerformException ex) {
                throw new InitializationException(this, ex);
            }
        }
    }

private function dumpValue($value, $interpolate = true)
    {
        if (is_array($value)) {
            $code = array();
            foreach ($value as $k => $v) {
                $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
            }

            return sprintf('array(%s)', implode(', ', $code));
        } elseif ($value instanceof Definition) {
            if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
                return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate);
            }
            if (count($value->getMethodCalls()) > 0) {
                throw new RuntimeException('Cannot dump definitions which have method calls.');
            }
            if (null !== $value->getConfigurator()) {
                throw new RuntimeException('Cannot dump definitions which have a configurator.');
            }

            $arguments = array();
            foreach ($value->getArguments() as $argument) {
                $arguments[] = $this->dumpValue($argument);
            }

            if (null !== $value->getFactory()) {
                $factory = $value->getFactory();

                if (is_string($factory)) {
                    return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments));
                }

                if (is_array($factory)) {
                    if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) {
                        throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a'));
                    }

                    if (is_string($factory[0])) {
                        return sprintf('%s::%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory[0])), $factory[1], implode(', ', $arguments));
                    }

                    if ($factory[0] instanceof Definition) {
                        return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($factory[0]), $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
                    }

                    if ($factory[0] instanceof Reference) {
                        return sprintf('%s->%s(%s)', $this->dumpValue($factory[0]), $factory[1], implode(', ', $arguments));
                    }
                }

                throw new RuntimeException('Cannot dump definition because of invalid factory');
            }

            $class = $value->getClass();
            if (null === $class) {
                throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
            }

            return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments));
        } elseif ($value instanceof Variable) {
            return '$'.$value;
        } elseif ($value instanceof Reference) {
            if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) {
                return $this->dumpValue($this->referenceVariables[$id], $interpolate);
            }

            return $this->getServiceCall((string) $value, $value);
        } elseif ($value instanceof Expression) {
            return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container'));
        } elseif ($value instanceof Parameter) {
            return $this->dumpParameter($value);
        } elseif (true === $interpolate && is_string($value)) {
            if (preg_match('/^%([^%]+)%$/', $value, $match)) {
                // we do this to deal with non string values (Boolean, integer, ...)
                // the preg_replace_callback converts them to strings
                return $this->dumpParameter(strtolower($match[1]));
            } else {
                $replaceParameters = function ($match) {
                    return "'.".$this->dumpParameter(strtolower($match[2])).".'";
                };

                $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));

                return $code;
            }
        } elseif (is_object($value) || is_resource($value)) {
            throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
        } else {
            return $this->export($value);
        }
    }

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


Question:
Ensure FTP connection.

@throws ServerException

protected function connect()
    {
        if (!empty($this->conn)) {
            return;
        }

        if (!extension_loaded('ftp')) {
            throw new ServerException(
                "Unable to initialize ftp storage server, extension 'ftp' not found"
            );
        }

        $conn = ftp_connect(
            $this->options['host'],
            $this->options['port'],
            $this->options['timeout']
        );

        if (empty($conn)) {
            throw new ServerException(
                "Unable to connect to remote FTP server '{$this->options['host']}'"
            );
        }

        if (!ftp_login($conn, $this->options['username'], $this->options['password'])) {
            throw new ServerException(
                "Unable to authorize on remote FTP server '{$this->options['host']}'"
            );
        }

        if (!ftp_pasv($conn, $this->options['passive'])) {
            throw new ServerException(
                "Unable to set passive mode at remote FTP server '{$this->options['host']}'"
            );
        }

        $this->conn = $conn;
    }

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)

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


Question:
Get a copy of the language/locale priority list

@return a copy of the language/locale priority list.
@hide draft / provisional / internal are hidden on Android

public List<ULocale> getLocales() {
        List<ULocale> result;
        if (locales == null) {
            result = guessLocales();
        } else {
            result = new ArrayList<ULocale>();
            result.addAll(locales);
        }
        return result;
    }

def render_source(output_dir, package_spec):

    path, name = package_spec.filepath
    destination_filename = '%s/%s.proto' % (output_dir, name)
    pb_template = JENV.get_template(MESSAGES_TEMPLATE_NAME)
    includes = [include[:-5] if include.endswith('.yaml') else include for include in package_spec.includes]
    if 'types' in includes:
        includes.remove('types')
    with open(destination_filename, 'w') as f:
        f.write(pb_template.render(
            name=name,
            package=package_spec.identifier,
            messages=package_spec.definitions,
            includes=includes,
            description=package_spec.description,
        ))

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


Question: Return the syllable and tone of an IPA syllable.

def _parse_ipa_syllable(unparsed_syllable):
    """"""
    ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS},
                         unparsed_syllable)
    if not ipa_tone:
        syllable, tone = unparsed_syllable, '5'
    else:
        for tone_number, tone_mark in _IPA_TONES.items():
            if ipa_tone.group() == tone_mark:
                tone = tone_number
                break
        syllable = unparsed_syllable[0:ipa_tone.start()]
    return syllable, tone

def _tokens_from_patsy(node):

    for n in node.args:
        for t in _tokens_from_patsy(n):
            yield t

    if node.token:
        yield node.token

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


Question:
Returns the last-modified time from the remote server. Assumes the remote server knows how to
 do this. Returns the epoch if the remote is dense.

def web_modification_time(local_url)
      resp = nil
      Net::HTTP.start(local_url.host, 80) do |http|
        resp = http.head(local_url.path)
      end
      resp['Last-Modified'].nil? ? Time.at(0) : Time.parse(resp['Last-Modified'])
    end

def git_status_all_repos(cat, hard=True, origin=False, clean=True):

    log = cat.log
    log.debug("gitter.git_status_all_repos()")

    all_repos = cat.PATHS.get_all_repo_folders()
    for repo_name in all_repos:
        log.info("Repo in: '{}'".format(repo_name))
        # Get the initial git SHA
        sha_beg = get_sha(repo_name)
        log.debug("Current SHA: '{}'".format(sha_beg))

        log.info("Fetching")
        fetch(repo_name, log=cat.log)

        git_comm = ["git", "status"]
        _call_command_in_repo(
            git_comm, repo_name, cat.log, fail=True, log_flag=True)

        sha_end = get_sha(repo_name)
        if sha_end != sha_beg:
            log.info("Updated SHA: '{}'".format(sha_end))

    return

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


Question:
Whether the URI is a absolute-path reference.

A relative reference that begins with a single slash character is termed an absolute-path reference.

@param UriInterface $uri

@return bool
@link https://tools.ietf.org/html/rfc3986#section-4.2

public static function isAbsolutePathReference(UriInterface $uri)
    {
        $uriPath = $uri->getPath();
        return $uri->getScheme() === ''
            && $uri->getAuthority() === ''
            && isset($uriPath[0])
            && $uriPath[0] === '/';
    }

def reset (self):

        # self.url is constructed by self.build_url() out of base_url
        # and (base_ref or parent) as absolute and normed url.
        # This the real url we use when checking so it also referred to
        # as 'real url'
        self.url = None
        # a splitted version of url for convenience
        self.urlparts = None
        # the scheme, host, port and anchor part of url
        self.scheme = self.host = self.port = self.anchor = None
        # the result message string and flag
        self.result = u""
        self.has_result = False
        # valid or not
        self.valid = True
        # list of warnings (without duplicates)
        self.warnings = []
        # list of infos
        self.info = []
        # content size
        self.size = -1
        # last modification time of content in HTTP-date format as specified in RFC2616 chapter 3.3.1
        self.modified = None
        # download time
        self.dltime = -1
        # check time
        self.checktime = 0
        # connection object
        self.url_connection = None
        # data of url content,  (data == None) means no data is available
        self.data = None
        # cache url is set by build_url() calling set_cache_url()
        self.cache_url = None
        # extern flags (is_extern, is_strict)
        self.extern = None
        # flag if the result should be cached
        self.caching = True
        # title is either the URL or parsed from content
        self.title = None
        # flag if content should be checked or not
        self.do_check_content = True
        # MIME content type
        self.content_type = u""
        # URLs seen through redirections
        self.aliases = []

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


Question:
Validate that the given name match a notation declaration.
           - [ VC: Notation Declared ]

def validateNotationUse(self, ctxt, notationName):

        if ctxt is None: ctxt__o = None
        else: ctxt__o = ctxt._o
        ret = libxml2mod.xmlValidateNotationUse(ctxt__o, self._o, notationName)
        return ret

def _get_vqa_v2_annotations(directory,
                            annotation_url,
                            annotation_filename="vqa_v2.tar.gz"):
  """"""
  annotation_file = generator_utils.maybe_download_from_drive(
      directory, annotation_filename, annotation_url)
  with tarfile.open(annotation_file, "r:gz") as annotation_tar:
    annotation_tar.extractall(directory)

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


Question:
/* (non-Javadoc)
@see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)

@Override
    protected void doHandle(CommandContext ctx) throws CommandFormatException {

        Batch batch = ctx.getBatchManager().getActiveBatch();
        if(batch == null) {
            throw new CommandFormatException("No active batch.");
        }
        batch.clear();
    }

def show_backends(socket=DEFAULT_SOCKET_URL):
    '''

    '''
    ha_conn = _get_conn(socket)
    ha_cmd = haproxy.cmds.showBackends()
    return ha_conn.sendCmd(ha_cmd)

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


Question:
Counts whether the computed key value is already present
           in the memoization dictionary (a hit) or not (a miss).

def count(self, *args, **kw):

        obj = args[0]
        try:
            memo_dict = obj._memo[self.method_name]
        except KeyError:
            self.miss = self.miss + 1
        else:
            key = self.keymaker(*args, **kw)
            if key in memo_dict:
                self.hit = self.hit + 1
            else:
                self.miss = self.miss + 1

def do_shutdown(self, restart):

        print("in shutdown function")
        if self.hist_file:
            with open(self.hist_file, 'wb') as fid:
                data = '\n'.join(self.hist_cache[-self.max_hist_cache:])
                fid.write(data.encode('utf-8'))
        if self.mva:
            self.mva._endsas()
            self.mva = None
        if restart:
            self.Print("Restarting kernel...")
            self.reload_magics()
            self.restart_kernel()
            self.Print("Done!")
        return {'status': 'ok', 'restart': restart}

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


Question: Returns all methods that this router handles. For {@code OPTIONS *}.

public Set<HttpMethod> allAllowedMethods() {
		if (anyMethodRouter.size() > 0) {
			Set<HttpMethod> ret = new HashSet<HttpMethod>(9);
			ret.add(HttpMethod.CONNECT);
			ret.add(HttpMethod.DELETE);
			ret.add(HttpMethod.GET);
			ret.add(HttpMethod.HEAD);
			ret.add(HttpMethod.OPTIONS);
			ret.add(HttpMethod.PATCH);
			ret.add(HttpMethod.POST);
			ret.add(HttpMethod.PUT);
			ret.add(HttpMethod.TRACE);
			return ret;
		} else {
			return new HashSet<HttpMethod>(routers.keySet());
		}
	}

public function post($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('POST', $pattern, $handler, $requirements, $defaults);
    }

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


Question:
Returns document link for performance issue

@param string $issue string describing issue
@param string $name name of issue
@return string issue link pointing to docs page.

public function doc_link($issue, $name) {
        global $CFG, $OUTPUT;

        if (empty($CFG->docroot)) {
            return $name;
        }

        return $OUTPUT->doc_link('report/performance/'.$issue, $name);
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question:
Replace placeholders in the given messagePattern with arguments.

@param messagePattern the message pattern containing placeholders.
@param arguments      the arguments to be used to replace placeholders.
@return the formatted message.

static String format(final String messagePattern, final Object[] arguments) {
        final StringBuilder result = new StringBuilder();
        final int argCount = arguments == null ? 0 : arguments.length;
        formatMessage(result, messagePattern, arguments, argCount);
        return result.toString();
    }

def _DoSubstitute(args, context, callback, trace):

    name, formatters = args

    if name is None:
        value = context.Root()  # don't use the cursor
    else:
        try:
            value = context.Lookup(name)
        except TypeError as e:
            raise EvaluationError(
                'Error evaluating %r in context %r: %r' % (name, context, e))

    last_index = len(formatters) - 1
    for i, (f, args, formatter_type) in enumerate(formatters):
        try:
            if formatter_type == TEMPLATE_FORMATTER:
                template = f.Resolve(context)
                if i == last_index:
                    # In order to keep less template output in memory, we can just let the
                    # other template write to our callback directly, and then stop.
                    template.execute(value, callback, trace=trace)
                    return  # EARLY RETURN
                else:
                    # We have more formatters to apply, so explicitly construct 'value'
                    tokens = []
                    template.execute(value, tokens.append, trace=trace)
                    value = JoinTokens(tokens)

            elif formatter_type == ENHANCED_FUNC:
                value = f(value, context, args)

            elif formatter_type == SIMPLE_FUNC:
                value = f(value)

            else:
                assert False, 'Invalid formatter type %r' % formatter_type

        except (KeyboardInterrupt, EvaluationError):
            # Don't "wrap" recursive EvaluationErrors
            raise

        except Exception as e:
            if formatter_type == TEMPLATE_FORMATTER:
                raise  # in this case we want to see the original exception
            raise EvaluationError(
                'Formatting name %r, value %r with formatter %s raised exception: %r '
                '-- see e.original_exc_info' % (name, value, f, e),
                original_exc_info=sys.exc_info())

    # TODO: Require a string/unicode instance here?
    if value is None:
        raise EvaluationError('Evaluating %r gave None value' % name)
    callback(value)

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


Question:
/*
Gets hadoop tokens for a user to run mapred/hive jobs on a secured cluster

@Override
  public void prefetchToken(final File tokenFile, final Props props, final Logger logger)
      throws HadoopSecurityManagerException {
    final String userToProxy = props.getString(JobProperties.USER_TO_PROXY);

    logger.info("Getting hadoop tokens based on props for " + userToProxy);
    doPrefetch(tokenFile, props, logger, userToProxy);
  }

def login_open_sheet(oauth_key_file, spreadsheet):
    """"""
    try:
        scope =  ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope)
        gc = gspread.authorize(credentials)
        worksheet = gc.open(spreadsheet).sheet1
        return worksheet
    except Exception as ex:
        print('Unable to login and get spreadsheet.  Check OAuth credentials, spreadsheet name, and make sure spreadsheet is shared to the client_email address in the OAuth .json file!')
        print('Google sheet login failed with error:', ex)
        sys.exit(1)

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


Question:
Multiplies the current value by a given number.

@param $number

@return $this

public function multiply($number = null)
    {
        if ($number === null) {
            $this->internalSetOperationModeWithHistory('multiply');
        } elseif ($number instanceof Closure) {
            $this->internalSetOperationModeWithHistory('multiply');
            return $this->group($number);
        } else {
            $this->performOperationOnExpressionEngine('multiply', $number);
        }

        return $this;
    }

public JcNumber mult(JcNumber val) {
		JcNumber ret = new JcNumber(val, this, OPERATOR.Number.MULT);
		QueryRecorder.recordInvocationConditional(this, "mult", ret, QueryRecorder.placeHolder(val));
		return ret;
	}

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


Question: Sets column width and marks grid as changed

def set_col_width(self, col, width):
        """"""

        # Mark content as changed
        post_command_event(self.main_window, self.ContentChangedMsg)

        tab = self.grid.current_table

        self.code_array.set_col_width(col, tab, width)
        self.grid.SetColSize(col, width)

def flag(self, context):

        lrow, urow = MS.row_extents(context)

        flag = self._manager.ordered_main_table.getcol(
            MS.FLAG, startrow=lrow, nrow=urow-lrow)

        return flag.reshape(context.shape).astype(context.dtype)

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


Question:
Execute a PATCH method request

@param string $url
@param array $data
@param string $dataType
@return $this

public function patch($url, $data = array(), $dataType = null)
    {
        return $this->processMethod($url, $data, $dataType, 'PATCH');
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

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


Question:
Get Subtitle for the specific trackID.

@param trackID
@return
@throws MusixMatchException

public Subtitle getSubtitle(int trackID) throws MusixMatchException {
        Subtitle subtitle = null;
        SubtitleGetMessage message = null;
        Map<String, Object> params = new HashMap<String, Object>();

        params.put(Constants.API_KEY, apiKey);
        params.put(Constants.TRACK_ID, new String("" + trackID));

        String response = null;

        response = MusixMatchRequest.sendRequest(Helper.getURLString(
				Methods.TRACK_SUBTITLE_GET, params));

        Gson gson = new Gson();

        try {
            message = gson.fromJson(response, SubtitleGetMessage.class);
        } catch (JsonParseException jpe) {
            jpe.printStackTrace();
            handleErrorResponse(response);
        }

        subtitle = message.getContainer().getBody().getSubtitle();

        return subtitle;
    }

def set_cover_video_for_playlist(self, access_token, playlist_id,
                                     video_id):

        url = 'https://openapi.youku.com/v2/playlists/video/setcover.json'
        data = {
            'client_id': self.client_id,
            'access_token': access_token,
            'playlist_id': playlist_id,
            'video_id': video_id
        }
        r = requests.post(url, data=data)
        check_error(r)
        return r.json()['id']

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


Question:
Removes all intervals overlapping the given point or range.

        Completes in O((r+m)*log n) time, where:
          * n = size of the tree
          * m = number of matches
          * r = size of the search range (this is 1 for a point)

def remove_overlap(self, begin, end=None):

        hitlist = self.at(begin) if end is None else self.overlap(begin, end)
        for iv in hitlist:
            self.remove(iv)

def borrow_from_next_sibling(next_node)
      if next_node.keys.length - 1 > min_keys
        # The next sibling now has a new lead key that requires the branch key
        # to be updated in the parent node.
        index = next_node.parent.search_node_index(next_node) - 1

        @tree.node_cache.insert(self)
        @tree.node_cache.insert(next_node.get_node)
        @tree.node_cache.insert(next_node.parent.get_node)
        if @is_leaf
          # Move the first key of the next node to the end of the this node
          @keys << next_node.keys.shift
          # Register the new lead key of next_node with its parent
          next_node.parent.keys[index] = next_node.keys.first
          # Move the first value of the next node to the end of this node
          @values << next_node.values.shift
        else
          # For branch nodes we need to get the lead key from the parent of
          # next_node.
          @keys << next_node.parent.keys[index]
          # The old lead key of next_node becomes the branch key in the parent
          # of next_node. And the keys of next_node are shifted.
          next_node.parent.keys[index] = next_node.keys.shift
          # Move the first child of the next node to the end of this node
          @children << (node = next_node.children.shift)
          node.parent = link(self)
        end

        return true
      end

      false
    end

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


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

@Override
	public EClass getIfcImageTexture() {
		if (ifcImageTextureEClass == null) {
			ifcImageTextureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(317);
		}
		return ifcImageTextureEClass;
	}

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: // PeekRune returns the next rune witohut consuming it

func (p *Lexer) PeekRune() (rune, error) {
	r, err := p.Rune()

	if err != nil {
		return 0, nil
	}

	return r, p.UnreadRune()
}

func (b *boundManager) pinOp(leaseName string, entity string, ch chan pin) error {
	return errors.Trace(pin{
		leaseKey: b.leaseKey(leaseName),
		entity:   entity,
		response: make(chan error),
		stop:     b.manager.catacomb.Dying(),
	}.invoke(ch))
}

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


Question:
Creates a relation item list wrapped in a field set and appends it to the dialog panel.<p>

@param label the list label

@return the list

private CmsList<CmsListItem> createList(String label) {

        CmsFieldSet fieldset = new CmsFieldSet();
        CmsScrollPanel scrollPanel = GWT.create(CmsScrollPanel.class);
        CmsList<CmsListItem> list = new CmsList<CmsListItem>();
        scrollPanel.add(list);
        m_scrollPanels.add(scrollPanel);
        fieldset.getElement().getStyle().setMarginTop(10, Style.Unit.PX);
        scrollPanel.getElement().getStyle().setHeight(CmsResourceInfoDialog.SCROLLPANEL_HEIGHT, Style.Unit.PX);
        fieldset.setLegend(label);
        fieldset.add(scrollPanel);
        m_panel.add(fieldset);
        return list;
    }

def add(self, child):

        if isinstance(child, Run):
            self.add_run(child)
        elif isinstance(child, Record):
            self.add_record(child)
        elif isinstance(child, EventRecord):
            self.add_event_record(child)
        elif isinstance(child, DataDisplay):
            self.add_data_display(child)
        elif isinstance(child, DataWriter):
            self.add_data_writer(child)
        elif isinstance(child, EventWriter):
            self.add_event_writer(child)
        else:
            raise ModelError('Unsupported child element')

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


Question: ZAP: show the last selected panel

public void showDialog(boolean showRoot, String panel) {
        expandRoot();

        try {
            DefaultMutableTreeNode node = null;
            if (panel != null) {
                node = getTreeNodeFromPanelName(panel);
            }

            if (node == null) {
                if (nameLastSelectedPanel != null) {
                    node = getTreeNodeFromPanelName(nameLastSelectedPanel);

                } else if (showRoot) {
                    node = (DefaultMutableTreeNode) getTreeModel().getRoot();

                } else if (((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildCount() > 0) {
                    node = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildAt(0);
                }
            }

            if (node != null) {
                showParamPanel(node.toString());
            }

        } catch (Exception e) {
            // ZAP: log errors
            log.error(e.getMessage(), e);
        }
    }

protected String endLayerModules(HttpServletRequest request, Object arg) {
		// Save module list in request attribute for processing during {@code END_RESPONSE}
		request.setAttribute(ADD_REQUIRE_DEPS_REQATTRNAME, arg);
		return "}});require({cache:{}});"; //$NON-NLS-1$
	}

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


Question:
Creates a DOM element

@private
@param {string} tag The element's tag name
@return {Node}

function(tag) {
		if (!tag) {
			// create a document fragment to hold multiple-root elements
			if (document.createDocumentFragment) {
				return document.createDocumentFragment();
			}

			tag = '';

		} else if (tag.charAt(0) === '!') {
			return document.createComment(tag === '!' ? '' : tag.substr(1)+' ');
		}

		return document.createElement(tag);
	}

public function seeElementInDOM($selector, $attributes = [])
    {
        $this->enableImplicitWait();
        $els = $this->match($this->getBaseElement(), $selector);
        $els = $this->filterByAttributes($els, $attributes);
        $this->disableImplicitWait();
        $this->assertNotEmpty($els);
    }

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


Question: helper function to get dataloader

def get_training_data(batch_size):

    return gluon.data.DataLoader(
        CIFAR10(train=True, transform=transformer),
        batch_size=batch_size, shuffle=True, last_batch='discard')

@Override
  public final void retrievePage(final Map<String, Object> pAddParam,
    final IRequestData pRequestData) throws Exception {
    this.isDbgSh = this.logger.getDbgSh(this.getClass())
        && this.logger.getDbgFl() < 7001 && this.logger.getDbgCl() > 7003;
    this.hlpEntitiesPage.retrievePage(pAddParam, pRequestData, this.entitiesMap,
      this.isDbgSh, this.filterFiMaker);
  }

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


Question:
Extracts element at current take position, advances, and signals.
Call only when holding lock.

private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;
        if (++takeIndex == items.length) takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

func (all *assetLruList) MoveToBack(alle *assetLruListElement) {
	if alle.list != all || all.root.prev == alle {
		return
	}
	// see comment in assetLruList.Remove about initialization of l
	all.insert(all.remove(alle), all.root.prev)
}

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


Question:
Return an instance of the NotFoundHandlerInterface.

@throws ContainerExceptionInterface
@throws NotFoundExceptionInterface

private static function invalidRequestHandler(ContainerInterface $container): InvalidRequestHandlerInterface
    {
        if (!$container->has(InvalidRequestHandlerInterface::class)) {
            return new InvalidRequestHandler();
        }

        return $container->get(InvalidRequestHandlerInterface::class);
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
Issue a log message with a level of INFO using {@link java.text.MessageFormat}-style formatting.

@param format the message format string
@param param1 the sole parameter

public void infov(String format, Object param1) {
        if (isEnabled(Level.INFO)) {
            doLog(Level.INFO, FQCN, format, new Object[] { param1 }, null);
        }
    }

def format_message(self, message):

        look = Look(message)
        return look.pretty(display=False)

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


Question: Generates the slide shows based on configuration.

public function generateSlideShows()
    {
        foreach ($this->names as $tag => $name) {
            $this->output->write(sprintf(
                '- <comment>%s</comment> %s ',
                $name,
                str_pad('.', 44 - mb_strlen($name), '.', STR_PAD_LEFT)
            ));

            if (null !== $slideShow = $this->findSlideShowByTag($tag)) {
                $this->output->writeln('already exists.');
                continue;
            }

            /** @var \Ekyna\Bundle\CmsBundle\Entity\SlideShow $slideShow */
            $slideShow = $this->repository->createNew();
            $slideShow
                ->setName($name)
                ->setTag($tag);

            $this->operator->persist($slideShow);

            $this->output->writeln('created.');
        }
    }

public function flash(string $ip, array $request, array $server): void
    {
        $this->isConfigDebug ? print('anti flash') : null;
        $this->log(configDefault('anti/flash', 'log', 'anti', 'flash'), ['ip' => $ip, 'request' => $request, 'server' => $server]);
    }

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.BNG__PGRP_NAME:
				setPGrpName(PGRP_NAME_EDEFAULT);
				return;
			case AfplibPackage.BNG__TRIPLETS:
				getTriplets().clear();
				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:
Template variable getter. Returns country ISO 3

@return string

public function getCountryISO3()
    {
        $oOrder = $this->getOrder();
        if ($oOrder) {
            $oCountry = oxNew(\OxidEsales\Eshop\Application\Model\Country::class);
            $oCountry->load($oOrder->oxorder__oxbillcountryid->value);

            return $oCountry->oxcountry__oxisoalpha3->value;
        }
    }

public function context(ContextInterface $context)
    {
        if (!empty($this->vary)) {
            $this->varyValue = $context->get($this->vary);
        }
    }

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


Question:
Moves node to another ancestor.

@return void

protected function moveNode()
    {
        if ($this->exists) {
            if (is_null($this->closure->ancestor)) {
                $primaryKey = $this->getKey();
                $this->closure->ancestor = $primaryKey;
                $this->closure->descendant = $primaryKey;
                $this->closure->depth = 0;
            }

            if ($this->isDirty($this->getParentIdColumn())) {
                $this->reorderSiblings(true);
                $this->closure->moveNodeTo($this->parent_id);
            }
        }
    }

public Tree<T> addLeaf( T child )
    {
        Tree<T> leaf = new Tree<T>( child );
        leaf.parent = this;
        children.add( leaf );
        return leaf;
    }

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


Question:
/*
(non-Javadoc)

@see org.m2latex.mojo.TexFileUtils#copyLatexSrcToTempDir(java.io.File, java.io.File)

public void copyLatexSrcToTempDir( File texDirectory, File tempDirectory )
        throws MojoExecutionException
    {
        try
        {
            if ( tempDirectory.exists() )
            {
                log.info( "Deleting existing directory " + tempDirectory.getPath() );
                FileUtils.deleteDirectory( tempDirectory );
            }

            log.debug( "Copying TeX source directory (" + texDirectory.getPath() + ") to temporary directory ("
                + tempDirectory + ")" );
            FileUtils.copyDirectory( texDirectory, tempDirectory );
        }
        catch ( IOException e )
        {
            throw new MojoExecutionException( "Failure copying the TeX directory (" + texDirectory.getPath()
                + ") to a temporary directory (" + tempDirectory.getPath() + ").", e );
        }
    }

def upload(cls, path, document_type, is_protocol, description=""):

        file_name = os.path.basename(path)
        mime_type = mimetypes.guess_type(file_name)[0]
        data = base64.b64encode(open(path, 'rb').read())
        temp_uri = str(data, "utf-8")
        #href = "data:{mime_type};base64,{temp_uri}".format(mime_type=mime_type, temp_uri=temp_uri)
        payload = {}
        payload["content_type"] = mime_type
        payload["data"] = temp_uri
        payload["description"] = description
        payload["document_type_id"] = DocumentType(document_type).id
        payload["name"] =  file_name
        payload["is_protocol"] = is_protocol
        cls.post(payload)

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


Question: Use this API to fetch transformprofile resource of given name .

public static transformprofile get(nitro_service service, String name) throws Exception{
		transformprofile obj = new transformprofile();
		obj.set_name(name);
		transformprofile response = (transformprofile) obj.get_resource(service);
		return response;
	}

def get_thumbnail_source(self, obj):

        if hasattr(self, 'thumbnail_field') and self.thumbnail_field:
            return resolve(obj, self.thumbnail_field)

        # try get_list_image, from ListableMixin
        if hasattr(obj, 'get_list_image'):
            return resolve(obj, "get_list_image")

        logger.warning('ThumbnailAdminMixin.thumbnail_field unspecified')
        return None

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


Question:
// parseFormatPictureSet provides a function to parse the format settings of
// the picture with default value.

func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
	format := formatPicture{
		FPrintsWithSheet: true,
		FLocksWithSheet:  false,
		NoChangeAspect:   false,
		OffsetX:          0,
		OffsetY:          0,
		XScale:           1.0,
		YScale:           1.0,
	}
	err := json.Unmarshal(parseFormatSet(formatSet), &format)
	return &format, err
}

func (c *Chat) UnmarshalJSON(data []byte) error {
	s := &struct {
		ID                          int        `json:"id"`
		Type                        string     `json:"type"`
		Title                       string     `json:"title"`
		Username                    string     `json:"username"`
		FirstName                   string     `json:"first_name"`
		LastName                    string     `json:"last_name"`
		Photo                       *ChatPhoto `json:"photo"`
		Description                 string     `json:"description"`
		InviteLink                  string     `json:"invite_link"`
		PinnedMessage               *Message   `json:"pinned_message"`
		StickerSetName              string     `json:"sticker_set_name"`
		AllMembersAreAdministrators bool       `json:"all_members_are_administrators"`
		CanSetStickerSet            bool       `json:"can_set_sticker_set"`
	}{}
	err := json.Unmarshal(data, s)
	if err != nil {
		return err
	}
	*c = Chat{
		ID:                          fmt.Sprint(s.ID),
		Type:                        s.Type,
		Title:                       s.Title,
		Username:                    s.Username,
		FirstName:                   s.FirstName,
		LastName:                    s.LastName,
		Photo:                       s.Photo,
		Description:                 s.Description,
		InviteLink:                  s.InviteLink,
		PinnedMessage:               s.PinnedMessage,
		StickerSetName:              s.StickerSetName,
		AllMembersAreAdministrators: s.AllMembersAreAdministrators,
		CanSetStickerSet:            s.CanSetStickerSet,
	}
	return nil
}

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


Question:
Write a line to a file

@param string $filePointer  File resource to write in
@param array  $dataArray    Data to write out
@param string $delimiter    Field separator
@param string $enclosure    Enclosure

protected function fputcsv($filePointer, $dataArray, $delimiter = ",",   $enclosure = "\"")
  {
    // Build the string
    $string = "";
    // No leading delimiter
    $writeDelimiter = false;
    foreach ($dataArray as $dataElement) {
      // Replaces a double quote with two double quotes
      $dataElement = str_replace("\"", "\"\"", $dataElement);
      // Adds a delimiter before each field (except the first)
      if ($writeDelimiter) {
        $string .= $delimiter;
      }
      // Encloses each field with $enclosure and adds it to the string
      if ($enclosure) {
        $string .= $enclosure . $dataElement . $enclosure;
      } else {
        $string .= $dataElement;
      }
      // Delimiters are used every time except the first.
      $writeDelimiter = true;
    }
    // Append new line
    $string .= "\n";
    // Write the string to the file
    fwrite($filePointer, $string);
  }

public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException
    {
        float[] parameter = this.parameter;
        this.compress(ratio, 1e-3f);

        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile)));
        save(out);
        out.close();

        if (text)
        {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8"));
            TagSet tagSet = featureMap.tagSet;
            for (Map.Entry<String, Integer> entry : featureIdSet)
            {
                bw.write(entry.getKey());
                if (featureIdSet.size() == parameter.length)
                {
                    bw.write("\t");
                    bw.write(String.valueOf(parameter[entry.getValue()]));
                }
                else
                {
                    for (int i = 0; i < tagSet.size(); ++i)
                    {
                        bw.write("\t");
                        bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i]));
                    }
                }
                bw.newLine();
            }
            bw.close();
        }
    }

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


Question:
Validates the entity dict representation

    entity
        Dictionary representation of an entity.
        See ``_get_entity`` docstrings for format.

def _validate_entity(entity):
    '''

    '''

    #Validate entity:
    if entity['type'] == 'cluster':
        schema = ESXClusterEntitySchema.serialize()
    elif entity['type'] == 'vcenter':
        schema = VCenterEntitySchema.serialize()
    else:
        raise ArgumentValueError('Unsupported entity type \'{0}\''
                                 ''.format(entity['type']))
    try:
        jsonschema.validate(entity, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise InvalidEntityError(exc)

def parsePyLintWarnings(warnings):

    warningsDict = {}

    for line in warnings:

        match = re.search(P_PYLINT_ERROR, line)

        if match:
            matchDict = match.groupdict()

            if not warningsDict.get(matchDict["file"]):
                warningsDict[matchDict["file"]] = []

            warningEntry = {
                "line": matchDict.get("file"),
                "warning_id": matchDict.get("type") + matchDict.get("errno"),
            }

            if matchDict.get("msg"):
                warningEntry["warning_message"] = matchDict.get("msg")

            warningsDict[matchDict["file"]].append(warningEntry)

    return warningsDict

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


Question:
Runs the command session.
Create the Shell, then run this method to listen to the user,
and the Shell will invoke Handler's methods.
@throws java.io.IOException when can't readLine() from input.

public void commandLoop() throws IOException {
        for (Object handler : allHandlers) {
            if (handler instanceof ShellManageable) {
                ((ShellManageable)handler).cliEnterLoop();
            }
        }
        output.output(appName, outputConverter);
        String command = "";
        while (true) {
            try {
                command = input.readCommand(path);
                if (command.trim().equals("exit")) {
                    if (lineProcessor == null)
                        break;
                    else {
                        path = savedPath;
                        lineProcessor = null;
                    }
                }

                processLine(command);
            } catch (TokenException te) {
                lastException = te;
                output.outputException(command, te);
            } catch (CLIException clie) {
                lastException = clie;
                if (!command.trim().equals("exit")) {
                    output.outputException(clie);
                }
            }
        }
        for (Object handler : allHandlers) {
            if (handler instanceof ShellManageable) {
                ((ShellManageable)handler).cliLeaveLoop();
            }
        }
    }

public void marshall(Output output, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(output.getName(), NAME_BINDING);
            protocolMarshaller.marshall(output.getKinesisStreamsOutput(), KINESISSTREAMSOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getKinesisFirehoseOutput(), KINESISFIREHOSEOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getLambdaOutput(), LAMBDAOUTPUT_BINDING);
            protocolMarshaller.marshall(output.getDestinationSchema(), DESTINATIONSCHEMA_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Generate an infinite series of rectangular phase screens
    Uses an FFT screen generator to make a large screen and then
    returns non-overlapping subsections of it

def ScreenGenerator(nfft, r0, nx, ny):
    """"""
    while 1:
        layers = GenerateTwoScreens(nfft, r0)
        for iLayer in range(2):
            for iy in range(int(nfft/ny)):
                for ix in range(int(nfft/nx)):
                    yield layers[iLayer][iy*ny:iy*ny+ny, ix*nx:ix*nx+nx]

def _dump_query_timestamps(self, current_time: float):
        """"""
        windows = [10, 11, 15, 20, 30, 60]
        print("GraphQL requests:", file=sys.stderr)
        for query_hash, times in self._graphql_query_timestamps.items():
            print("  {}".format(query_hash), file=sys.stderr)
            for window in windows:
                reqs_in_sliding_window = sum(t > current_time - window * 60 for t in times)
                print("    last {} minutes: {} requests".format(window, reqs_in_sliding_window), file=sys.stderr)

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


Question:
Constructs a Font-object.

@param   attributes  the attributes of a Font object.
@return the Font constructed based on the attributes

public Font getFont(Properties attributes) {
        String fontname = null;
        String encoding = defaultEncoding;
        boolean embedded = defaultEmbedding;
        float size = Font.UNDEFINED;
        int style = Font.NORMAL;
        Color color = null;
        String value = attributes.getProperty(Markup.HTML_ATTR_STYLE);
        if (value != null && value.length() > 0) {
            Properties styleAttributes = Markup.parseAttributes(value);
            if (styleAttributes.isEmpty()) {
                attributes.put(Markup.HTML_ATTR_STYLE, value);
            }
            else {
                fontname = styleAttributes.getProperty(Markup.CSS_KEY_FONTFAMILY);
                if (fontname != null) {
                    String tmp;
                    while (fontname.indexOf(',') != -1) {
                        tmp = fontname.substring(0, fontname.indexOf(','));
                        if (isRegistered(tmp)) {
                            fontname = tmp;
                        }
                        else {
                            fontname = fontname.substring(fontname.indexOf(',') + 1);
                        }
                    }
                }
                if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTSIZE)) != null) {
                    size = Markup.parseLength(value);
                }
                if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTWEIGHT)) != null) {
                    style |= Font.getStyleValue(value);
                }
                if ((value = styleAttributes.getProperty(Markup.CSS_KEY_FONTSTYLE)) != null) {
                    style |= Font.getStyleValue(value);
                }
                if ((value = styleAttributes.getProperty(Markup.CSS_KEY_COLOR)) != null) {
                    color = Markup.decodeColor(value);
                }
                attributes.putAll(styleAttributes);
                for (Enumeration e = styleAttributes.keys(); e.hasMoreElements();) {
                    Object o = e.nextElement();
                    attributes.put(o, styleAttributes.get(o));
                }
            }
        }
        if ((value = attributes.getProperty(ElementTags.ENCODING)) != null) {
            encoding = value;
        }
        if ("true".equals(attributes.getProperty(ElementTags.EMBEDDED))) {
            embedded = true;
        }
        if ((value = attributes.getProperty(ElementTags.FONT)) != null) {
            fontname = value;
        }
        if ((value = attributes.getProperty(ElementTags.SIZE)) != null) {
            size = Markup.parseLength(value);
        }
        if ((value = attributes.getProperty(Markup.HTML_ATTR_STYLE)) != null) {
            style |= Font.getStyleValue(value);
        }
        if ((value = attributes.getProperty(ElementTags.STYLE)) != null) {
            style |= Font.getStyleValue(value);
        }
        String r = attributes.getProperty(ElementTags.RED);
        String g = attributes.getProperty(ElementTags.GREEN);
        String b = attributes.getProperty(ElementTags.BLUE);
        if (r != null || g != null || b != null) {
            int red = 0;
            int green = 0;
            int blue = 0;
            if (r != null) red = Integer.parseInt(r);
            if (g != null) green = Integer.parseInt(g);
            if (b != null) blue = Integer.parseInt(b);
            color = new Color(red, green, blue);
        }
        else if ((value = attributes.getProperty(ElementTags.COLOR)) != null) {
            color = Markup.decodeColor(value);
        }
        if (fontname == null) {
            return getFont(null, encoding, embedded, size, style, color);
        }
        return getFont(fontname, encoding, embedded, size, style, color);
    }

public static function Create( $value )
	{
		if ( $value instanceof ValueProxy )
			return $value;
		try
		{
			if ( $value instanceof XPath2Item )
			{
				$valueType = $value->getValueType();
				$typeName = $valueType->getTypeName();
				$value = $value->getTypedValue();
			}
			else if ( $value instanceof IXmlSchemaType )
			{
				$typeName = $value::$CLASSNAME;
			}
			else
			{
				$typeName = Type::FromValue( $value )->getTypeName();
			}

			if ( ! isset( ValueProxy::$valueFactory[ $typeName ] ) )
			{
				throw new KeyNotFoundException();
			}

			return ValueProxy::$valueFactory[ $typeName ]->Create( $value );
		}
		catch ( KeyNotFoundException $ex )
		{
			$className = get_class( $value );
			if ( is_null( $value ) )
				throw XPath2Exception::withErrorCodeAndParam( "XPTY0004", "The type {0} is not registred in ValueProxy", $className);
			else
				throw new InvalidCastException( "The type {$className} is not registred in ValueProxy" );
		}
	}

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


Question:
The URL for the request. If the template has not been resolved, the url will represent a uri
template.

@return the url

public String url() {

    /* build the fully qualified url with all query parameters */
    StringBuilder url = new StringBuilder(this.path());
    if (!this.queries.isEmpty()) {
      url.append(this.queryLine());
    }
    if (fragment != null) {
      url.append(fragment);
    }

    return url.toString();
  }

protected function GetResponseURL($sResponse)
    {
        $sReturnURLBase = $this->getActivePageService()->getActivePage()->GetRealURLPlain(array(), true);
        if ('.html' === substr($sReturnURLBase, -5)) {
            $sReturnURLBase = substr($sReturnURLBase, 0, -5);
        }
        if ('/' !== substr($sReturnURLBase, -1)) {
            $sReturnURLBase .= '/';
        }
        // remove http:// and https:// since these are set in the interface
        $sReturnURLBase = str_replace('https://', '', $sReturnURLBase);
        $sReturnURLBase = str_replace('http://', '', $sReturnURLBase);

        return $sReturnURLBase.self::URL_IDENTIFIER.$sResponse;
    }

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


Question:
Build a Criteria object containing the values of all modified columns in this object.

@return Criteria The Criteria object containing all modified values.

public function buildCriteria()
    {
        $criteria = new Criteria(IndexEngineIndexVersionTableMap::DATABASE_NAME);

        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::ID)) {
            $criteria->add(IndexEngineIndexVersionTableMap::ID, $this->id);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::VISIBLE)) {
            $criteria->add(IndexEngineIndexVersionTableMap::VISIBLE, $this->visible);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::CODE)) {
            $criteria->add(IndexEngineIndexVersionTableMap::CODE, $this->code);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::TITLE)) {
            $criteria->add(IndexEngineIndexVersionTableMap::TITLE, $this->title);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::TYPE)) {
            $criteria->add(IndexEngineIndexVersionTableMap::TYPE, $this->type);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::ENTITY)) {
            $criteria->add(IndexEngineIndexVersionTableMap::ENTITY, $this->entity);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::SERIALIZED_COLUMNS)) {
            $criteria->add(IndexEngineIndexVersionTableMap::SERIALIZED_COLUMNS, $this->serialized_columns);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::SERIALIZED_CONDITION)) {
            $criteria->add(IndexEngineIndexVersionTableMap::SERIALIZED_CONDITION, $this->serialized_condition);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::INDEX_ENGINE_DRIVER_CONFIGURATION_ID)) {
            $criteria->add(IndexEngineIndexVersionTableMap::INDEX_ENGINE_DRIVER_CONFIGURATION_ID, $this->index_engine_driver_configuration_id);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::CREATED_AT)) {
            $criteria->add(IndexEngineIndexVersionTableMap::CREATED_AT, $this->created_at);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::UPDATED_AT)) {
            $criteria->add(IndexEngineIndexVersionTableMap::UPDATED_AT, $this->updated_at);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::VERSION)) {
            $criteria->add(IndexEngineIndexVersionTableMap::VERSION, $this->version);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::VERSION_CREATED_AT)) {
            $criteria->add(IndexEngineIndexVersionTableMap::VERSION_CREATED_AT, $this->version_created_at);
        }
        if ($this->isColumnModified(IndexEngineIndexVersionTableMap::VERSION_CREATED_BY)) {
            $criteria->add(IndexEngineIndexVersionTableMap::VERSION_CREATED_BY, $this->version_created_by);
        }

        return $criteria;
    }

public function update(Query $query)
    {
        $options = $query->getOptions();

        if (isset($options['cache']) && is_string($options['cache']['key'])) {
            $key = $options['cache']['key'];
        }

        $pk   = $query->getPk($options);
        $data = $options['data'];

        if (empty($options['where'])) {
            // 如果存在主键数据 则自动作为更新条件
            if (is_string($pk) && isset($data[$pk])) {
                $where[$pk] = [$pk, '=', $data[$pk]];
                if (!isset($key)) {
                    $key = $this->getCacheKey($query, $data[$pk]);
                }
                unset($data[$pk]);
            } elseif (is_array($pk)) {
                // 增加复合主键支持
                foreach ($pk as $field) {
                    if (isset($data[$field])) {
                        $where[$field] = [$field, '=', $data[$field]];
                    } else {
                        // 如果缺少复合主键数据则不执行
                        throw new Exception('miss complex primary data');
                    }
                    unset($data[$field]);
                }
            }

            if (!isset($where)) {
                // 如果没有任何更新条件则不执行
                throw new Exception('miss update condition');
            } else {
                $options['where']['AND'] = $where;
                $query->setOption('where', ['AND' => $where]);
            }
        } elseif (!isset($key) && is_string($pk) && isset($options['where']['AND'])) {
            foreach ($options['where']['AND'] as $val) {
                if (is_array($val) && $val[0] == $pk) {
                    $key = $this->getCacheKey($query, $val);
                }
            }
        }

        // 更新数据
        $query->setOption('data', $data);

        // 生成UPDATE SQL语句
        $sql  = $this->builder->update($query);
        $bind = $query->getBind();

        if (!empty($options['fetch_sql'])) {
            // 获取实际执行的SQL语句
            return $this->getRealSql($sql, $bind);
        }

        // 检测缓存
        if ($this->cache && isset($key) && $this->cache->get($key)) {
            // 删除缓存
            $this->cache->rm($key);
        }

        // 执行操作
        $result = '' == $sql ? 0 : $this->execute($sql, $bind, $query);

        if ($result) {
            if (is_string($pk) && isset($where[$pk])) {
                $data[$pk] = $where[$pk];
            } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
                list($a, $val) = explode('|', $key);
                $data[$pk]     = $val;
            }

            $query->setOption('data', $data);
            $query->trigger('after_update');
        }

        return $result;
    }

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


Question:
// SetGeneratePreview sets the GeneratePreview optional argument.
// Whether preview should be generated for the result.
//
// Note: This property is experimental.

func (a *CallFunctionOnArgs) SetGeneratePreview(generatePreview bool) *CallFunctionOnArgs {
	a.GeneratePreview = &generatePreview
	return a
}

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question:
Log this transaction.
@param strTrxType The transaction type.

public void logTrx(FieldList record, String strTrxType)
    {
        BaseBuffer buffer = this.getBuffer();
        buffer.clearBuffer();
        buffer.addHeader(strTrxType);
        buffer.addHeader(record.getTableNames(false));
        buffer.addHeader(record.getCounterField().toString());
        if (ProxyConstants.REMOVE != strTrxType)
            buffer.fieldsToBuffer(record);
        Object objLogData = buffer.getPhysicalData();
        this.logTrx(objLogData);
    }

public Long getParameterTime(String name) throws RepositoryConfigurationException
   {
      try
      {
         return StringNumberParser.parseTime(getParameterValue(name));
      }
      catch (NumberFormatException e)
      {
         throw new RepositoryConfigurationException(name + ": unparseable time (as Long). " + e, e);
      }
   }

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


Question:
Callback from the AORequestedTick when the expiry alarm occurs.
@param requestedTick

public void expiryAlarm(AORequestedTick requestedTick)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "expiryAlarm", requestedTick);

    boolean transitionOccured = false;
    ArrayList<AORequestedTick> satisfiedTicks = null;
    try
    {
      this.lock();
      try
      {
        // it is possible that this event occurs after this object is closed.
        // it is safe to ignore it since we must have already transitioned the requestedTick to its final state
        if (closed)
        {
          if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "expiryAlarm");

          return;
        }

        transitionOccured = cancelRequestInternal(requestedTick, true);

        // If we expired the request and have more then process those
        // requests now
        if (transitionOccured && !listOfRequests.isEmpty())
          satisfiedTicks = processQueuedMsgs(null);
      }
      finally
      {
        this.unlock();
      }
    }
    catch(SINotPossibleInCurrentConfigurationException e)
    {
      // No FFDC code needed
      notifyException(e);
    }

    if (transitionOccured)
    { // parent needs to be informed
      parent.expiredRequest(requestedTick.tick);
    }

    if (satisfiedTicks != null)
    {
      // inform parent about satisfied ticks - outside lock
      int length = satisfiedTicks.size();
      for (int i = 0; i < length; i++)
      {
        AORequestedTick aotick = (AORequestedTick) satisfiedTicks.get(i);
        long tick = aotick.tick;
        SIMPMessage m = aotick.getMessage();
        parent.satisfiedRequest(tick, m);
      }
    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "expiryAlarm");

  }

func (_class FeatureClass) GetExperimental(sessionID SessionRef, self FeatureRef) (_retval bool, _err error) {
	_method := "Feature.get_experimental"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertFeatureRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertBoolToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
Add {@link Runnable} invoked when the {@link Server} is started.
(see: {@link ServerListener#serverStarted(Server)})

public ServerListenerBuilder addStartedCallback(Runnable runnable) {
        requireNonNull(runnable, "runnable");
        serverStartedCallbacks.add(unused -> runnable.run());
        return this;
    }

def _create_event_listeners(self):
        """"""
        LOG.debug("Create the event listeners.")
        for event_type, callback in self._event_callback_pairs:
            LOG.debug("Create listener for %r event", event_type)
            listener = self._utils.get_vnic_event_listener(event_type)
            eventlet.spawn_n(listener, callback)

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


Question:
Removes an object to the persistence.

This repository keeps track of added and removed nodes (additionally to the
other Unit of Work) in order to find in-memory nodes.

@param object $object The object to remove
@return void
@api

public function remove($object)
    {
        if ($object instanceof NodeInterface) {
            $object = $object->getNodeData();
        }
        if ($this->addedNodes->contains($object)) {
            $this->addedNodes->detach($object);
        }
        if (!$this->removedNodes->contains($object)) {
            $this->removedNodes->attach($object);
        }
        parent::remove($object);
    }

def delete_ptr_records(self, device, ip_address=None):

        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        if ip_address:
            uri = "%s&ip=%s" % (uri, ip_address)
        resp, resp_body = self._async_call(uri, method="DELETE",
                has_response=False,
                error_class=exc.PTRRecordDeletionFailed)
        return resp_body.get("status") == "COMPLETED"

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


Question:
Update this record (Always called from the record class).
@exception DBException File exception.

public void set(Rec fieldList) throws DBException
    {
        super.set(fieldList);
        this.logTrx((FieldList)fieldList, ProxyConstants.SET);
    }

def get_filehandle(self):
        """"""
        if os.path.exists(self.filename):
            self.filehandle = SD(self.filename, SDC.READ)
            logger.debug("Loading dataset {}".format(self.filename))
        else:
            raise IOError("Path {} does not exist.".format(self.filename))

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


Question: // OnTouchEnd is called when Title scene is Touched and it is released.

func (t *Title) OnTouchEnd(x, y float32) {
	if t.isAnimating {
		t.text.StopAnimation()
		t.isAnimating = false
	} else {
		t.text.StartAnimation("animation test", true, func() {})
		t.isAnimating = true
	}
}

@Override
  public void close() {
    log.info("Updating the current state high water mark with " + this.highWatermark);
    this.workUnitState.setActualHighWatermark(new LongWatermark(this.highWatermark));
    try {
      this.closeConnection();
    } catch (Exception e) {
      log.error("Failed to close the extractor", e);
    }
  }

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


Question: If the drone exits prematurely then respond with an error containing the data we receieved from `stderr`

function onExit () {
      if (!responded) {
        errState = true;
        responded = true;
        error = new Error('Error spawning drone');
        error.blame = {
          type: 'user',
          message: 'Script prematurely exited'
        }
        error.stdout = stdout.join('\n');
        error.stderr = stderr.join('\n');
        callback(error);

        //
        // Remove listeners to related events.
        //
        drone.removeListener('error', onError);
        drone.removeListener('message', onCarapacePort);
        clearTimeout(timeout);
      }
    }

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:
builds the usage line

@param array $usage_data   Usage line specification data
@param array $options_data Options specification data

@return string formatted usage line text

protected function buildUsageLine($usage_data, $options_data) {
    if ($usage_data['use_argv_self']) {
      $self_name = $_SERVER['argv'][0];
    } else {
      $self_name = $usage_data['self'];
    }

    $has_options = (count($options_data['lines']) > 0 ? true : false);
    $has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);

    $out =
      ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
      "  {$self_name}".
      ($has_options ? ' [options]' : '').
      ($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
      "\n";

    return $out;
  }

def get_arguments():
    """"""
    import argparse
    parser = argparse.ArgumentParser(
        description='Plot spectral responses for a set of satellite imagers')

    parser.add_argument("--platform_name", '-p', nargs='*',
                        help="The Platform name",
                        type=str, required=True)
    parser.add_argument("--sensor", '-s', nargs='*',
                        help="The sensor/instrument name",
                        type=str, required=True)
    parser.add_argument("-x", "--xlimits", nargs=2,
                        help=("x-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-y", "--ylimits", nargs=2,
                        help=("y-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-t", "--minimum_response",
                        help=("Minimum response: Any response lower than " +
                              "this will be ignored when plotting"),
                        default=0.015, type=float)

    parser.add_argument("-no_platform_name_in_legend", help=("No platform name in legend"),
                        action='store_true')
    parser.add_argument("--title", help=("Plot title"),
                        default=None, type=str)
    parser.add_argument("--wavelength_resolution",
                        help=("The step in wavelength (nanometers) when scanning\n" +
                              " the spectral range trying to find bands"),
                        default=0.005, type=float)
    parser.add_argument("-o", "--filename", help=("Output plot file name"),
                        default=None, type=str)
    parser.add_argument(
        "-v", '--verbose', help=("Turn logging on"), action='store_true')

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--bandname", '-b',
                       help="The sensor band name", type=str)
    group.add_argument("--wavelength", "-w", type=float,
                       help='the approximate spectral wavelength in micron')
    group.add_argument("--range", "-r", nargs='*',
                       help="The wavelength range for the plot",
                       default=[None, None], type=float)

    return parser.parse_args()

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


Question:
Return the next state

@throws Jacopo\LaravelImportExport\Exception\ClassNotFoundException
@return ImportState

public function getNextState()
	{
		if( $this->getIsExecuted() )
			{
				if ( class_exists( $next = $this->getNextStateClass() ) )
				{
					return (new $next );
				}
				else
				{
					throw new ClassNotFoundException;
				}
			}
			else
			{
				return $this;
			}
	}

public function handle()
    {
        try {
            $data = $this->argument('data');
            if (filter_var($data, FILTER_VALIDATE_URL)) {
                // need to download file
                $data = FileUtilities::importUrlFileToTemp($data);
            }

            if (is_file($data)) {
                $data = file_get_contents($data);
            }

            $format = $this->option('format');
            $format = DataFormats::toNumeric($format);
            $this->comment($format);

            $service = $this->option('service');
            $resource = $this->option('resource');
            $result = ServiceManager::handleRequest($service, Verbs::POST, $resource, [], [], $data, $format, false);
            if ($result->getStatusCode() >= 300) {
                $this->error(print_r($result->getContent(), true));
            } else {
                $this->info('Import complete!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

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


Question:
Create an object depends on is argument required

@param bool $argument
@return ArgumentTypeAbstract|FieldAbstract
@throws \Youshido\GraphQL\Exception\ConfigurationException

public function init($argument = false, $multiple = false)
    {
        if (!empty($argument)) {
            return new ArgumentTypeAbstract(
                ($multiple === true) ? $this->makeMultiple($this->getArguments()) : $this->getArguments(),
                $this->getName(),
                $this->getDescription(),
                $multiple
            );
        }

        return new FieldAbstract(
            ($multiple === true) ? new ListType($this->getFields()) : $this->getFields(),
            $this->getName(),
            $this->getDescription()
        );
    }

def validate(string_or_document, rules: nil, context: nil)
      doc = if string_or_document.is_a?(String)
        GraphQL.parse(string_or_document)
      else
        string_or_document
      end
      query = GraphQL::Query.new(self, document: doc, context: context)
      validator_opts = { schema: self }
      rules && (validator_opts[:rules] = rules)
      validator = GraphQL::StaticValidation::Validator.new(validator_opts)
      res = validator.validate(query)
      res[:errors]
    end

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


Question: works out the updates to be performed

def _analyze(self):

        if self.value is None or self.value == self.previous:
            pass
        elif self._operation == "add":
            self._additions = self.value
        elif self._operation == "remove":
            self._removals = self.value
        elif self.previous is None:
            self._assignments = self.value
        else:
            # partial update time
            self._additions = (self.value - self.previous) or None
            self._removals = (self.previous - self.value) or None
        self._analyzed = True

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

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