Question: // Find looks for a filename match in the OVA file

func (of *OVAFile) Find(filename string) (*tar.Header, error) {
	for {
		header, err := of.tarFile.Next()
		if err == io.EOF {
			return nil, err
		}
		if header.Name == filename {
			return header, nil
		}
	}
}

def audio_type(hsh)
      if !hsh.nil? && hsh.length
        hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus')
      end
    end

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


Question:
Query.

@return Response

public function query()
    {
        $sourceUUID = $this->getSourceUUID();
        if (empty($sourceUUID)) {
            return new JsonResponse([
                'status' => 'Error',
                'message' => 'Source UUID header must be defined',
            ], 400);
        }

        $authorUUID = $this
            ->userCredentialsProvider
            ->getUUID();

        $queryParameterBag = $this
            ->request
            ->query;

        $page = (int) $queryParameterBag->get('page', 1);
        $numPerPage = (int) $queryParameterBag->get('num_per_page', 10);
        $sortBy = json_decode($queryParameterBag->get(
            'sort_by',
            ['created_at' => 'desc']
        ), true);
        $indexedMetadataSortBy = [
            'indexed_metadata.' . key($sortBy) => $sortBy[key($sortBy)],
        ];

        $role = $this->userCredentialsProvider->isModerator()
            ? Author::ROLE_MODERATOR
            : Author::ROLE_USER;

        $result = $this
            ->commentRepository
            ->getCommentsBySource(
                $sourceUUID,
                $page,
                $numPerPage,
                $indexedMetadataSortBy,
                $role
            );

        if (!empty($authorUUID)) {
            foreach ($result->getComments() as $comment) {
                $this->setEditableInComment(
                    $comment,
                    $authorUUID
                );
            }
        }

        return new JsonResponse([
            'comments_result' => $result->toArray(),
            'user' => $this->userCredentialsProvider->toArray(),
        ], 200);
    }

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

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


Question: access the value

def value(self):

        if isinstance(self._value, str):
            dimension = self._value
            return getattr(self.call, dimension).value

        return super(CallDimensionI, self)._get_value()

func IsValue(node Expr) bool {
	switch v := node.(type) {
	case *SQLVal:
		switch v.Type {
		case StrVal, HexVal, IntVal, ValArg:
			return true
		}
	}
	return false
}

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


Question:
Generates the constructor code (un-setting public lazy loaded properties, setting identifier field values).

@param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class

@return string

private function generateConstructorImpl(ClassMetadata $class)
    {
        $constructorImpl = <<<'EOT'
    /**
     * @param \Closure $initializer
     * @param \Closure $cloner
     */
    public function __construct($initializer = null, $cloner = null)
    {

EOT;
        $toUnset         = [];

        foreach ($this->getLazyLoadedPublicProperties($class) as $lazyPublicProperty => $unused) {
            $toUnset[] = '$this->' . $lazyPublicProperty;
        }

        $constructorImpl .= (empty($toUnset) ? '' : '        unset(' . implode(', ', $toUnset) . ");\n")
            . <<<'EOT'

        $this->__initializer__ = $initializer;
        $this->__cloner__      = $cloner;
    }
EOT;

        return $constructorImpl;
    }

protected function buildDatabase(): DatabaseAdapter {
		$dbName = $this->determineDbName();
		$database = new PgsqlDatabase($dbName, $this->determineDbCharset($dbName),
				$this->getPersistedMetaEntities($dbName), $this->determineDbAttrs($dbName));

		foreach ($database->getMetaEntities() as $metaEntity) {
			if (!$metaEntity instanceof Table) continue;

			$this->metaEntityBuilder->applyIndexesForTable($dbName, $metaEntity);
		}

		return $database;
	}

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


Question:
// Handler defines a prefixed route responding to a request type specified in
// the method parameter

func (mr *MountableRouter) Handler(method string, path string, handler http.Handler) {
	mr.Delegate.Handler(method, libpath.Join(mr.Prefix, path), handler)
}

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());
		}
	}

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


Question: Issues a device clear command.

def clear(self, transport):
        """"""
        logger.debug('IEC60488 clear')
        with transport:
            try:
                transport.clear()
            except AttributeError:
                clear_msg = self.create_message('*CLS')
                transport.write(clear_msg)

func (s *ClaimDevicesByClaimCodeOutput) SetClaimCode(v string) *ClaimDevicesByClaimCodeOutput {
	s.ClaimCode = &v
	return s
}

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


Question:
Create SSH2 connection.

@param string $host
@param int $port
@param mixed[] $methods
@param callable[] $callbacks
@return resource

protected function createConnection($host, $port, $methods, $callbacks)
    {
        return @ssh2_connect($host, $port, $methods, $callbacks);
    }

def cmd(send, msg, args):

    parser = arguments.ArgParser(args['config'])
    parser.add_argument('speaker', nargs='?', default=args['config']['core']['channel'])
    parser.add_argument('--length', type=int, choices=[1, 2], default=2)
    parser.add_argument('--start', nargs='*')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    if args['db'].query(Babble).count():
        send(build_msg(args['db'], cmdargs.speaker, cmdargs.length, cmdargs.start))
    else:
        send("Please run ./scripts/gen_babble.py to initialize the babble cache")

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


Question:
send the given Particle

 @param [Particle] p the Particle to send
 @param [Boolean] sys if true send to system Particle fifo

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

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question: // SetBudgetName sets the BudgetName field's value.

func (s *BudgetPerformanceHistory) SetBudgetName(v string) *BudgetPerformanceHistory {
	s.BudgetName = &v
	return s
}

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

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

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


Question: // Update updates a bottle field(s).

func (b *BottleController) Update(ctx *app.UpdateBottleContext) error {
	bottle, ok := b.db.GetBottle(ctx.AccountID, ctx.BottleID)
	if !ok {
		return ctx.NotFound()
	}
	payload := ctx.Payload
	if payload.Name != nil {
		bottle.Name = *payload.Name
	}
	if payload.Vintage != nil {
		bottle.Vintage = *payload.Vintage
	}
	if payload.Vineyard != nil {
		bottle.Vineyard = *payload.Vineyard
	}
	if payload.Varietal != nil {
		bottle.Varietal = *payload.Varietal
	}
	if payload.Color != nil {
		bottle.Color = *payload.Color
	}
	if payload.Sweetness != nil {
		bottle.Sweetness = payload.Sweetness
	}
	if payload.Country != nil {
		bottle.Country = payload.Country
	}
	if payload.Region != nil {
		bottle.Region = payload.Region
	}
	if payload.Review != nil {
		bottle.Review = payload.Review
	}
	bottle.UpdatedAt = time.Now()

	b.db.SaveBottle(bottle)
	return ctx.NoContent()
}

protected function isFieldChanged($sField)
    {
        if (empty($sField)) {
            return false;
        }

        if ($this->obElement->$sField == $this->obElement->getOriginal($sField)) {
            return false;
        }

        return true;
    }

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


Question: // ExecTx runs a method which operates on a transaction.

func (c *conn) ExecTx(fn func(tx *trans) error) error {
	if c.flavor.executeTx != nil {
		return c.flavor.executeTx(c.db, func(sqlTx *sql.Tx) error {
			return fn(&trans{sqlTx, c})
		})
	}

	sqlTx, err := c.db.Begin()
	if err != nil {
		return err
	}
	if err := fn(&trans{sqlTx, c}); err != nil {
		sqlTx.Rollback()
		return err
	}
	return sqlTx.Commit()
}

public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {
		try {
			writeConfig(writer, config);
		} catch (IOException e) {
			throw SqlExceptionUtil.create("Could not write config to writer", e);
		}
	}

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


Question: // SetNextToken sets the NextToken field's value.

func (s *ListStackResourcesOutput) SetNextToken(v string) *ListStackResourcesOutput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question: Main program - internal

@SuppressWarnings("unchecked")
    private Result parseAndExecute(List<String> argList, Iterable<? extends JavaFileObject> fileObjects)
            throws ToolException, OptionException, com.sun.tools.javac.main.Option.InvalidValueException {
        long tm = System.currentTimeMillis();

        List<String> javaNames = new ArrayList<>();

        compOpts = Options.instance(context);

        // Make sure no obsolete source/target messages are reported
        try {
            com.sun.tools.javac.main.Option.XLINT_CUSTOM.process(getOptionHelper(), "-Xlint:-options");
        } catch (com.sun.tools.javac.main.Option.InvalidValueException ignore) {
        }

        Arguments arguments = Arguments.instance(context);
        arguments.init(ProgramName);
        arguments.allowEmpty();

        doclet.init(locale, messager);
        parseArgs(argList, javaNames);

        if (!arguments.handleReleaseOptions(extra -> true)) {
            // Arguments does not always increase the error count in the
            // case of errors, so increment the error count only if it has
            // not been updated previously, preventing complaints by callers
            if (!messager.hasErrors() && !messager.hasWarnings())
                messager.nerrors++;
            return CMDERR;
        }

        if (!arguments.validate()) {
            // Arguments does not always increase the error count in the
            // case of errors, so increment the error count only if it has
            // not been updated previously, preventing complaints by callers
            if (!messager.hasErrors() && !messager.hasWarnings())
                messager.nerrors++;
            return CMDERR;
        }

        if (fileManager instanceof BaseFileManager) {
            ((BaseFileManager) fileManager).handleOptions(fileManagerOpts);
        }

        compOpts.notifyListeners();
        List<String> modules = (List<String>) jdtoolOpts.computeIfAbsent(ToolOption.MODULE,
                s -> Collections.EMPTY_LIST);

        if (modules.isEmpty()) {
            List<String> subpkgs = (List<String>) jdtoolOpts.computeIfAbsent(ToolOption.SUBPACKAGES,
                    s -> Collections.EMPTY_LIST);
            if (subpkgs.isEmpty()) {
                if (javaNames.isEmpty() && isEmpty(fileObjects)) {
                    String text = messager.getText("main.No_modules_packages_or_classes_specified");
                    throw new ToolException(CMDERR, text);
                }
            }
        }

        JavadocTool comp = JavadocTool.make0(context);
        if (comp == null) return ABNORMAL;

        DocletEnvironment docEnv = comp.getEnvironment(jdtoolOpts,
                javaNames,
                fileObjects);

        // release resources
        comp = null;

        if (breakiterator || !locale.getLanguage().equals(Locale.ENGLISH.getLanguage())) {
            JavacTrees trees = JavacTrees.instance(context);
            trees.setBreakIterator(BreakIterator.getSentenceInstance(locale));
        }
        // pass off control to the doclet
        Result returnStatus = docEnv != null && doclet.run(docEnv)
                ? OK
                : ERROR;

        // We're done.
        if (compOpts.get("-verbose") != null) {
            tm = System.currentTimeMillis() - tm;
            messager.notice("main.done_in", Long.toString(tm));
        }

        return returnStatus;
    }

void _emitJcc(INST_CODE code, Label label, final int hint) {
        if (hint == 0) {
            emitX86(code, label);
        } else {
            emitX86(code, label, Immediate.imm(hint));
        }
    }

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


Question:
Remove any extraneous control characters from text fields.
@param s The string to have control characters removed
@param removeCR true if carriage returns should be removed
@return The given string with all control characters removed

public static String removeControlCharacters(String s, boolean removeCR)
    {
        String ret = s;
        if(ret != null)
        {
            ret = ret.replaceAll("_x000D_","");
            if(removeCR)
                ret = ret.replaceAll("\r","");
        }
        return ret;
    }

def parse_rmd_options(line):

    parsing_context = ParsingContext(line)

    result = []
    prev_char = ''

    name = ''
    value = ''

    for char in ',' + line + ',':
        if parsing_context.in_global_expression():
            if char == ',':
                if name != '' or value != '':
                    if result and name == '':
                        raise RMarkdownOptionParsingError(
                            'Option line "{}" has no name for '
                            'option value {}'.format(line, value))
                    result.append((name.strip(), value.strip()))
                    name = ''
                    value = ''
            elif char == '=':
                if name == '':
                    name = value
                    value = ''
                else:
                    value += char
            else:
                parsing_context.count_special_chars(char, prev_char)
                value += char
        else:
            parsing_context.count_special_chars(char, prev_char)
            value += char
        prev_char = char

    if not parsing_context.in_global_expression():
        raise RMarkdownOptionParsingError(
            'Option line "{}" is not properly terminated'.format(line))

    return result

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


Question: // addKnownTypes adds the set of types defined in this package to the supplied scheme.

func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(SchemeGroupVersion,
		&Workflow{},
		&WorkflowList{},
	)
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.NOP__UNDF_DATA:
				return UNDF_DATA_EDEFAULT == null ? undfData != null : !UNDF_DATA_EDEFAULT.equals(undfData);
		}
		return super.eIsSet(featureID);
	}

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


Question: // Top level parser for authorization configurations.

func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
	switch vv := v.(type) {
	case map[string]interface{}:
		// New style with allow and/or deny properties.
		return parseSubjectPermission(vv, errors, warnings)
	default:
		// Old style
		return parseOldPermissionStyle(v, errors, warnings)
	}
}

func NewAPI(
	backend Backend,
	authorizer facade.Authorizer,
	blockChecker BlockChecker,
) (*API, error) {
	if !authorizer.AuthClient() {
		return nil, common.ErrPerm
	}
	return &API{
		backend:    backend,
		authorizer: authorizer,
		check:      blockChecker,
	}, nil
}

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


Question:
Get the Struts module path for a URI that is relative to the web application root.

@param uri the URI for which to get the module path.

public static String getModulePathForRelativeURI( String uri )
    {
        if ( uri == null ) return null;
        assert uri.length() > 0;
        assert uri.charAt( 0 ) == '/' : uri;

        // Strip off the actual page name (e.g., some_page.jsp)
        int slash = uri.lastIndexOf( '/' );
        uri = uri.substring( 0, slash );

        return uri;
    }

def attr_subresource(raml_resource, route_name):

    static_parent = get_static_parent(raml_resource, method='POST')
    if static_parent is None:
        return False
    schema = resource_schema(static_parent) or {}
    properties = schema.get('properties', {})
    if route_name in properties:
        db_settings = properties[route_name].get('_db_settings', {})
        return db_settings.get('type') in ('dict', 'list')
    return False

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


Question:
/*global define
Detects the type of the passed object

@param {Any} obj object to find the type of
@memberOf type
@return {String} type of the passed object

function typeOf(obj) {
        if (obj === undefined) {
            return 'undefined';
        }

        if (obj === null) {
            return 'null';
        }

        var t = Object.prototype.toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(),
            m;

        if (t !== 'object') {
            return t;
        }

        m = obj.constructor.toString().match(/^function\s*([$A-Z_][0-9A-Z_$]*)/i);
        if (m === null) {
            return 'object';
        }

        return m[1];
    }

protected function _init() {
		parent::_init();
		$this->_rules += [
			'allowAll' => [
				'rule' => function() {
					return true;
				}
			],
			'denyAll' => [
				'rule' => function() {
					return false;
				}
			],
			'allowAnyUser' => [
				'message' => 'You must be logged in.',
				'rule' => function($user) {
					return $user ? true : false;
				}
			],
			'allowIp' => [
				'message' => 'Your IP is not allowed to access this area.',
				'rule' => function($user, $request, $options) {
					$options += ['ip' => false];
					if (is_string($options['ip']) && strpos($options['ip'], '/') === 0) {
						return (boolean) preg_match($options['ip'], $request->env('REMOTE_ADDR'));
					}
					if (is_array($options['ip'])) {
						return in_array($request->env('REMOTE_ADDR'), $options['ip']);
					}
					return $request->env('REMOTE_ADDR') === $options['ip'];
				}
			]
		];
	}

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


Question:
Resolves redirect chains in `fetches` and returns a list of fetches
    representing the final redirect destinations of the given url. There could
    be more than one if for example youtube-dl hit the same url with HEAD and
    then GET requests.

def final_bounces(fetches, url):

    redirects = {}
    for fetch in fetches:
         # XXX check http status 301,302,303,307? check for "uri" header
         # as well as "location"? see urllib.request.HTTPRedirectHandler
         if 'location' in fetch['response_headers']:
             redirects[fetch['url']] = fetch

    final_url = url
    while final_url in redirects:
        fetch = redirects.pop(final_url)
        final_url = urllib.parse.urljoin(
                fetch['url'], fetch['response_headers']['location'])

    final_bounces = []
    for fetch in fetches:
        if fetch['url'] == final_url:
            final_bounces.append(fetch)

    return final_bounces

def get_versions(self):

		'''

		'''

		# get all versions
		versions_response = self.repo.api.http_request('GET', '%s/fcr:versions' % self.uri)

		# parse response
		versions_graph = self.repo.api.parse_rdf_payload(versions_response.content, versions_response.headers)

		# loop through fedora.hasVersion
		for version_uri in versions_graph.objects(self.uri, self.rdf.prefixes.fedora.hasVersion):

			# get label
			version_label = versions_graph.value(version_uri, self.rdf.prefixes.fedora.hasVersionLabel, None).toPython()

			# affix version
			self._affix_version(version_uri, version_label)

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


Question:
/*
Construct a predicate based on the JSON-like representation "pred".  "types"
maps field names to either "string" or "number".  See README.md for details.

function createPredicate(pred, types)
{
	krillPrimValidateSyntax(pred);

	if (arguments.length >= 2 && types !== null) {
		mod_jsprim.forEachKey(types, function (k, v) {
			if (v !== 'string' && v !== 'number' && v !== 'boolean')
				throw (new VError(
				    'field "%s": unknown type "%s"', k, v));
		});

		krillPrimValidateTypes(types, pred);
	}

	return (new Predicate(mod_jsprim.deepCopy(pred), types));
}

def list_gebouwen_adapter(obj, request):

    return {
        'id': obj.id,
        'aard': {
            'id': obj.aard.id,
            'naam': obj.aard.naam,
            'definitie': obj.aard.definitie
        },
        'status': {
            'id': obj.status.id,
            'naam': obj.status.naam,
            'definitie': obj.status.definitie
        }
    }

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


Question:
Direct inbox feed,
        contains activities addressed directly to the owner of the inbox.

def direct(self):

        url = self._subfeed("direct")
        if "direct" in self.url or "major" in self.url or "minor" in self.url:
            return self
        if self._direct is None:
            self._direct = self.__class__(url, pypump=self._pump)
        return self._direct

def _load_file(self, log_file, message_name_filter_list):

        if isinstance(log_file, str):
            self._file_handle = open(log_file, "rb")
        else:
            self._file_handle = log_file

        # parse the whole file
        self._read_file_header()
        self._last_timestamp = self._start_timestamp
        self._read_file_definitions()

        if self.has_data_appended and len(self._appended_offsets) > 0:
            if self._debug:
                print('This file has data appended')
            for offset in self._appended_offsets:
                self._read_file_data(message_name_filter_list, read_until=offset)
                self._file_handle.seek(offset)

        # read the whole file, or the rest if data appended
        self._read_file_data(message_name_filter_list)

        self._file_handle.close()
        del self._file_handle

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


Question:
Per the JDBC 3.0 spec, this commits the transaction for the
specified Xid, not necessarily for the transaction associated
with this XAResource object.

public void commit(Xid xid, boolean onePhase) throws XAException {

        // Comment out following debug statement before public release:
        System.err.println("Performing a " + (onePhase ? "1-phase"
                                                       : "2-phase") + " commit on "
                                                       + xid);

        JDBCXAResource resource = xaDataSource.getResource(xid);

        if (resource == null) {
            throw new XAException("The XADataSource has no such Xid:  " + xid);
        }

        resource.commitThis(onePhase);
    }

def extract_child_criteria
      @entry.xpath("./*/cda:outboundRelationship[@typeCode='COMP']/cda:criteriaReference/cda:id",
                   HQMF2::Document::NAMESPACES).collect do |ref|
        Reference.new(ref).id
      end.compact
    end

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


Question:
change all BigDecimal values to floats due to
 https://github.com/rails/rails/issues/6033
 possible loss of precision :/

def cast_big_decimal(obj)
      case obj
      when BigDecimal
        obj.to_f
      when Hash
        obj.each do |k, v|
          # performance
          if v.is_a?(BigDecimal)
            obj[k] = v.to_f
          elsif v.is_a?(Enumerable)
            obj[k] = cast_big_decimal(v)
          end
        end
      when Enumerable
        obj.map do |v|
          cast_big_decimal(v)
        end
      else
        obj
      end
    end

def add_series(series)
      raise ArgumentError, "Invalid argument 'series' Expected ImageSeries or DoseVolume, got #{series.class}." unless [ImageSeries, DoseVolume].include?(series.class)
      @image_series << series
      @associated_series[series.uid] = series
    end

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


Question:
Shows or hides the element for a widget.<p>

@param widget the widget to show or hide
@param visible true if the widget should be shown

protected void setElementVisible(Widget widget, boolean visible) {

        if (visible) {
            widget.getElement().getStyle().clearDisplay();
        } else {
            widget.getElement().getStyle().setDisplay(Display.NONE);
        }

    }

protected function displayPage(SwatNoteBookPage $page, $count = 0)
    {
        echo '
';
        echo '';

        $radio = new SwatHtmlTag('input');
        $radio->type = 'radio';
        $radio->name = $this->id;
        $radio->id = $this->id . '_' . $page->id;
        $radio->value = $this->id . '_' . $page->id;

        if ($page->id == $this->selected_page) {
            $radio->checked = 'checked';
        }

        echo '';
        $radio->display();
        echo '';
        echo '';

        echo '	';
        echo '';

        $label = new SwatHtmlTag('label');
        $label->for = $this->id . '_' . $page->id;
        $label->setContent($page->title, $page->title_content_type);
        $label->display();

        echo '	';
        echo '
';

        echo '
';
        echo '	';

        $td = new SwatHtmlTag('td');
        $td->class = 'swat-radio-note-book-page';

        if ($page->id == $this->selected_page) {
            $td->class .= ' selected';
        }

        $td->open();
        echo '
';
        $page->display();
        echo '
';
        $td->close();

        echo '
';
    }

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


Question: Writes out any remaining bytes at the end of the stream and closes.

private function beforeClose()
    {
        if ($this->isWritable() && $this->remainder !== '') {
            $this->stream->write(base64_encode($this->remainder));
            $this->remainder = '';
        }
    }

@Override
    public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options,
            FileAttribute<?>... attrs) throws IOException {
        return new ShrinkWrapFileChannel(newByteChannel(path, options, attrs));
    }

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


Question:
Replace the class name in the stub.

@param  string $stub
@return $this

protected function replaceClassName(&$stub)
    {

        $className = $this->scaffoldCommandObj->getObjName('Name') . 'Controller';
        $stub = str_replace('{{class}}', $className, $stub);

        return $this;
    }

private static function loadDependency($parameterClass) {
		if (!isset(self::$instance[$parameterClass])) {
			/** @var DependencyManager $parameterDependency */
			$parameterDependency = $parameterClass;

			self::$loading[$parameterClass] = true;
			self::$instance[$parameterClass] = $parameterDependency::init();
		}

		return self::$instance[$parameterClass];
	}

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


Question: Non-linear refinement of motion estimate

private void refineMotionEstimate() {

		// use observations from the inlier set
		List<Stereo2D3D> data = new ArrayList<>();

		int N = matcher.getMatchSet().size();
		for( int i = 0; i < N; i++ ) {
			int index = matcher.getInputIndex(i);

			PointTrack l = candidates.get(index);
			LeftTrackInfo info = l.getCookie();
			PointTrack r = info.right;

			Stereo2D3D stereo = info.location;
			// compute normalized image coordinate for track in left and right image
			leftImageToNorm.compute(l.x,l.y,info.location.leftObs);
			rightImageToNorm.compute(r.x,r.y,info.location.rightObs);

			data.add(stereo);
		}

		// refine the motion estimate using non-linear optimization
		Se3_F64 keyToCurr = currToKey.invert(null);
		Se3_F64 found = new Se3_F64();
		if( modelRefiner.fitModel(data,keyToCurr,found) ) {
			found.invert(currToKey);
		}
	}

func RunIteration() {
	Time.Tick()
	Input.update()
	jsPollKeys()
	currentUpdater.Update(Time.Delta())
	Input.Mouse.Action = Neutral
	// TODO: this may not work, and sky-rocket the FPS
	//  requestAnimationFrame(func(dt float32) {
	// 	currentWorld.Update(Time.Delta())
	// 	keysUpdate()
	// 	if !headless {
	// 		// TODO: does this require !headless?
	// 		Mouse.ScrollX, Mouse.ScrollY = 0, 0
	// 	}
	// 	Time.Tick()
	// })
}

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


Question:
Handle an incoming request.

@param Request  $request
@param \Closure $next
@param int      $level

@throws \jeremykenedy\LaravelRoles\Exceptions\LevelDeniedException

@return mixed

public function handle($request, Closure $next, $level)
    {
        if ($this->auth->check() && $this->auth->user()->level() >= $level) {
            return $next($request);
        }

        throw new LevelDeniedException($level);
    }

public function create()
    {
        // Is this user allowed to do this?
        if (!$this->repository->isUserAllowed('create'))
        {
            Session::flash('status_code', 400 );
            $message = "You are not allowed to create ".$this->table_type_plural;
            Session::flash('message', $message);
            return view('formhandling::warnings/' . config('lasallecmsadmin.admin_template_name') . '/user_not_allowed', [
                'package_title'        => $this->package_title,
                'table_type_plural'    => $this->table_type_plural,
                'table_type_singular'  => $this->table_type_singular,
                'resource_route_name'  => $this->resource_route_name,
                'HTMLHelper'           => HTMLHelper::class,
            ]);
        }

        return view('formhandling::lookuptables/' . config('lasallecmsadmin.admin_template_name') . '/create', [
            'package_title'        => $this->package_title,
            'table_type_plural'    => $this->table_type_plural,
            'table_type_singular'  => $this->table_type_singular,
            'resource_route_name'  => $this->resource_route_name,
            'DatesHelper'          => DatesHelper::class,
            'HTMLHelper'           => HTMLHelper::class,
        ]);
    }

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


Question:
Loads the xml action to the menu template tree.

        :param      xaction | <xml.etree.ElementTree>

def loadXml( self, xaction ):

        if ( xaction.tag == 'menu' ):
            title = xaction.get('title', '')
            item = self.createMenuItem(title)
            for xchild in xaction:
                item.addChild(self.loadXml(xchild))

        elif ( xaction.tag == 'separator' ):
            item = self.createSeparatorItem()

        else:
            key = xaction.get('name', '')
            item = self.createActionItem(key)

        return item

def showPanelMenu(self, panel, point=None):

        if not self._panelMenu:
            self._panelMenu = XViewPanelMenu(self)

        if point is None:
            point = QtGui.QCursor.pos()

        self._panelMenu.setCurrentPanel(panel)
        self._panelMenu.exec_(point)

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


Question:
Set a unique, replicable guid for this work unit. Used for recovering partially successful work units.
@param state {@link State} where guid should be written.
@param guid A byte array guid.

public static void setWorkUnitGuid(State state, Guid guid) {
    state.setProp(WORK_UNIT_GUID, guid.toString());
  }

def InternalRecv(self):
    """"""
    first_read = self.InternalReadFrame()
    first_packet = UsbHidTransport.InitPacket.FromWireFormat(self.packet_size,
                                                             first_read)

    data = first_packet.payload
    to_read = first_packet.size - len(first_packet.payload)

    seq = 0
    while to_read > 0:
      next_read = self.InternalReadFrame()
      next_packet = UsbHidTransport.ContPacket.FromWireFormat(self.packet_size,
                                                              next_read)
      if self.cid != next_packet.cid:
        # Skip over packets that are for communication with other clients.
        # HID is broadcast, so we see potentially all communication from the
        # device.  For well-behaved devices, these should be BUSY messages
        # sent to other clients of the device because at this point we're
        # in mid-message transit.
        continue

      if seq != next_packet.seq:
        raise errors.HardwareError('Packets received out of order')

      # This packet for us at this point, so debit it against our
      # balance of bytes to read.
      to_read -= len(next_packet.payload)

      data.extend(next_packet.payload)
      seq += 1

    # truncate incomplete frames
    data = data[0:first_packet.size]
    return (first_packet.cmd, data)

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


Question:
// Status reports that readiness status of this Git repo: whether it
// has been cloned and is writable, and if not, the error stopping it
// getting to the next state.

func (r *Repo) Status() (GitRepoStatus, error) {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.status, r.err
}

def handleStatus(self, version, code, message):
        ""
        proxy.ProxyClient.handleStatus(self, version, code, message)
        # client.Response is currently just a container for needed data
        self._response = client.Response(version, code, message, {}, None)

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


Question: Returns the inverse of the incomplete beta function

function invIncBeta(p, a, b) {
  if(x < 0 || x > 1) {
    throw new RangeError('First argument must be between 0 and 1.');
	}

  // Special cases, there can make trouble otherwise
  else if (a === 1 && b === 1) return p;
  else if (p === 1) return 1;
  else if (p === 0) return 0;
  else if (a === 0) return 0;
  else if (b === 0) return 1;

  else {
    var EPS = 1e-8,
        a1 = a - 1,
        b1 = b - 1,
        j = 0,
        lna, lnb, pp, t, u, err, x, al, h, w, afac;

	if(a >= 1 && b >= 1) {
    pp = (p < 0.5) ? p : 1 - p;
    t = Math.sqrt(-2 * Math.log(pp));

		x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t;
		if(p < 0.5) x = -x;
		al = (x * x - 3) / 6;
		h = 2 / (1 / (2 * a - 1)  + 1 / (2 * b - 1));
		w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) * (al + 5 / 6 - 2 / (3 * h));
		x = a / (a + b * Math.exp(2 * w));
	} else {
		lna = Math.log(a / (a + b));
		lnb = Math.log(b / (a + b));
		t = Math.exp(a * lna) / a;
		u = Math.exp(b * lnb) / b;
		w = t + u;
		if (p < t / w) x = Math.pow(a * w * p, 1 / a);
		else x = 1 - Math.pow(b * w * (1 - p), 1 / b);
	}

	afac = -gammaCollection.logGamma(a) - gammaCollection.logGamma(b) + gammaCollection.logGamma(a + b);

  for(; j < 10; j++) {
		if(x === 0 || x === 1) return x;
		err = regualizedBeta(x, a, b) - p;

    t = Math.exp(a1 * Math.log(x) + b1 * log1p(-x) + afac);
		u = err / t;
		x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))));

    if (x <= 0) x = 0.5 * (x + t);
		if (x >= 1) x = 0.5 * (x + t + 1);

		if (Math.abs(t) < EPS * x && j > 0) break;
	}

	return x;
  }
}

func (t *T) ExpectPanic(f func(), err interface{}, desc ...string) {
	prefix := ""
	if len(desc) > 0 {
		prefix = strings.Join(desc, " ") + ": "
	}
	defer func() {
		i := recover()
		if i == nil {
			t.Fatalf("%sFunction call did not panic as expected.", prefix)
		}
		t.Equal(i, err, "Raised value is not correct")
	}()
	f()
}

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


Question:
Return the local method for this pod method, when the pod is on the
same jvm.

private MethodRefAmp findLocalMethod()
  {
    ServiceRefAmp serviceRefLocal = _serviceRef.getLocalService();

    if (serviceRefLocal == null) {
      return null;
    }

    if (_type != null) {
      return serviceRefLocal.methodByName(_name, _type);
    }
    else {
      return serviceRefLocal.methodByName(_name);
    }
  }

@Override
	public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException {

		this.logger.fine( "Terminating an in-memory agent." );
		Map<String,String> targetProperties = preventNull( parameters.getTargetProperties());

		// If we executed real recipes, undeploy everything first.
		// That's because we do not really terminate the agent's machine, we just kill the agent.
		// So, it is important to stop and undeploy properly.
		if( ! simulatePlugins( targetProperties )) {
			this.logger.fine( "Stopping instances correctly (real recipes are used)." );
			Map.Entry<String,String> ctx = parseMachineId( machineId );
			ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( ctx.getValue());

			// We do not want to undeploy the scoped instances, but its children.
			try {
				Instance scopedInstance = InstanceHelpers.findInstanceByPath( ma.getApplication(), ctx.getKey());
				for( Instance childrenInstance : scopedInstance.getChildren())
					this.manager.instancesMngr().changeInstanceState( ma, childrenInstance, InstanceStatus.NOT_DEPLOYED );

			} catch( IOException e ) {
				throw new TargetException( e );
			}
		}

		// Destroy the IPojo
		Factory factory = findIPojoFactory( parameters );
		deleteIPojo( factory, machineId );
	}

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


Question:
Login the passed user without much ado.

@param sLoginName
Login name of the user to log-in. May be null.
@param sPlainTextPassword
Plain text password to use. May be null.
@return Never null login status.

@Nonnull
  public ELoginResult loginUser (@Nullable final String sLoginName, @Nullable final String sPlainTextPassword)
  {
    return loginUser (sLoginName, sPlainTextPassword, (Iterable <String>) null);
  }

public PasswordAuthentication registerPasswordAuthentication(InetAddress pAddress, int pPort, String pProtocol, String pPrompt, String pScheme, PasswordAuthentication pPA) {
        /*
         System.err.println("registerPasswordAuthentication");
         System.err.println(pAddress);
         System.err.println(pPort);
         System.err.println(pProtocol);
         System.err.println(pPrompt);
         System.err.println(pScheme);
         */

        return passwordAuthentications.put(new AuthKey(pAddress, pPort, pProtocol, pPrompt, pScheme), pPA);
    }

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


Question: synchronized weave sync trigger

def sync(self, length):

        # go in wave stream to the first bit
        try:
            self.next()
        except StopIteration:
            print "Error: no bits identified!"
            sys.exit(-1)

        log.info("First bit is at: %s" % self.pformat_pos())
        log.debug("enable half sinus scan")
        self.half_sinus = True

        # Toggle sync test by consuming one half sinus sample
#         self.iter_trigger_generator.next() # Test sync

        # get "half sinus cycle" test data
        test_durations = itertools.islice(self.iter_duration_generator, length)
        # It's a tuple like: [(frame_no, duration)...]

        test_durations = list(test_durations)

        diff1, diff2 = diff_info(test_durations)
        log.debug("sync diff info: %i vs. %i" % (diff1, diff2))

        if diff1 > diff2:
            log.info("\nbit-sync one step.")
            self.iter_trigger_generator.next()
            log.debug("Synced.")
        else:
            log.info("\nNo bit-sync needed.")

        self.half_sinus = False
        log.debug("disable half sinus scan")

func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool {
	select {
	case <-wait.wake:
		return true
	case <-after:
	}
	swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0)
	// They're gonna put it.
	if !swapped {
		<-wait.wake
		return true
	}
	return false
}

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


Question:
Gets the instanceName this client is associated with.

@deprecated Please use {@link #getProjectId()} and {@link #getInstanceId()}.

@Deprecated
  public com.google.bigtable.admin.v2.InstanceName getInstanceName() {
    return com.google.bigtable.admin.v2.InstanceName.of(projectId, instanceId);
  }

public BoxRequestsBookmark.GetBookmarkInfo getInfoRequest(final String id) {
        BoxRequestsBookmark.GetBookmarkInfo request = new BoxRequestsBookmark.GetBookmarkInfo(id, getBookmarkInfoUrl(id), mSession);
        return request;
    }

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


Question:
@param string $object
@param string $category
@param string $severity

@return string

private static function getMessagePrefix( $object , $category , $severity )
	{
		return '[' . date( 'Y/m/d H:i:s' ) . '][' . $severity. '][' . self::getClassNameWithoutNameSpace( $object ) . '][' . $category . '] ';
	}

private function handleINFO()
    {
        header('Content-Type: text/html');

        $css = '
body {
    margin: 0px;
    padding: 10px;
    font-family: sans-serif;
}
#header {
    background-color: #339900;
    color: #FFFFFF;
    padding: 5px 10px;
    margin: -10px;
}
h1 {
    font-size: xx-large;
    color: #CCFF99;
}
#header p {
    font-size: large;
}

dt {
    margin-top: 1em;
}

.description {
    padding-left: 1.5em;
    margin-bottom: 1.5em;
}

a:link {
    color: #006600;
}

a:visited {
    color: #030;
}

a:hover {
    color: #003300;
}
';

        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>' . $this->wsdlclassname . ' WebService</title>
<meta name="generator" content="PEAR::Services_Webservice" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">

'.
        '
' . $this->wsdlclassname . '

' .
        htmlspecialchars($this->description)
        . '

The following operations are supported. ' .
        'For a formal definition, please review the getSelfUrl()) . '?WSDL">Service Description.

';

        foreach ($this->wsdlStruct[$this->wsdlclassname]['method'] as $methodName => $method) {
            $paramValue = array();
            foreach ($method['var'] as $methodVars) {
                if (isset($methodVars['param'])) {
                    $paramValue[] = $methodVars['type']
                                     . str_repeat('[]', $methodVars['length']);
                }
            }
            $returnValue = array();
            foreach ($method['var'] as $methodVars) {
                if (isset($methodVars['return'])) {
                    $returnValue[] = $methodVars['type']
                                     . str_repeat('[]', $methodVars['length']);
                }
            }
            echo sprintf(
                '
<samp><var class="returnedValue">%s</var> '
                . '%s'
                . '( <var class="parameter">%s</var> )</samp>%s
',
                implode(',', $returnValue),
                $methodName,
                implode(
                    '</var> , <var class="parameter">',
                    $paramValue
                ), ((empty($method['description'])) ?
                    '' : ('
'
                    . htmlspecialchars($method['description']) . ''))
            );
        }
        echo '

getSelfUrl()) . '?DISCO">DISCO makes it possible for clients to reflect against endpoints to discover services and their associated <acronym title="Web Service Description Language">WSDL</acronym> documents.
';

        if ($this->warningNamespace == true
            || $this->namespace == 'http://example.org/'
        ) {
            echo '

This web service is using http://example.org/ as its default namespace.

Recommendation: Change the default namespace before the <acronym title="eXtensible Markup Language">XML</acronym> Web service is made public.

Each XML Web service needs a unique namespace in order for client applications to distinguish it from other services on the Web. http://example.org/ is available for XML Web services that are under development, but published XML Web services should use a more permanent namespace.

Your XML Web service should be identified by a namespace that you control. For example, you can use your company`s Internet domain name as part of the namespace. Although many XML Web service namespaces look like <acronym title="Uniform Resource Locators">URLs</acronym>, they need not point to actual resources on the Web. (XML Web service namespaces are <acronym title="Uniform Resouce Identifiers">URIs</acronym>.)

For more details on XML namespaces, see the <acronym title="World Wide Web Consortium">W3C</acronym> recommendation on Namespaces in XML.

For more details on <acronym title="Web Service Description Language">WSDL</acronym>, see the WSDL Specification.

For more details on URIs, see <acronym title="Request For Comment">RFC</acronym> 2396.

Powered by PEAR http://pear.php.net

';

        }
        echo '';
    }

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


Question:
Displays the combined assets for the given asset type

@param string $type
@param array $files

protected function displayCombinedAssets($type, $files)
    {
        $isValid = $this->validateTypeCache($type, $files);

        // If the cache isn't valid, we build the cache
        $result = $isValid;
        if (!$isValid) {
            $result = $this->buildTypeCache($type, $files);
        }

        // If the cache is valid, load the file
        if ($result) {
            $hash = $this->getTypeHash($type);
            $cachedFile = $this->cachedFiles[$hash]['file'];

            echo $this->generateHtmlCode($type, $cachedFile);
        }
    }

private static void mergeApiPathParamDoc(ApiPathParam apiPathParam, ApiParamDoc apiParamDoc) {
		if (apiPathParam != null) {
			if (apiParamDoc.getName().trim().isEmpty()) {
				apiParamDoc.setName(apiPathParam.name());
			}
			apiParamDoc.setDescription(apiPathParam.description());
			apiParamDoc.setAllowedvalues(apiPathParam.allowedvalues());
			apiParamDoc.setFormat(apiPathParam.format());
		}
	}

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


Question:
:calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_
        :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment`

def get_comments(self):

        return github.PaginatedList.PaginatedList(
            github.CommitComment.CommitComment,
            self._requester,
            self.url + "/comments",
            None
        )

def version_history(soup, html_flag=True):
    ""
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)
    version_history = []
    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
    for tag in related_object_tags:
        article_version = OrderedDict()
        date_tag = first(raw_parser.date(tag))
        if date_tag:
            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
            (day, month, year) = ymd(date_tag)
            article_version['day'] = day
            article_version['month'] = month
            article_version['year'] = year
            article_version['date'] = date_struct_nn(year, month, day)
        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
        set_if_value(article_version, "comment",
                     convert(node_contents_str(first(raw_parser.comment(tag)))))
        version_history.append(article_version)
    return version_history

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


Question:
Find all instances of a name in the various code styles

Handles replacing both singular and plural replacements

@param string $singularFindName
@param string $singularReplaceName

@return FindReplace

public function findReplaceName(
        string $singularFindName,
        string $singularReplaceName
    ): self {
        $singularFindName    = Inflector::classify($singularFindName);
        $singularReplaceName = Inflector::classify($singularReplaceName);
        $this->findReplace($singularFindName, $singularReplaceName);
        $this->findReplace(\lcfirst($singularFindName), \lcfirst($singularReplaceName));
        $this->findReplace(\strtoupper($singularFindName), \strtoupper($singularReplaceName));
        $this->findReplace(
            \strtoupper(Inflector::tableize($singularFindName)),
            \strtoupper(Inflector::tableize($singularReplaceName))
        );

        $pluralFindName    = $this->getPlural($singularFindName);
        $pluralReplaceName = $this->getPlural($singularReplaceName);
        $this->findReplace($pluralFindName, $pluralReplaceName);
        $this->findReplace(\lcfirst($pluralFindName), \lcfirst($pluralReplaceName));
        $this->findReplace(\strtoupper($pluralFindName), \strtoupper($pluralReplaceName));
        $this->findReplace(
            \strtoupper(Inflector::tableize($pluralFindName)),
            \strtoupper(Inflector::tableize($pluralReplaceName))
        );

        return $this;
    }

func (s *JobParameters) SetFormat(v string) *JobParameters {
	s.Format = &v
	return s
}

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


Question:
Initialize the object with values from the remote service (if any).

@return boolean
@throws \Exception|\OpenStackStorage\Exceptions\ResponseError

protected function initialize()
    {
        if (!$this->name) {
            return false;
        }

        try {
            $response = $this->container->getConnection()->makeRequest(
                Client::HEAD,
                array($this->container->getName(), $this->name)
            );
        } catch (Exceptions\ResponseError $e) {
            if (404 == $e->getCode()) {
                return false;
            }

            throw $e;
        }

        $this->manifest     = $response['headers']['x-object-manifest'];
        $this->contentType  = $response['headers']['content-type'];
        $this->etag         = $response['headers']['etag'];
        $this->size         = intval($response['headers']['content-length']);
        $this->lastModified = new \DateTime($response['headers']['last-modified']);

        foreach ($response['headers'] as $name => $values) {
            if (0 === strpos($name, 'x-object-meta-')) {
                $this->metadata[substr($name, 14)] = is_array($values) ? $values[0] : $values;
            }
        }

        return true;
    }

func StorageProviders() storage.ProviderRegistry {
	return storage.StaticProviderRegistry{
		map[storage.ProviderType]storage.Provider{
			"static": &StorageProvider{IsDynamic: false},
			"modelscoped": &StorageProvider{
				StorageScope: storage.ScopeEnviron,
				IsDynamic:    true,
				IsReleasable: true,
			},
			"modelscoped-unreleasable": &StorageProvider{
				StorageScope: storage.ScopeEnviron,
				IsDynamic:    true,
				IsReleasable: false,
			},
			"modelscoped-block": &StorageProvider{
				StorageScope: storage.ScopeEnviron,
				IsDynamic:    true,
				IsReleasable: true,
				SupportsFunc: func(k storage.StorageKind) bool {
					return k == storage.StorageKindBlock
				},
			},
			"machinescoped": &StorageProvider{
				StorageScope: storage.ScopeMachine,
				IsDynamic:    true,
			},
		},
	}
}

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


Question: // DocKind returns the type of document produced by this rule.

func (head *Head) DocKind() DocKind {
	if head.Key != nil {
		if head.Value != nil {
			return PartialObjectDoc
		}
		return PartialSetDoc
	}
	return CompleteDoc
}

function(doctype){
    if (doctype && (doctype.val || !this.doctype)) {
      this.setDoctype(doctype.val || 'html');
    }

    if (this.doctype) this.buffer(this.doctype);
    this.hasCompiledDoctype = true;
  }

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


Question: Convert a JSON-serializable representation back to a field.

def field_from_json(self, key_and_type, json_value):
        """"""
        assert ':' in key_and_type
        key, type_code = key_and_type.split(':', 1)
        from_json = self.field_function(type_code, 'from_json')
        value = from_json(json_value)
        return key, value

public function toPHP($value, Driver $driver)
    {
        if ($this->_isSerialized($value)) {
            $value = unserialize($value);
        }

        return $value;
    }

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


Question: Return true if the string is a mathematical symbol.

def is_symbol(string):

    return (
        is_int(string) or is_float(string) or
        is_constant(string) or is_unary(string) or
        is_binary(string) or
        (string == '(') or (string == ')')
    )

protected static function parseBooleanType(&$data, &$result)
    {
        // Boolean type
        $booleanValue = (bool) (ord($data[2]) == 0xff);
        $dataI = substr($data, 3);
        $result[] = [
            'boolean (1)',
            $booleanValue, ];
        $data = $dataI;
    }

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


Question:
1) Returns true if request has email and password in the json body

@param Request $request
@return bool

public function supports(Request $request)
    {
        $post = json_decode($request->getContent(), true);

        return !empty($post[self::EMAIL_FIELD]) && !empty($post[self::PASSWORD_FIELD]);
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question:
Convert raw value to references

@param string $rawValue
@param Context $context
@return array<NodeInterface>

protected function convertReferences($rawValue, Context $context)
    {
        $nodeIdentifiers = $rawValue;
        $result = [];

        if (is_array($nodeIdentifiers)) {
            foreach ($nodeIdentifiers as $nodeIdentifier) {
                $referencedNode = $context->getNodeByIdentifier($nodeIdentifier);
                if ($referencedNode !== null) {
                    $result[] = $referencedNode;
                }
            }
        }

        return $result;
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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


Question: // ContainerInspect is part of the APIClient interface

func (sa *StubAPIClient) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) {
	sa.called()
	return sa.ContainerInspectFn(ctx, containerID)
}

protected function getClass($class)
    {
        if(ClientVersionMapInterface::VERSION_V090X === $this->versionFolder) {
            throw new RepositoryException('Version folder ' .
                ClientVersionMapInterface::VERSION_V090X . ' is not allowed for cat repository');
        }

        return parent::getClass($class);
    }

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


Question: // hasHostVolume returns true if the pod spec has a HostPath volume.

func hasHostVolume(pod *v1.Pod) bool {
	for _, v := range pod.Spec.Volumes {
		if v.HostPath != nil {
			return true
		}
	}
	return false
}

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question:
Return query to find the child comments.

@param integer $baseId
@param array $config
@return \yii\db\ActiveQuery to query child comments.

public static function queryByBaseId( $baseId, $config = [] ) {

		$type	= isset( $config[ 'type' ] ) ? $config[ 'type' ] : self::TYPE_COMMENT;
		$status	= isset( $config[ 'status' ] ) ? $config[ 'status' ] : self::STATUS_APPROVED;

		return self::find()->where( [ 'baseId' => $baseId, 'type' => $type, 'status' => $status ] );
	}

public function index(PageController $parent_controller, Tree $tree, $block_id, $template) {
        $view_bag = new ViewBag();

        if($parent_controller && $tree) {

            $view_bag->set('tree', $tree);
            $view_bag->set('indi', $parent_controller->getSignificantIndividual());

            $id = $this->module->getName().$block_id;
            $class = $this->module->getName().'_block';
            $parent_controller->addInlineJavascript('
                jQuery("#maj-new_passwd").hide();
                jQuery("#maj-passwd_click").click(function()
                {
                    jQuery("#maj-new_passwd").slideToggle(100, function() {
                        jQuery("#maj-new_passwd_username").focus();
    			});
    					return false;
    				  });
    			');

            if (Auth::isAdmin()) {
                $title='getNameHtml() . '&ctype=gedcom">';
            } else {
                $title='';
            }
            $title .=''.$tree->getTitleHtml().'';

            $piwik_enabled = $this->module->getBlockSetting($block_id, 'piwik_enabled', false);
            $view_bag->set('piwik_enabled', $piwik_enabled);
            if($piwik_enabled) {
                $parent_controller->addInlineJavascript(
                    '$("#piwik_stats")
                        .load("module.php?mod='.$this->module->getName().'&mod_action=Piwik&block_id='.$block_id.'");'
                );
            }

            $content = ViewFactory::make('WelcomeBlock', $this,  new BaseController(), $view_bag)->getHtmlPartial();

            if ($template) {
                return Theme::theme()->formatBlock($id, $title, $class, $content);
            } else {
                return $content;
            }
        }
    }

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


Question:
Connect adapter, model and adaptee.

@param string $adaptee

@return \Assely\Contracts\Adapter\AdapterInterface

public function connectAdapter($adaptee)
    {
        $adapter = new $this->adapter($this->config);

        return $adapter
            ->setAdaptee($adaptee)
            ->setModel($this->model);
    }

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question:
/* -- Requires --
protected $model;
-----------------

public function getDelete($sid)
    {
        $model = $this->model->find($sid);

        if ($model == null) {
            $errors = new MessageBag;
            $errors->add('deleteError', trans('redminportal::messages.error_delete_entry'));
            return redirect()->back()->withErrors($errors);
        }

        $model->delete();

        return redirect()->back();
    }

public function Comment2($CommentID, $Inserted = FALSE) {
      $this->CommentModel->Save2($CommentID, $Inserted);
      $this->Render('Blank', 'Utility', 'Dashboard');
   }

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


Question:
download a file from LinShare using its rest api.
        This method could throw exceptions like urllib2.HTTPError.

def download(self, uuid, url, forced_file_name=None,
                 progress_bar=True, chunk_size=256,
                 directory=None, overwrite=False):

        self.last_req_time = None
        url = self.get_full_url(url)
        self.log.debug("download url : " + url)
        # Building request
        request = urllib2.Request(url)
        # request.add_header('Content-Type', 'application/json; charset=UTF-8')
        request.add_header('Accept', 'application/json,*/*;charset=UTF-8')
        # request start
        starttime = datetime.datetime.now()
        # doRequest
        resultq = urllib2.urlopen(request)
        code = resultq.getcode()
        file_name = uuid
        self.log.debug("ret code : '" + str(code) + "'")
        if code == 200:
            content_lenth = resultq.info().getheader('Content-Length')
            if not content_lenth:
                msg = "No content lengh header found !"
                self.log.debug(msg)
                progress_bar = False
            else:
                file_size = int(content_lenth.strip())
            if forced_file_name:
                file_name = forced_file_name
            else:
                content_dispo = resultq.info().getheader('Content-disposition')
                if content_dispo:
                    content_dispo = content_dispo.strip()
                    file_name = extract_file_name(content_dispo)
            if directory:
                if os.path.isdir(directory):
                    file_name = directory + "/" + file_name
            if os.path.isfile(file_name):
                if not overwrite:
                    cpt = 1
                    while 1:
                        if not os.path.isfile(file_name + "." + str(cpt)):
                            file_name += "." + str(cpt)
                            break
                        cpt += 1
                else:
                    self.log.warn("'%s' already exists. It was overwriten.",
                                  file_name)
            stream = None
            pbar = None
            if progress_bar:
                widgets = [FileTransferSpeed(), ' <<<', Bar(), '>>> ',
                           Percentage(), ' ', ETA()]
                pbar = ProgressBar(widgets=widgets, maxval=file_size)
                stream = FileWithCallback(file_name, 'w', pbar.update,
                                          file_size, file_name)
                pbar.start()
            else:
                stream = file(file_name, 'w')
            while 1:
                chunk = resultq.read(chunk_size)
                if not chunk:
                    break
                stream.write(chunk)
            stream.flush()
            stream.close()
            if pbar:
                pbar.finish()
        # request end
        endtime = datetime.datetime.now()
        self.last_req_time = str(endtime - starttime)
        self.log.debug("download url : %(url)s : request time : %(time)s",
                       {"url": url,
                        "time": self.last_req_time})
        return (file_name, self.last_req_time)

func (ftp *FTP) Syst() (line string, err error) {
	if err := ftp.send("SYST"); err != nil {
		return "", err
	}
	if line, err = ftp.receive(); err != nil {
		return
	}
	if !strings.HasPrefix(line, StatusSystemType) {
		err = errors.New(line)
		return
	}

	return strings.SplitN(strings.TrimSpace(line), " ", 2)[1], nil
}

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


Question:
Sends a clear snapshot message for a particular item to the remote LS proxy.

@param {String} itemName the item name

function clearSnapshot(itemName) {
		var message, id = getIdFromItemName(itemName);
		message = proto.writeClearSnapshot(id, itemName);
		notify(message);
		return that;
	}

def capture_setting(self, sbp_msg, **metadata):

        if sbp_msg.msg_type == SBP_MSG_SETTINGS_READ_RESP:
            section, setting, value = sbp_msg.payload.split(b'\0')[:3]
            self.settings.append((section, setting, value))

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


Question: Send messages.success message after successful document creation.

def document_created_message(self, request, document):

        messages.success(request, _("Document {} was created".format(document)))

public function handle()
    {
        $this->showWelcomeMessage();
        $this->userSetup();
        $this->triggerPublish();
        $this->call('dashboard:fresh');
        $this->setupSeedStubs();
        $this->triggerMigrations();
        $this->createDefaultUser();
        $this->info('Setup is complete. Keep coding!');
    }

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


Question:
@EXT\Route(
"/index",
name="claro_admin_index"
)

Displays the administration section index.

@throws \Symfony\Component\Security\Core\Exception\AccessDeniedException

@return \Symfony\Component\HttpFoundation\Response

public function indexAction()
    {
        $tools = $this->toolManager->getAdminToolsByRoles($this->tokenStorage->getToken()->getRoles());

        if (count($tools) === 0) {
            throw new AccessDeniedException();
        }

        return $this->redirect($this->generateUrl('claro_admin_open_tool', array('toolName' => $tools[0]->getName())));
    }

public function getAction(Request $request)
    {
        $structureProvider = $this->get('sulu.content.structure_manager');
        $type = $request->get('type', 'default');

        $templates = [];
        foreach ($structureProvider->getStructures('article') as $structure) {
            if ($this->getType($structure->getStructure()) !== $type) {
                continue;
            }

            $templates[] = [
                'internal' => $structure->getInternal(),
                'template' => $structure->getKey(),
                'title' => $structure->getLocalizedTitle($this->getUser()->getLocale()),
            ];
        }

        return new JsonResponse(
            [
                '_embedded' => $templates,
                'total' => count($templates),
            ]
        );
    }

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


Question:
@private

Attempt to get the oEmbed info for a given link
Falls back to an <a> tag if that's not possible.

@param {string} value
@return {string}

async function _oembed(value) {
    let result = cache.get(value);

    if (result) {
      return result;
    }

    try {
      const unfurled = await unfurl(value);
      result = unfurled.oembed.html;
    } catch (err) {
      result = `<a href="${value}">${value}</a>`;
    }

    return cache.put(value, result);
  }

public static function encode($value, string $type = null): string
    {
        return self::run(self::ENCODER, $value, $type);
    }

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


Question: (path: String) => Array<String> splits a `/`-delimited path into segments

function splitPath(path) {
  if (Array.isArray(path)) {
    return path
  }
  if (path[0] === '/') {
    path = path.substr(1)
  }
  if (path[path.length-1] === '/') {
    path = path.substr(0, path.length-1)
  }
  return path.split('/')
}

public <R> SparkStream<R> mapPartitions(@NonNull SerializableFunction<Iterator<? super T>, ? extends R> function) {
      return new SparkStream<>(rdd.mapPartitions(iterator -> {
         Configurator.INSTANCE.configure(configBroadcast.value());
         return Cast.as(function.apply(iterator));
      }));
   }

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


Question: // SetNodeGroupId sets the NodeGroupId field's value.

func (s *ReshardingConfiguration) SetNodeGroupId(v string) *ReshardingConfiguration {
	s.NodeGroupId = &v
	return s
}

def update(cls, cluster_id_label, cluster_info):

        conn = Qubole.agent(version="v2")
        return conn.put(cls.element_path(cluster_id_label), data=cluster_info)

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


Question: Drops a table. Use caution!

def drop_table(self, tablename: str) -> int:
        """"""
        sql = "DROP TABLE IF EXISTS {}".format(tablename)
        log.info("Dropping table " + tablename + " (ignore any warning here)")
        return self.db_exec_literal(sql)

func dmlFormatter(buf *sqlparser.TrackedBuffer, node sqlparser.SQLNode) {
	switch node := node.(type) {
	case sqlparser.TableName:
		node.Name.Format(buf)
		return
	}
	node.Format(buf)
}

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


Question:
Recursively convert a potentially-multipart tree.

    Returns a tuple of (the converted tree, whether any markdown was found)

def convert_tree(message, config, indent=0, wrap_alternative=True, charset=None):

    ct = message.get_content_type()
    cs = message.get_content_subtype()
    if charset is None:
        charset = get_charset_from_message_fragment(message)
    if not message.is_multipart():
        # we're on a leaf
        converted = None
        disposition = message.get('Content-Disposition', 'inline')
        if disposition == 'inline' and ct in ('text/plain', 'text/markdown'):
            converted = convert_one(message, config, charset)
        if converted is not None:
            if wrap_alternative:
                new_tree = MIMEMultipart('alternative')
                _move_headers(message, new_tree)
                new_tree.attach(message)
                new_tree.attach(converted)
                return new_tree, True
            else:
                return converted, True
        return message, False
    else:
        if ct == 'multipart/signed':
            # if this is a multipart/signed message, then let's just
            # recurse into the non-signature part
            new_root = MIMEMultipart('alternative')
            if message.preamble:
                new_root.preamble = message.preamble
            _move_headers(message, new_root)
            converted = None
            for part in message.get_payload():
                if part.get_content_type() != 'application/pgp-signature':
                    converted, did_conversion = convert_tree(part, config, indent=indent + 1,
                                                             wrap_alternative=False,
                                                             charset=charset)
                    if did_conversion:
                        new_root.attach(converted)
            new_root.attach(message)
            return new_root, did_conversion
        else:
            did_conversion = False
            new_root = MIMEMultipart(cs, message.get_charset())
            if message.preamble:
                new_root.preamble = message.preamble
            _move_headers(message, new_root)
            for part in message.get_payload():
                part, did_this_conversion = convert_tree(part, config, indent=indent + 1, charset=charset)
                did_conversion |= did_this_conversion
                new_root.attach(part)
            return new_root, did_conversion

def toXml(self, xparent):

        for key, value in self.items():
            elem = ElementTree.SubElement(xparent, 'entry')
            typ = type(elem).__name__

            elem.set('key', key)
            elem.set('type', typ)

            if typ in DataSet._xmlTypes:
                DataSet._xmlTypes[typ][0](elem, value)
            else:
                elem.set('value', nstr(value))

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


Question:
Creates and returns the collection from given array

@param array $templates Pairs of key-value where: key - template's index, value - template's content
@return Templates

public static function fromArray(array $templates): Templates
    {
        // No templates. Nothing to do.
        if (empty($templates)) {
            return new static();
        }

        $result = new static();

        foreach ($templates as $index => $template) {
            $result->add(new Template($template), $index);
        }

        return $result;
    }

public function populateCollection(RouteCollection $routes): RouteCollection
    {
        foreach ($this->items as $route) {
            if ($route instanceof self) {
                $route->populateCollection($routes);
            } else {
                $routes->add(...$route);
            }
        }

        return $routes;
    }

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


Question:
/*
return the number of items on stock. this will either return the actual stock
count, OR 999.999 if an unlimited number of items may be purchased.
@return double

public function TotalStockAvailable()
    {
        $bStock = $this->getAvailableStock();
        // if the article is set to auto deactivate on zero stock, we have a limited
        // supply. if on the other hand, the article remains active on zero stock, we have an
        // unlimited supply
        if (1 == $this->CheckActivateOrDeactivate(0)) {
            // we may also not allow any more purchases than available stock, if the article is marked as show_preorder_on_zero_stock
            if (false == $this->fieldShowPreorderOnZeroStock) {
                $bStock = 999999;
            }
        }

        return $bStock;
    }

func (mysqlFlavor) waitUntilPositionCommand(ctx context.Context, pos Position) (string, error) {
	// A timeout of 0 means wait indefinitely.
	timeoutSeconds := 0
	if deadline, ok := ctx.Deadline(); ok {
		timeout := time.Until(deadline)
		if timeout <= 0 {
			return "", vterrors.Errorf(vtrpc.Code_DEADLINE_EXCEEDED, "timed out waiting for position %v", pos)
		}

		// Only whole numbers of seconds are supported.
		timeoutSeconds = int(timeout.Seconds())
		if timeoutSeconds == 0 {
			// We don't want a timeout <1.0s to truncate down to become infinite.
			timeoutSeconds = 1
		}
	}

	return fmt.Sprintf("SELECT WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS('%s', %v)", pos, timeoutSeconds), nil
}

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


Question: Returns all specs found for the model.  if none found it returns an empty array

def find_specs
      specs_found = []
      # Check for specs the object owns
      if self.respond_to? :specs
        object_specs = specs
        unless object_specs.nil?
          if object_specs.class == Origen::Specs::Spec
            specs_found << object_specs
          else
            specs_found.concat(object_specs)
          end
        end
      end
      sub_blocks.each do |_name, sb|
        next unless sb.respond_to? :specs
        child_specs = sb.specs
        unless child_specs.nil?
          if child_specs.class == Origen::Specs::Spec
            specs_found << child_specs
          else
            specs_found.concat(child_specs)
          end
        end
      end
      specs_found
    end

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

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

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

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


Question:
// Identifier transforms the container steps in the Yaml and assigns a unique
// container identifier.

func Identifier(c *yaml.Config) error {

	// creates a random prefix for the build
	rand := base64.RawURLEncoding.EncodeToString(
		securecookie.GenerateRandomKey(8),
	)

	for i, step := range c.Services {
		step.ID = fmt.Sprintf("drone_%s_%d", rand, i)
	}

	for i, step := range c.Pipeline {
		step.ID = fmt.Sprintf("drone_%s_%d", rand, i+len(c.Services))
	}

	return nil
}

def find_path(self, test_function=None, on_targets=False):

        assert self.has_referential_domain(), "need context set"

        if not test_function:
            test_function = lambda x, y: True

        def find_path_inner(part, prefix):
            name, structure = part
            if test_function(name, structure):
                yield prefix + [name]
            if isinstance(structure, DictCell):
                for sub_structure in structure:
                    for prefix2 in find_path_inner(sub_structure,\
                            prefix[:] + [name]):
                        yield prefix2

        prefix = []
        if on_targets:
            # apply search to the first target
            results = []
            for _, instance in self.iter_singleton_referents():
                for part in instance:
                    for entry in find_path_inner(part, prefix[:]):
                        results.append(['target'] + entry)
                while results:
                    yield results.pop()
                break # only use first instance
        else:
            # apply search to self
            for part in self:
                for entry in find_path_inner(part, prefix[:]):
                    yield entry

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


Question:
Execute a POST request against the API

@param $str_action
@param null $obj_request_body

private function executePostRequest($str_action, $obj_request_body = null)
    {
        $arr_options = [];
        if(null !== $obj_request_body) {
            $arr_options['json'] = $obj_request_body;
        }
        $obj_response = $this->httpClient()->post($this->actionUrl($str_action), $arr_options);
        $this->obj_last_response = json_decode((string)$obj_response->getBody());
    }

public function buildUrl()
    {
        $url = $this->getApiUrl();
        if ($endpoint = $this->getEndpoint()) {
            $url .= $endpoint;
        }
        if ($id = $this->getId()) {
            $url .= '/'.$id;
        }
        $parameters = [];
        if ($include = $this->getInclude()) {
            if (is_array($include)) {
                $include = implode(',', $include);
            }
            $parameters['include'] = $include;
        }
        if ($filters = $this->getFilters()) {
            if (!empty($filters)) {
                $parameters['filter'] = $filters;
            }
        }
        if ($pageSize = $this->getPageSize()) {
            if (!empty($pageSize)) {
                $parameters['page'] = ['size' => $pageSize];
            }
        }
        if ($sort = $this->getSort()) {
            if (!empty($sort)) {
                $parameters['sort'] = $sort;
            }
        }
        if ($parameters) {
            $url .= '?'.http_build_query($parameters);
        }
        return $url;
    }

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


Question:
// TypeBool will add an error to the Validator if the first
// element of data.Values[field] cannot be converted to a bool.

func (v *Validator) TypeBool(field string) *ValidationResult {
	if _, err := strconv.ParseBool(v.data.Get(field)); err != nil {
		// note: "true or false" is a more natural colloquial term than "bool"
		return v.addTypeError(field, "true or false")
	} else {
		return validationOk
	}
}

public function setErrorByCode($code)
    {
        if (is_numeric($code)) {
            $code = ShopgateLibraryException::getMessageFor($code);
        }
        $this->setNotValidMessage($code);

        return $this;
    }

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


Question: Implementation of urllib3's urlopen.

def urlopen(self, method, url, body=None, headers=None, **kwargs):
        """"""
        # pylint: disable=arguments-differ
        # We use kwargs to collect additional args that we don't need to
        # introspect here. However, we do explicitly collect the two
        # positional arguments.

        # Use a kwarg for this instead of an attribute to maintain
        # thread-safety.
        _credential_refresh_attempt = kwargs.pop(
            '_credential_refresh_attempt', 0)

        if headers is None:
            headers = self.headers

        # Make a copy of the headers. They will be modified by the credentials
        # and we want to pass the original headers if we recurse.
        request_headers = headers.copy()

        self.credentials.before_request(
            self._request, method, url, request_headers)

        response = self.http.urlopen(
            method, url, body=body, headers=request_headers, **kwargs)

        # If the response indicated that the credentials needed to be
        # refreshed, then refresh the credentials and re-attempt the
        # request.
        # A stored token may expire between the time it is retrieved and
        # the time the request is made, so we may need to try twice.
        # The reason urllib3's retries aren't used is because they
        # don't allow you to modify the request headers. :/
        if (response.status in self._refresh_status_codes
                and _credential_refresh_attempt < self._max_refresh_attempts):

            _LOGGER.info(
                'Refreshing credentials due to a %s response. Attempt %s/%s.',
                response.status, _credential_refresh_attempt + 1,
                self._max_refresh_attempts)

            self.credentials.refresh(self._request)

            # Recurse. Pass in the original headers, not our modified set.
            return self.urlopen(
                method, url, body=body, headers=headers,
                _credential_refresh_attempt=_credential_refresh_attempt + 1,
                **kwargs)

        return response

def get_link(self, peer):

        for access in peer.accesses:
            if access.type == 'mqtt':
                break
        else:
            # No MQTT access found
            return None

        # Get server access tuple
        server = (access.server.host, access.server.port)

        with self.__lock:
            try:
                # Get existing link
                return self._links[server]

            except KeyError:
                # Create a new link
                link = self._links[server] = MQTTLink(access)
                return link

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


Question:
value can be a String (for a single entry) or a List<String> for multiple entries

@param b
@return

public static Map<String, Object> getHeaders(Bundle b) {
	Dictionary<String, String> headers = b.getHeaders();
	Enumeration<String> keys = headers.keys();
	Enumeration<String> values = headers.elements();

	String key, value;
	Object existing;
	List<String> list;
	Map<String, Object> _headers = new HashMap<String, Object>();
	while (keys.hasMoreElements()) {
	    key = keys.nextElement();
	    value = StringUtil.unwrap(values.nextElement());
	    existing = _headers.get(key);
	    if (existing != null) {
		if (existing instanceof String) {
		    list = new ArrayList<>();
		    list.add((String) existing);
		    _headers.put(key, list);
		}
		else list = (List<String>) existing;
		list.add(value);
	    }
	    else _headers.put(key, value);
	}

	return _headers;
    }

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

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


Question: // New creates a new comandante

func New(binaryName, description string) *Comandante {
	c := &Comandante{
		binaryName:         binaryName,
		description:        description,
		registeredCommands: make([]*Command, 0),
	}

	return c
}

private function instantiateParameters(Command $command) {
        return array_map(function(\ReflectionParameter $param) {
            return $this->container->get($param->getType()->getName());
        }, (new ReflectionClass(get_class($command)))->getMethod('execute')->getParameters());
    }

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


Question:
Performs the dialog actions depending on the initialized action and displays the dialog form.<p>

@throws Exception if writing to the JSP out fails

public void displayDialog() throws Exception {

        initAdminTool();
        getToolManager().setCurrentToolPath(this, getParentPath());

        JspWriter out = getJsp().getJspContext().getOut();
        out.print(htmlStart());
        out.print(bodyStart(null));
        out.print("<form name='editor' method='post' target='_top' action='");
        out.print(getJsp().link("/system/workplace/editors/editor.jsp"));
        out.print("'>\n");
        out.print(allParamsAsHidden());
        out.print("</form>\n");
        out.print("<script type='text/javascript'>\n");
        out.print("document.forms['editor'].submit();\n");
        out.print("</script>\n");
        out.print(dialogContentStart(getParamTitle()));
        out.print(dialogContentEnd());
        out.print(dialogEnd());
        out.print(bodyEnd());
        out.print(htmlEnd());
    }

private static void parseErrorPages(final ErrorPageType errorPageType, final WebApp webApp) {
		final WebAppErrorPage errorPage = new WebAppErrorPage();
		if (errorPageType.getErrorCode() != null) {
			errorPage.setErrorCode(errorPageType.getErrorCode().getValue().toString());
		}
		if (errorPageType.getExceptionType() != null) {
			errorPage.setExceptionType(errorPageType.getExceptionType().getValue());
		}
		if (errorPageType.getLocation() != null) {
			errorPage.setLocation(errorPageType.getLocation().getValue());
		}
		if (errorPage.getErrorCode() == null && errorPage.getExceptionType() == null) {
			errorPage.setExceptionType(ErrorPageModel.ERROR_PAGE);
		}
		webApp.addErrorPage(errorPage);
	}

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


Question:
Returns the field descriptors given in the the field names list.

@param fieldNames The field names, separated by commas
@return The field descriptors in the order given by the field names
@throws NoSuchFieldException If a field hasn't been found

public ArrayList getFields(String fieldNames) throws NoSuchFieldException
    {
        ArrayList          result    = new ArrayList();
        FieldDescriptorDef fieldDef;
        String             name;

        for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)
        {
            name = it.getNext();
            fieldDef = getField(name);
            if (fieldDef == null)
            {
                throw new NoSuchFieldException(name);
            }
            result.add(fieldDef);
        }
        return result;
    }

function parseTagged(definition, taggedTypes) {
	let match = definition.match(/^(\w+)(?:\((.*)\))?$/),
		tag, args, typeInfo
	if (!match) {
		return
	}

	// Get type info
	tag = match[1]
	typeInfo = taggedTypes[tag]
	if (!typeInfo) {
		return
	}

	// Special no-'()' case: only match 'tag' if minArgs is zero
	if (typeInfo.minArgs > 0 && match[2] === undefined) {
		return
	}

	// Parse and check args
	args = (match[2] || '').trim().split(/\s*,\s*/)
	if (args.length === 1 && args[0] === '') {
		// Especial empty case
		args = []
	}
	args = args.map((arg, i) => {
		if (!arg) {
			if (!typeInfo.sparse) {
				throw new Error('Missing argument at position ' + i + ' for tagged type ' + tag)
			}
			return
		}

		if (typeInfo.numeric) {
			arg = Number(arg)
			if (isNaN(arg)) {
				throw new Error('Invalid numeric argument at position ' + i + ' for tagged type ' + tag)
			}
		}

		return arg
	})
	args.original = definition
	if (args.length < typeInfo.minArgs) {
		throw new Error('Too few arguments for tagged type ' + tag)
	} else if (typeInfo.maxArgs && args.length > typeInfo.maxArgs) {
		throw new Error('Too many arguments for tagged type ' + tag)
	}

	return new Field(typeInfo.type, typeInfo.parseArgs ? typeInfo.parseArgs(args) : args)
}

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


Question: Example of deleting a subscription.

public ProjectSubscriptionName deleteSubscription(String subscriptionId) throws Exception {
    // [START pubsub_delete_subscription]
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      subscriptionAdminClient.deleteSubscription(subscriptionName);
      return subscriptionName;
    }
    // [END pubsub_delete_subscription]
  }

public GetSubscriptionDefinitionResult withTags(java.util.Map<String, String> tags) {
        setTags(tags);
        return this;
    }

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


Question:
[getFormGenerator description].

@return FormGenerator

protected function getFormGenerator()
    {
        if (null === $this->formGenerator) {
            $this->formGenerator = new FormGenerator($this->getContainer()->get('filesystem'),  __DIR__.'/../Resources/skeletons/form');
        }

        return $this->formGenerator;
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        parent::visit($visitor, $generator, $data->content);
        $visitor->setHeader(
            'Location',
            $this->router->generate(
                'ezpublish_rest_loadContent',
                array('contentId' => $data->content->contentInfo->id)
            )
        );
        $visitor->setStatus(201);
    }

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