Question:
The gid that the subprocess will switch to. If the group attribute is
 given as a group name, it is converted to a gid by Etc.getgrnam
 TODO migrate to shellout/unix.rb

def gid
      return group.kind_of?(Integer) ? group : Etc.getgrnam(group.to_s).gid if group
      return Etc.getpwuid(uid).gid if using_login?
      nil
    end

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

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

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

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

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

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

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

    return db_refs, ont_type, relevant_ambiguities

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


Question:
Products collection.

@return array

public function getLoadedProductCollection()
    {
        $params = $this->getRequest()->getParams();
        //check for param code and id
        if (! isset($params['customer_id']) ||
            ! isset($params['code']) ||
            ! $this->helper->isCodeValid($params['code'])
        ) {
            $this->helper->log('Recently viewed no id or valid code is set');
            return [];
        }

        $productsToDisplay = [];
        $mode = $this->getRequest()->getActionName();
        $customerId = (int) $this->getRequest()->getParam('customer_id');
        $limit = (int) $this->recommnededHelper->getDisplayLimitByMode($mode);

        //login customer to receive the recent products
        $session = $this->sessionFactory->create();
        $isLoggedIn = $session->loginById($customerId);
        $productIds = $this->catalog->getRecentlyViewed($customerId, $limit);

        //get product collection to check for salable
        $productCollection = $this->catalog->getProductCollectionFromIds($productIds);

        //show products only if is salable
        foreach ($productCollection as $product) {
            if ($product->isSalable()) {
                $productsToDisplay[$product->getId()] = $product;
            }
        }
        $this->helper->log(
            'Recentlyviewed customer  : ' . $customerId . ', mode ' . $mode
            . ', limit : ' . $limit .
            ', items found : ' . count($productIds) . ', is customer logged in : '
            . $isLoggedIn . ', products :' . count($productsToDisplay)
        );

        $session->logout();

        return $productsToDisplay;
    }

public void setProductModules(final String name, final List<String> moduleNames) {
        final DbProduct dbProduct = getProduct(name);
        dbProduct.setModules(moduleNames);
        repositoryHandler.store(dbProduct);
    }

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


Question:
Build a task from a callable.

@param callable $callable

@return ClosureTask

protected function buildTaskFromCallable($callable)
    {
        $task = new ClosureTask();
        $task->setContainer($this->container);
        $task->setClosure(function () use ($callable, $task) {
            list($class, $method) = is_array($callable) ? $callable : explode('::', $callable);

            return $this->getContainer()->get($class)->$method($task);
        });

        return $task;
    }

func (m *MockEnviron) Bootstrap(arg0 environs.BootstrapContext, arg1 context.ProviderCallContext, arg2 environs.BootstrapParams) (*environs.BootstrapResult, error) {
	ret := m.ctrl.Call(m, "Bootstrap", arg0, arg1, arg2)
	ret0, _ := ret[0].(*environs.BootstrapResult)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

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


Question: // Current implements the Iterator interface.

func (it *Iterator4Chunk) Current() Row {
	if it.cursor == 0 || int(it.cursor) > it.Len() {
		return it.End()
	}
	return it.chk.GetRow(int(it.cursor) - 1)
}

def run_iteration(self):
        '''
        '''

        self._employer_phase()
        self._calc_probability()
        self._onlooker_phase()
        self._check_positions()

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


Question: Wrap LocalCaller to execute remote exec functions locally on the Minion

def caller(self, fun, **kwargs):
        '''

        '''
        self.client_cache['caller'].cmd(fun, *kwargs['arg'], **kwargs['kwarg'])

async def handle_client_kill_job(self, client_addr, message: ClientKillJob):

        # Check if the job is not in the queue
        if (client_addr, message.job_id) in self._waiting_jobs:
            del self._waiting_jobs[(client_addr, message.job_id)]
            # Do not forget to send a JobDone
            await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(message.job_id, ("killed", "You killed the job"),
                                                                                0.0, {}, {}, {}, "", None, "", ""))
        # If the job is running, transmit the info to the agent
        elif (client_addr, message.job_id) in self._job_running:
            agent_addr = self._job_running[(client_addr, message.job_id)][0]
            await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendKillJob((client_addr, message.job_id)))
        else:
            self._logger.warning("Client %s attempted to kill unknown job %s", str(client_addr), str(message.job_id))

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


Question:
@private

Determine if two members are equal.

function memberEqual(source, target) {
  if(typeof source === 'string'
    && typeof target === 'string') {
    return source === target;
  }else if(Buffer.isBuffer(source) && Buffer.isBuffer(target)) {
    return bufferEqual(source, target);
  }

  return false;
}

protected function isSame(string $key, string $field) : bool
    {
        $other = $this->param[$key];

        if (isset($other) && $field === $other) {
            return true;
        }

        $this->errors[$field.self::ERROR] = $this->convertToFieldName($field).' value must be same as '.
            $this->convertToFieldName($key).'.';

        return false;
    }

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


Question:
将列表写入文件，覆盖模式，编码为UTF-8

@param <T> 集合元素类型
@param list 列表
@param file 绝对路径
@return 目标文件
@throws IORuntimeException IO异常
@since 3.2.0

public static <T> File writeUtf8Lines(Collection<T> list, File file) throws IORuntimeException {
		return writeLines(list, file, CharsetUtil.CHARSET_UTF_8);
	}

def do_format(self, format):

        fmt = ('jpg' if (format is None) else format)
        if (fmt == 'png'):
            self.logger.debug("format: png")
            self.mime_type = "image/png"
            self.output_format = fmt
            format = 'png'
        elif (fmt == 'jpg'):
            self.logger.debug("format: jpg")
            self.mime_type = "image/jpeg"
            self.output_format = fmt
            format = 'jpeg'
        elif (fmt == 'webp'):
            self.logger.debug("format: webp")
            self.mime_type = "image/webp"
            self.output_format = fmt
            format = 'webp'
        else:
            raise IIIFError(code=415, parameter='format',
                            text="Unsupported output file format (%s), only png,jpg,webp are supported." % (fmt))
        if (self.outfile is None):
            # Create temp
            f = tempfile.NamedTemporaryFile(delete=False)
            self.outfile = f.name
            self.outtmp = f.name
            self.image.save(f, format=format)
        else:
            # Save to specified location
            self.image.save(self.outfile, format=format)

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


Question:
// SetEtcdVersionKeyValue writes the given version to the etcd 'etcd_version' key.
// If no error is returned, the write was successful, indicating the etcd server is available
// and able to perform consensus writes.

func (e *CombinedEtcdClient) SetEtcdVersionKeyValue(version *EtcdVersion) error {
	return e.Put(version, "etcd_version", version.String())
}

def _init_config(self):

        system = platform.system().lower()
        leveldb_fallback_dir = os.path.expanduser("~")
        if system.startswith("darwin"):
            leveldb_fallback_dir = os.path.join(
                leveldb_fallback_dir, "Library", "Ethereum"
            )
        elif system.startswith("windows"):
            leveldb_fallback_dir = os.path.join(
                leveldb_fallback_dir, "AppData", "Roaming", "Ethereum"
            )
        else:
            leveldb_fallback_dir = os.path.join(leveldb_fallback_dir, ".ethereum")
        leveldb_fallback_dir = os.path.join(leveldb_fallback_dir, "geth", "chaindata")

        if not os.path.exists(self.config_path):
            log.info("No config file found. Creating default: " + self.config_path)
            open(self.config_path, "a").close()

        config = ConfigParser(allow_no_value=True)
        config.optionxform = str
        config.read(self.config_path, "utf-8")
        if "defaults" not in config.sections():
            self._add_default_options(config)

        if not config.has_option("defaults", "leveldb_dir"):
            self._add_leveldb_option(config, leveldb_fallback_dir)

        if not config.has_option("defaults", "dynamic_loading"):
            self._add_dynamic_loading_option(config)

        with codecs.open(self.config_path, "w", "utf-8") as fp:
            config.write(fp)

        leveldb_dir = config.get(
            "defaults", "leveldb_dir", fallback=leveldb_fallback_dir
        )
        return os.path.expanduser(leveldb_dir)

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


Question:
Build where (or selection) statement for a single field using the
provided operation

@param field
field
@param value
value
@param operation
operation
@return where clause

public String buildWhere(String field, Object value, String operation) {
		return CoreSQLUtils.quoteWrap(field) + " "
				+ (value != null ? operation + " ?" : "IS NULL");
	}

func (s *DateOptions) SetSourceField(v string) *DateOptions {
	s.SourceField = &v
	return s
}

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


Question:
Mass number for a atom with a given atomic number and exact mass.
@param atomicNumber atomic number
@param exactMass exact mass
@return the mass number (or null) if no mass number was found
@throws IOException isotope configuration could not be loaded

private Integer massNumber(int atomicNumber, double exactMass) throws IOException {
        String symbol = PeriodicTable.getSymbol(atomicNumber);
        IIsotope isotope = Isotopes.getInstance().getIsotope(symbol, exactMass, 0.001);
        return isotope != null ? isotope.getMassNumber() : null;
    }

public void marshall(ElastiCacheInstanceDetails elastiCacheInstanceDetails, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getNodeType(), NODETYPE_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getProductDescription(), PRODUCTDESCRIPTION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: // Land tells drone to come in for landing.

func (d Driver) Land() {
	d.mutex.Lock()
	d.cmd[9] = 0x80
	d.cmd[10] = checksum(d.cmd)
	d.mutex.Unlock()
	time.Sleep(500 * time.Millisecond)
	d.mutex.Lock()
	d.cmd[9] = 0x04
	d.cmd[10] = checksum(d.cmd)
	d.mutex.Unlock()
}

def check_valid_locations(self, locations=None):

        if locations is None:
            locations = self.locations
        for location in locations:
            if (not self.is_server(location) and
                not self.is_ssh_url(location) and
                not self.has_host(location)):
                err_exit('Unknown location: %(location)s' % locals())

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


Question: // Array returns a value at key that is expected to be a []interface{}

func (mmap MarshalMap) Array(key string) ([]interface{}, error) {
	val, exists := mmap.Value(key)
	if !exists {
		return nil, fmt.Errorf(`"%s" is not set`, key)
	}

	arrayValue, isArray := val.([]interface{})
	if !isArray {
		return nil, fmt.Errorf(`"%s" is expected to be an array`, key)
	}
	return arrayValue, nil
}

public function boot(): KernelInterface
    {
        if (! $this->isBooted) {
            foreach ($this->serviceProviders as $provider) {
                $this->bootProvider($provider);
            }
            $this->isBooted = true;
        }

        return $this;
    }

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


Question:
// Stop stops s gracefully (or forcefully after timeout) and
// closes its listener.

func (s *Server) Stop() error {
	ctx, cancel := context.WithTimeout(context.Background(), s.connTimeout)
	defer cancel()

	err := s.Server.Shutdown(ctx)
	if err != nil {
		return err
	}

	// signal any TLS governor goroutines to exit
	if s.tlsGovChan != nil {
		close(s.tlsGovChan)
	}

	return nil
}

public void logout() {
        if (loginContext != null) {
            try {
                loginContext.logout();
                if (logoutLogger.isDebugEnabled()) {
                    logoutLogger.debug("[ws/#" + getId() + "] Logout successful.");
                }
            } catch (LoginException e) {
                logoutLogger.trace("[ws/#" + getId() + "] Exception occurred logging out of this WebSocket session.", e);
            }
        }
        loginContext = null;
    }

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


Question:
Returns true if Solr search is enabled.

@return true if Solr search is enabled

private boolean isSolrEnabled() {

        boolean solrEnabled = OpenCms.getSearchManager().getSolrServerConfiguration().isEnabled();
        CmsSolrIndex solrIndex = OpenCms.getSearchManager().getIndexSolr(CmsSolrIndex.DEFAULT_INDEX_NAME_OFFLINE);
        return solrEnabled && (solrIndex != null);
    }

public void log(final Level level, final String msg, final Object... args) {
        String message = msg;

        if (null != args && 0 < args.length) {
            // Is it a java.text style format?
            // Ideally we could match with Pattern.compile("\\{\\d").matcher(format).find())
            // However the cost is 14% higher, so we cheaply check for 1 of the first 4 parameters
            if (msg.indexOf("{0") >= 0 || msg.indexOf("{1") >= 0 || msg.indexOf("{2") >= 0 || msg.indexOf("{3") >= 0) {
                message = java.text.MessageFormat.format(msg, args);
            }
        }

        switch (level) {
            case ERROR:
                if (proxy.isErrorEnabled()) {
                    if (proxy instanceof LocationAwareLogger) {
                        ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.ERROR_INT, message, null, null);
                    } else {
                        proxy.error(message);
                    }
                }

                break;
            case WARN:
                if (proxy.isWarnEnabled()) {
                    if (proxy instanceof LocationAwareLogger) {
                        ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.WARN_INT, message, null, null);
                    } else {
                        proxy.warn(message);
                    }
                }

                break;
            case INFO:
                if (proxy.isInfoEnabled()) {
                    if (proxy instanceof LocationAwareLogger) {
                        ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.INFO_INT, message, null, null);
                    } else {
                        proxy.info(message);
                    }
                }

                break;
            case DEBUG:
                if (proxy.isDebugEnabled()) {
                    if (proxy instanceof LocationAwareLogger) {
                        ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.DEBUG_INT, message, null, null);
                    } else {
                        proxy.debug(message);
                    }
                }

                break;
            case TRACE:
                if (proxy.isTraceEnabled()) {
                    if (proxy instanceof LocationAwareLogger) {
                        ((LocationAwareLogger) proxy).log(null, FQCN, LocationAwareLogger.TRACE_INT, message, null, null);
                    } else {
                        proxy.trace(message);
                    }
                }

                break;
            default:
                throw new IllegalStateException("Logging level [" + level + "] is invalid");
        }
    }

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


Question:
Process columns

@param array $columnIds

@return $this

protected function processColumns($columnIds)
    {
        if (count((array) $columnIds)) {
            $this->set(self::REQUEST_QUERY_COLUMNS, $columnIds);
        }

        return $this;
    }

public function up()
    {
        // Add columns to products
        if (Schema::hasTable('products')) {
            Schema::table('products', function(Blueprint $table)
            {
                if (!Schema::hasColumn('products', 'weight_unit')) {
                    $table->string('weight_unit', 3)->nullable();
                }
                if (!Schema::hasColumn('products', 'volume_unit')) {
                    $table->string('volume_unit', 3)->nullable();
                }
                if (!Schema::hasColumn('products', 'length')) {
                    $table->decimal('length', 8, 3)->nullable();
                }
                if (!Schema::hasColumn('products', 'width')) {
                    $table->decimal('width', 8, 3)->nullable();
                }
                if (!Schema::hasColumn('products', 'height')) {
                    $table->decimal('height', 8, 3)->nullable();
                }
                if (!Schema::hasColumn('products', 'weight')) {
                    $table->decimal('weight', 8, 3)->nullable();
                }
            });
        }
    }

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


Question:
Remove old theme class and apply a new one
NOTE: if not a valid theme name, then the current name is not changed

function updateThemeClass(theme) {
        if (!theme) return;
        if (!registered(theme)) {
          $log.warn('Attempted to use unregistered theme \'' + theme + '\'. ' +
                    'Register it with $mdThemingProvider.theme().');
        }

        var oldTheme = el.data('$mdThemeName');
        if (oldTheme) el.removeClass('md-' + oldTheme +'-theme');
        el.addClass('md-' + theme + '-theme');
        el.data('$mdThemeName', theme);
        if (ctrl) {
          el.data('$mdThemeController', ctrl);
        }
      }

public function updateCMSFields(FieldList $fields)
    {
        // Update Field Objects (from parent):

        parent::updateCMSFields($fields);

        // Create Style Fields:

        $fields->addFieldsToTab(
            'Root.Style',
            [
                FieldSection::create(
                    'LinkColorStyle',
                    $this->owner->fieldLabel('LinkColorStyle'),
                    [
                        FieldGroup::create(
                            $this->owner->fieldLabel('Background'),
                            [
                                ColorField::create(
                                    'ColorBackgroundLink',
                                    $this->owner->fieldLabel('Link')
                                ),
                                ColorField::create(
                                    'ColorBackgroundHover',
                                    $this->owner->fieldLabel('Hover')
                                ),
                                ColorField::create(
                                    'ColorBackgroundActive',
                                    $this->owner->fieldLabel('Active')
                                )
                            ]
                        ),
                        FieldGroup::create(
                            $this->owner->fieldLabel('Foreground'),
                            [
                                ColorField::create(
                                    'ColorForegroundLink',
                                    $this->owner->fieldLabel('Link')
                                ),
                                ColorField::create(
                                    'ColorForegroundHover',
                                    $this->owner->fieldLabel('Hover')
                                ),
                                ColorField::create(
                                    'ColorForegroundActive',
                                    $this->owner->fieldLabel('Active')
                                )
                            ]
                        )
                    ]
                )
            ]
        );
    }

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


Question:
Converts each <a> and <img> uri in the given element to an absolute URI,
ignoring #ref URIs.

@param Element
@return void

function(articleContent) {
    var baseURI = this._doc.baseURI;
    var documentURI = this._doc.documentURI;
    function toAbsoluteURI(uri) {
      // Leave hash links alone if the base URI matches the document URI:
      if (baseURI == documentURI && uri.charAt(0) == "#") {
        return uri;
      }
      // Otherwise, resolve against base URI:
      try {
        return new URL(uri, baseURI).href;
      } catch (ex) {
        // Something went wrong, just return the original:
      }
      return uri;
    }

    var links = articleContent.getElementsByTagName("a");
    this._forEachNode(links, function(link) {
      var href = link.getAttribute("href");
      if (href) {
        // Replace links with javascript: URIs with text content, since
        // they won't work after scripts have been removed from the page.
        if (href.indexOf("javascript:") === 0) {
          var text = this._doc.createTextNode(link.textContent);
          link.parentNode.replaceChild(text, link);
        } else {
          link.setAttribute("href", toAbsoluteURI(href));
        }
      }
    });

    var imgs = articleContent.getElementsByTagName("img");
    this._forEachNode(imgs, function(img) {
      var src = img.getAttribute("src");
      if (src) {
        img.setAttribute("src", toAbsoluteURI(src));
      }
    });
  }

public function getCoverImage()
    {
        if ($this->coverImage)
        {
            return $this->coverImage;
        }

        $modelName = source_model_name($this->getNodeTypeName(), true);

        $mutatables = call_user_func([$modelName, 'getMutatables']);

        foreach ($mutatables as $mutatable => $type)
        {
            if ($type === 'gallery' && ($images = $this->getTranslationAttribute($mutatable, null, true, true)))
            {
                if ($cover = get_nuclear_cover($images))
                {
                    $this->coverImage = $cover;

                    return $cover;
                }
            }

            if ($type === 'document' && ($document = $this->getTranslationAttribute($mutatable, null, true, true)))
            {
                if ($document = get_nuclear_cover($document))
                {
                    $this->coverImage = $document;

                    return $document;
                }
            }
        }

        return null;
    }

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


Question:
Returns the options for the captcha JS widget.
@return array the options

protected function getClientOptions()
    {
        $routeRef = $routeTgl = $this->captchaAction;
        if (is_array($routeRef)) {
            $routeRef[CaptchaAction::REFRESH_GET_VAR] = 1;
            $routeTgl[CaptchaAction::TOGGLE_GET_VAR] = 1;
        } else {
            $routeRef = [$routeRef, CaptchaAction::REFRESH_GET_VAR => 1];
            $routeTgl = [$routeTgl, CaptchaAction::TOGGLE_GET_VAR => 1];
        }
        $options = [
            'refreshUrl' => Url::toRoute($routeRef),
            'toggleUrl' => Url::toRoute($routeTgl),
            'hashKey' => "yiiCaptcha/{$routeRef[0]}",
            // We have to use 'yiiCaptcha' instead of 'yiiMbCaptcha'
            // because yii\captcha\CaptchaValidator uses 'yiiCaptcha' for 'hashKey'.
        ];
        return $options;
    }

function getOptions () {
  return {
    compress: ('compress' in program) ? program.compress : false,
    debug: ('debug' in program) ? program.debug : false,
    deploy: false,
    grep: ('grep' in program) ? program.grep : false,
    invert: ('invert' in program) ? program.invert : false,
    maps: ('maps' in program) ? program.maps : false,
    reload: ('reload' in program) ? program.reload : false,
    script: ('script' in program) ? program.script : false,
    serve: ('serve' in program) ? program.serve : false,
    watch: false
  };
}

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


Question: Swap single and double curly brackets

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

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


Question:
Process any annotation which could not be managed by an update
to the the descriptor based configuration.

@param servletConfig The servlet configuration embedding a class
which is to be processed for annotations.

private void initializeNonDDRepresentableAnnotation(IServletConfig servletConfig) {
        if (com.ibm.ws.webcontainer.osgi.WebContainer.isServerStopping())
            return;

        String methodName = "initializeNonDDRepresentableAnnotation";

        String configClassName = servletConfig.getClassName();
        if (configClassName == null) {
            return; // Strange; but impossible to process; ignore.
        }

        if (!acceptAnnotationsFrom(configClassName, DO_NOT_ACCEPT_PARTIAL, DO_NOT_ACCEPT_EXCLUDED)) {
            return; // Ignore: In a metadata-complete or excluded region.
        }

        // Process: In a non-metadata-complete, non-excluded region.

        Class<?> configClass;

        try {
            configClass = Class.forName(configClassName, false, this.getClassLoader());
        } catch (ClassNotFoundException e) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                LoggingUtil.logParamsAndException(logger, Level.FINE, CLASS_NAME, methodName,
                                                  "unable to load class [{0}] which is benign if the class is never used",
                                                  new Object[] { configClassName }, e);
            }
            return;

        } catch (NoClassDefFoundError e) {
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                LoggingUtil.logParamsAndException(logger, Level.FINE, CLASS_NAME, methodName,
                                                  "unable to load class [{0}] which is benign if the class is never used",
                                                  new Object[] { configClassName }, e);
            }
            return;
        }

        checkForServletSecurityAnnotation(configClass, servletConfig);
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

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

			container_config.events = {};

			for (name in x.event) {

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

			}

		}

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

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

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

		}

		if ('style' in x) {

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

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

		}

		if ('classes' in x) {

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

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

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question: Converts the ContigOrdering file into AGP format

def write_agp(self, obj, sizes, fw=sys.stdout, gapsize=100,
                  gaptype="contig", evidence="map"):
        '''
        '''
        contigorder = [(x.contig_name, x.strand) for x in self]
        order_to_agp(obj, contigorder, sizes, fw,
                     gapsize=gapsize, gaptype=gaptype, evidence=evidence)

func (s *Service) FindTelegrafConfigs(ctx context.Context, filter influxdb.TelegrafConfigFilter, opt ...influxdb.FindOptions) (tcs []*influxdb.TelegrafConfig, n int, err error) {
	err = s.kv.View(ctx, func(tx Tx) error {
		tcs, n, err = s.findTelegrafConfigs(ctx, tx, filter)
		return err
	})
	return tcs, n, err
}

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


Question:
@param array $expressions

@return callable

public function andX(array $expressions)
    {
        return function ($object) use ($expressions) {
            foreach ($expressions as $expression) {
                if (!$expression($object)) {
                    return false;
                }
            }

            return true;
        };
    }

private function addCallback(string $method, $state) : void
    {
        $state = $this->makeCallable($state);
        $this->actions[$method] = $state;
    }

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


Question:
Gets the targetingDimension value for this TargetingCriteriaBreakdown.

@return targetingDimension   * The dimension of this breakdown

public com.google.api.ads.admanager.axis.v201902.TargetingDimension getTargetingDimension() {
        return targetingDimension;
    }

def export_model(model, model_type, export_dir, model_column_fn):

  wide_columns, deep_columns = model_column_fn()
  if model_type == 'wide':
    columns = wide_columns
  elif model_type == 'deep':
    columns = deep_columns
  else:
    columns = wide_columns + deep_columns
  feature_spec = tf.feature_column.make_parse_example_spec(columns)
  example_input_fn = (
      tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec))
  model.export_savedmodel(export_dir, example_input_fn,
                          strip_default_attrs=True)

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


Question: 1. Simple ruby polyfill; 2. Inter-character polyfill for Zhuyin

function renderSimpleRuby( $ruby ) {
  var frag = $.create( '!' )
  var clazz = $ruby.classList
  var $rb, $ru

  frag.appendChild( $.clone( $ruby ))

  $
  .tag( 'rt', frag.firstChild )
  .forEach(function( $rt ) {
    var $rb = $.create( '!' )
    var airb = []
    var irb

    // Consider the previous nodes the implied
    // ruby base
    do {
      irb = ( irb || $rt ).previousSibling
      if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i ))  break

      $rb.insertBefore( $.clone( irb ), $rb.firstChild )
      airb.push( irb )
    } while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))

    // Create a real `<h-ru>` to append.
    $ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )

    // Replace the ruby text with the new `<h-ru>`,
    // and remove the original implied ruby base(s)
    try {
      $rt.parentNode.replaceChild( $ru, $rt )
      airb.map( $.remove )
    } catch ( e ) {}
  })
  return createCustomRuby( frag )
}

def _clean_text(self, text):

        clean = []
        for char in text:
            if char in self.punc_stops:
                clean += '.'
            elif char not in self.punc:
                clean += char
            else:
                pass
        return (''.join(clean)).lower()

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


Question: // Next puts reader forward by a line

func (p *Parser) Next() (eof bool, err error) {

	// Get next record
	var records []string

	for {
		// read until valid record
		records, err = p.Reader.Read()
		if err != nil {
			if err.Error() == "EOF" {
				return true, nil
			}
			return false, err
		}
		if len(records) > 0 {
			break
		}
	}

	if len(p.indices) == 0 {
		p.indices = make([]int, len(records))
		// mapping simple index
		for i := 0; i < len(records); i++ {
			p.indices[i] = i + 1
		}
	}

	// record should be a pointer
	for i, record := range records {
		idx := p.indices[i]
		if idx == 0 {
			// skip empty index
			continue
		}
		// get target field
		field := p.ref.Field(idx - 1)
		switch field.Kind() {
		case reflect.String:
			// Normalize text
			if p.normalize >= 0 {
				record = p.normalize.String(record)
			}
			field.SetString(record)
		case reflect.Bool:
			if record == "" {
				field.SetBool(false)
			} else {
				col, err := strconv.ParseBool(record)
				if err != nil {
					return false, err
				}
				field.SetBool(col)
			}
		case reflect.Int:
			if record == "" {
				field.SetInt(0)
			} else {
				col, err := strconv.ParseInt(record, 10, 0)
				if err != nil {
					return false, err
				}
				field.SetInt(col)
			}
		default:
			return false, errors.New("Unsupported field type")
		}
	}

	return false, nil
}

func (scanner *Scanner) Advance() {
	if scanner.CanRead() {
		scanner.index++
		if scanner.CanRead() && scanner.Char() == '\n' {
			scanner.row++
			scanner.col = 1
		} else {
			scanner.col++
		}
	}
}

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


Question:
return the hash for this innermsg, token, seqnum
        return digest bytes

def __make_hash(cls, innermsg, token, seqnum):

        hobj = hmacNew(token, digestmod=hashfunc)
        hobj.update(innermsg)
        hobj.update(cls.__byte_packer(seqnum))
        return hobj.digest()

def encode_request(uuid, partition_id, interrupt):

    client_message = ClientMessage(payload_size=calculate_size(uuid, partition_id, interrupt))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(uuid)
    client_message.append_int(partition_id)
    client_message.append_bool(interrupt)
    client_message.update_frame_length()
    return client_message

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


Question:
// New accepts a variable that implemented interface io.Writer
// for write-only purpose operations.

func New(w io.Writer) *TzArchive {
	return &TzArchive{
		writer:      w,
		isHasWriter: true,
	}
}

public List<List<String>> getAllScopes() {
    this.checkInitialized();
    final ImmutableList.Builder<List<String>> builder = ImmutableList.<List<String>>builder();
    final Consumer<Integer> _function = (Integer it) -> {
      List<String> _get = this.scopes.get(it);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("No scopes are available for index: ");
      _builder.append(it);
      builder.add(Preconditions.<List<String>>checkNotNull(_get, _builder));
    };
    this.scopes.keySet().forEach(_function);
    return builder.build();
  }

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


Question:
指定分隔符的 Quotes

@param string $spec
@param string $sep
@param int    $pos
@return string

protected function quoteNameWithSeparator($spec, $sep, $pos)
    {
        $len   = strlen($sep);
        $part1 = $this->quoteName(substr($spec, 0, $pos));
        $part2 = $this->replaceName(substr($spec, $pos + $len));
        return "{$part1}{$sep}{$part2}";
    }

func (node *SetExpr) Format(buf *TrackedBuffer) {
	// We don't have to backtick set variable names.
	if node.Name.EqualString("charset") || node.Name.EqualString("names") {
		buf.Myprintf("%s %v", node.Name.String(), node.Expr)
	} else if node.Name.EqualString(TransactionStr) {
		sqlVal := node.Expr.(*SQLVal)
		buf.Myprintf("%s %s", node.Name.String(), strings.ToLower(string(sqlVal.Val)))
	} else {
		buf.Myprintf("%s = %v", node.Name.String(), node.Expr)
	}
}

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


Question:
Start the background file upload service.
@return the uploadId string. If you have passed your own uploadId in the constructor, this
method will return that same uploadId, otherwise it will return the automatically
generated uploadId

public String startUpload() {
        UploadService.setUploadStatusDelegate(params.id, delegate);

        final Intent intent = new Intent(context, UploadService.class);
        this.initializeIntent(intent);
        intent.setAction(UploadService.getActionUpload());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (params.notificationConfig == null) {
                throw new IllegalArgumentException("Android Oreo requires a notification configuration for the service to run. https://developer.android.com/reference/android/content/Context.html#startForegroundService(android.content.Intent)");
            }
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }

        return params.id;
    }

public function imageFactory()
    {
        if ($this->imageFactory === null) {
            $this->imageFactory = $this->createImageFactory();
        }

        return $this->imageFactory;
    }

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


Question:
Removes a job.
@param jobId The UUID identifying the job to be removed.
@param complete A value indicating whether the job has been completed.

private void removeScheduledJob(UUID jobId, boolean complete) {
    ScheduledJob sched = jobs.remove(jobId);
    if (sched != null) {
      if (complete) {
        sched.monitor.notifyComplete();
        if (logger.isInfoEnabled()) {
          logger.info("Job complete (" + jobId.toString() + ")");
        }
      } else {
        sched.monitor.notifyCancelled();
        if (logger.isInfoEnabled()) {
          logger.info("Job cancelled (" + jobId.toString() + ")");
        }
      }
      jobs.remove(jobId);
      scheduler.removeJob(jobId);
    }
    if (jobs.isEmpty()) {
      synchronized (this.complete) {
        this.complete.notifyAll();
      }
    }
  }

def delete_target(target_id)
      # In order to delete the target, we have to set it to non-active.
      # Therefore,first retrieve target info and act accordingly to target info
      # returned
      target_data = JSON.parse(retrieve_target(target_id)) # have to JSON.parse
      # retrieve_target's results since they're in string format
      target_result_code = target_data["result_code"]
      if target_result_code != "AuthenticationFailure"
        if target_result_code != "UnknownTarget"
          target_active_flag = target_data["target_record"]["active_flag"]
          target_status = target_data["status"]
          if target_result_code == "Success"
            if target_active_flag == true && target_status == "success"
              return {:result_code => "TargetActive"}.to_json
            elsif target_active_flag == false && target_status == "success"
              # if we reached this point, the target is fine, inactive and
              # ready to be deleted
              date_timestamp = Time.now.httpdate
              target_id_url = TARGETS_URL + '/' + target_id
              target_id_suburl = '/targets' + '/' + target_id
              signature = self.build_signature(target_id_suburl, nil, 'DELETE', date_timestamp)
              raise ArgumentError.new('Signature returned nil. Aborting...') if signature == nil
              authorization_header = "VWS " + @accesskey + ":" + signature
                begin
                  RestClient.delete(target_id_url,
                                             :'Date' => date_timestamp,
                                             :'Authorization' => authorization_header)
                rescue => e
                  e.response
                end
            else
              return {:result_code => "#{target_status}"}.to_json
            end
          end
        else
          return {:result_code => "UnknownTarget"}.to_json
        end
      else
        return {:result_code => "AuthenticationFailure"}.to_json
      end
    end

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


Question: // FindIdentityMemberships returns an array of Identity objects with the (optionally) specified resource type in which the specified Identity is a member

func (m *GormIdentityRepository) FindIdentityMemberships(ctx context.Context, identityID uuid.UUID, resourceType *string) ([]authorization.IdentityAssociation, error) {
	defer goa.MeasureSince([]string{"goa", "db", "identity", "FindIdentityMemberships"}, time.Now())
	associations := []authorization.IdentityAssociation{}

	var identities []Identity

	// query for identities in which the user is a member
	q := m.db.Table(m.TableName()).Preload("IdentityResource").Preload("IdentityResource.ParentResource")

	// with the specified resourceType
	if resourceType != nil {
		q = q.Joins("JOIN resource r ON r.resource_id = identities.identity_resource_id").
			Joins("JOIN resource_type rt ON r.resource_type_id = rt.resource_type_id AND rt.name = ?", resourceType)
	}

	err := q.Where(`identities.id IN (WITH RECURSIVE m AS (
			SELECT member_of FROM	membership WHERE member_id = ?
      UNION SELECT p.member_of	FROM membership p INNER JOIN m ON m.member_of = p.member_id)
		  SELECT member_of FROM m)`, identityID).
		Find(&identities).Error

	if err != nil {
		return nil, err
	}

	for _, identity := range identities {
		// TODO for some reason gorm's nested preloads aren't working here, some time should be spent in the gorm source code to find out why,
		// after which we should be able to remove this code
		if identity.IdentityResource.ParentResourceID != nil && identity.IdentityResource.ParentResource == nil {

			var native resource.Resource
			err = m.db.Table("resource").Where("resource_id = ?", identity.IdentityResource.ParentResourceID).Find(&native).Error
			if err != nil {
				return nil, err
			}
			identity.IdentityResource.ParentResource = &native
		}

		associations = authorization.AppendAssociation(associations, identity.IdentityResourceID.String, &identity.IdentityResource.Name, identity.IdentityResource.ParentResourceID, &identity.ID, true, nil)
	}

	return associations, nil
}

public function loadUserGroupByRemoteId(Request $request)
    {
        $contentInfo = $this->contentService->loadContentInfoByRemoteId($request->query->get('remoteId'));
        $userGroup = $this->userService->loadUserGroup($contentInfo->id, Language::ALL);
        $userGroupLocation = $this->locationService->loadLocation($contentInfo->mainLocationId);
        $contentType = $this->contentTypeService->loadContentType($contentInfo->contentTypeId);

        return new Values\RestUserGroup(
            $userGroup,
            $contentType,
            $contentInfo,
            $userGroupLocation,
            $this->contentService->loadRelations($userGroup->getVersionInfo())
        );
    }

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


Question: called while holding class lock

private ClassData fetchBytecodeFromRemote(String className) {
        ClusterService cluster = nodeEngine.getClusterService();
        ClassData classData;
        boolean interrupted = false;
        for (Member member : cluster.getMembers()) {
            if (isCandidateMember(member)) {
                continue;
            }
            try {
                classData = tryToFetchClassDataFromMember(className, member);
                if (classData != null) {
                    if (logger.isFineEnabled()) {
                        logger.finest("Loaded class " + className + " from " + member);
                    }
                    return classData;
                }
            } catch (InterruptedException e) {
                // question: should we give-up on loading at this point and simply throw ClassNotFoundException?
                interrupted = true;
            } catch (Exception e) {
                if (logger.isFinestEnabled()) {
                    logger.finest("Unable to get class data for class " + className
                            + " from member " + member, e);
                }
            }
        }
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
        return null;
    }

public static <T> Position.ReadWrite<T> readWrite(final Class<T> type) {
        return readWrite((Type) type);
    }

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


Question: // Call method on IDispatch with parameters.

func (d *Dispatch) Call(method string, params ...interface{}) (result *VARIANT, err error) {
	id, err := d.GetId(method)
	if err != nil {
		return
	}

	result, err = d.Invoke(id, DISPATCH_METHOD, params)
	return
}

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

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

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


Question: Returns the pivot element.

private int ssPivot(int Td, int PA, int first, int last) {
        int middle;// SA pointer
        int t = last - first;
        middle = first + t / 2;

        if (t <= 512) {
            if (t <= 32) {
                return ssMedian3(Td, PA, first, middle, last - 1);
            } else {
                t >>= 2;
                return ssMedian5(Td, PA, first, first + t, middle, last - 1 - t, last - 1);
            }
        }
        t >>= 3;
        first = ssMedian3(Td, PA, first, first + t, first + (t << 1));
        middle = ssMedian3(Td, PA, middle - t, middle, middle + t);
        last = ssMedian3(Td, PA, last - 1 - (t << 1), last - 1 - t, last - 1);
        return ssMedian3(Td, PA, first, middle, last);
    }

protected function moveChecksBackToTarget()
    {
        if (isset($this->result->checks)) {
            $this->checks = $this->result->checks;

            unset($this->result->checks);
        }
    }

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


Question: Resolve modules paths

function ( file ) {
			var resolved;
			var expanded = grunt.file.expand( file )[0];

			if ( !expanded ) {
				resolved = require.resolve( file );

			} else {
				resolved = "./" + expanded;
			}

			return resolved;
		}

public function getPathFromUrl($url)
    {
        $basename = $this->storageUrl ? basename($this->storageUrl) : basename($this->storageDir);
        $basename && $url = preg_replace("/(.*$basename\/)/", '', $url);
        return $url;
    }

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


Question:
is Holding Any Appointment for given User.

ToDo: Remove from here as needs knowledge from User

@param int $userId User to check belonging Appointments

@return bool Vacancy holds at least one Appointment of User

public function isHoldingAnyFor($userId)
    {
        $appointments = $this->appointments()->get();

        foreach ($appointments as $appointment) {
            $contact = $appointment->contact()->first();
            if ($contact->isProfileOf($userId)) {
                return true;
            }
        }

        return false;
    }

private function validateContainer($container)
    {
        if ($container === false)
            return $container;
        $resolver = new OptionsResolver();
        $resolver->setDefaults([
            'panel' => false,
            'class' => false,
            'rows' => false,
            'headerRow' => false,
            'collection' => false,
        ]);
        $resolver->setAllowedTypes('class', ['string', 'boolean']);
        $resolver->setAllowedTypes('panel', ['array', 'boolean']);
        $resolver->setAllowedTypes('rows', ['array', 'boolean']);
        $resolver->setAllowedTypes('headerRow', ['array', 'boolean']);
        $resolver->setAllowedTypes('collection', ['array', 'boolean']);
        $container = $resolver->resolve($container);

        $container['panel'] = $this->validatePanel($container['panel']);

        if (($container['panel'] !== false && $container['class'] !== false) || ( $container['panel'] === false && $container['class'] === false))
            trigger_error(sprintf('Containers must specify one of a panel (%s) or a class (%s), but not both.', $container['panel']['colour'], $container['class']), E_USER_ERROR);

        $container['collection'] = $this->validateCollection($container['collection']);

        $container['headerRow'] = $this->validateRow($container['headerRow']);
        $container['rows'] = $this->validateRows($container['rows']);

        return $container;
    }

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


Question:
Constraint that ensures that an event is scheduled in slots for which it is
    available

def _events_available_in_scheduled_slot(events, slots, X, **kwargs):

    slot_availability_array = lpu.slot_availability_array(slots=slots,
                                                          events=events)

    label = 'Event scheduled when not available'
    for row, event in enumerate(slot_availability_array):
        for col, availability in enumerate(event):
            if availability == 0:
                yield Constraint(
                    f'{label} - event: {row}, slot: {col}',
                    X[row, col] <= availability
                )

@Override  // for covariant return type
    @SuppressWarnings("unchecked")
    public ChronoLocalDateTime<Symmetry454Date> atTime(LocalTime localTime) {
        return (ChronoLocalDateTime<Symmetry454Date>) super.atTime(localTime);
    }

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


Question:
get client params

@return array

protected function getClientParams()
    {
        $agent    = $_SERVER['HTTP_USER_AGENT'];
        $bname    = 'Unknown';
        $platform = 'Unknown';

        if (preg_match('/linux/i', $agent)) {
            $platform = 'Linux';
        } elseif (preg_match('/macintosh|mac os x/i', $agent)) {
            $platform = 'Mac';
        } elseif (preg_match('/windows|win32/i', $agent)) {
            $platform = 'Windows';
        }
        if (preg_match('/Edge/i', $agent) && !preg_match('/Opera/i', $agent)) {
            $bname = 'Internet Explorer';
            $ub    = "MSIE";
        } elseif (preg_match('/MSIE/i', $agent) && !preg_match('/Opera/i', $agent)) {
            $bname = 'Internet Explorer';
            $ub    = "MSIE";
        } elseif (preg_match('/Firefox/i', $agent)) {
            $bname = 'Mozilla Firefox';
            $ub    = "Firefox";
        } elseif (preg_match('/Chrome/i', $agent)) {
            $bname = 'Google Chrome';
            $ub    = "Chrome";
        } elseif (preg_match('/Safari/i', $agent)) {
            $bname = 'Apple Safari';
            $ub    = "Safari";
        } elseif (preg_match('/Opera/i', $agent)) {
            $bname = 'Opera';
            $ub    = "Opera";
        } elseif (preg_match('/Netscape/i', $agent)) {
            $bname = 'Netscape';
            $ub    = "Netscape";
        }
        return [
            'browser' => $bname,
            'system'  => $platform,
            'machine' => php_uname('n')
        ];
    }

def new
      @parameter = Parameter.new

      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @parameter }
      end
    end

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


Question:
Action: Login
Synopsis: Login Manager
Privilege: <none>

@return void

protected function login()
    {
        $this->state = self::CONN_STATE_LOGIN_PACKET_SENT;
        $this->write(
            "Action: login\r\n"
            . "Username: " . $this->username . "\r\n"
            . "Secret: " . $this->secret . "\r\n"
            . "Events: on\r\n"
            . "\r\n"
        );
    }

public function build()
    {
        $this->overseer->clearRoles();

        if (isset($this->config['roles'])) {
            $this->saveRoles($this->config['roles']);
        }

        $this->overseer->clearPermissions();

        if (isset($this->config['permissions'])) {
            $this->savePermissions($this->config['permissions']);
        }

        $this->overseer->clearAssignments();

        if (isset($this->config['assignments'])) {
            $this->saveAssignments($this->config['assignments']);
        }
    }

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


Question: Check if a register is used in the instruction.

def has_reg(self, reg_name):
        """"""
        return any(operand.has_reg(reg_name) for operand in self.operands)

func (s *CreateTrailInput) SetIsMultiRegionTrail(v bool) *CreateTrailInput {
	s.IsMultiRegionTrail = &v
	return s
}

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


Question:
Runs the defined error module
Sets the state of the module object to \c failed and sets the error code.

@param mixed $errorCode
@param mixed $errorType
@param array $parameters
@param mixed $userParameters

@see setErrorModule(), errorModule()

function handleError( $errorCode, $errorType = false, $parameters = array(), $userParameters = false )
    {
        if ( self::$useExceptions && $errorType === "kernel" )
        {
            switch ( $errorCode )
            {
                case eZError::KERNEL_MODULE_NOT_FOUND:
                    throw new ezpModuleNotFound( $parameters["module"] );

                case eZError::KERNEL_MODULE_DISABLED:
                    if ( $parameters["check"]["view_checked"] )
                        throw new ezpModuleViewDisabled( $parameters["check"]['module'], $parameters["check"]['view'] );

                    throw new ezpModuleDisabled( $parameters["check"]['module'] );

                case eZError::KERNEL_MODULE_VIEW_NOT_FOUND:
                    throw new ezpModuleViewNotFound( $parameters["check"]['module'], $parameters["check"]['view'] );

                case eZError::KERNEL_ACCESS_DENIED:
                    throw new ezpAccessDenied;

                //case eZError::KERNEL_MOVED:
                // @todo ?

                case eZError::KERNEL_NOT_AVAILABLE:
                case eZError::KERNEL_NOT_FOUND:
                    throw new ezpContentNotFoundException( "" );

                case eZError::KERNEL_LANGUAGE_NOT_FOUND:
                        throw new ezpLanguageNotFound;
            }
        }

        if ( !$errorType )
        {
            eZDebug::writeWarning( "No error type specified for error code $errorCode, assuming kernel.\nA specific error type should be supplied, please check your code.", __METHOD__ );
            $errorType = 'kernel';
        }
        $errorModule = $this->errorModule();

        $module = self::findModule( $errorModule['module'], $this );

        if ( $module === null )
        {
            return false;
        }

        $result = $module->run( $errorModule['view'], array( $errorType, $errorCode, $parameters, $userParameters ) );
        // The error module may want to redirect to another URL, see error.ini
        if ( $this->exitStatus() != self::STATUS_REDIRECT and
             $this->exitStatus() != self::STATUS_RERUN )
        {
            $this->setExitStatus( self::STATUS_FAILED );
            $this->setErrorCode( $errorCode );
        }
        return $result;
    }

def handle_moban_file(moban_file, options):

    moban_file_configurations = load_data(None, moban_file)
    if moban_file_configurations is None:
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_INVALID_MOBAN_FILE % moban_file
        )
    if (
        constants.LABEL_TARGETS not in moban_file_configurations
        and constants.LABEL_COPY not in moban_file_configurations
    ):
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_NO_TARGETS % moban_file
        )
    check_none(moban_file_configurations, moban_file)
    version = moban_file_configurations.get(
        constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
    )
    if version == constants.DEFAULT_MOBAN_VERSION:
        mobanfile.handle_moban_file_v1(moban_file_configurations, options)
    else:
        raise exceptions.MobanfileGrammarException(
            constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
        )
    HASH_STORE.save_hashes()

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


Question: // PerformAssignmentsInstanceGroups populates InstanceGroups with default values

func PerformAssignmentsInstanceGroups(groups []*InstanceGroup) error {
	names := map[string]bool{}
	for _, group := range groups {
		names[group.ObjectMeta.Name] = true
	}

	for _, group := range groups {
		// We want to give them a stable Name as soon as possible
		if group.ObjectMeta.Name == "" {
			// Loop to find the first unassigned name like `nodes-%d`
			i := 0
			for {
				key := fmt.Sprintf("nodes-%d", i)
				if !names[key] {
					group.ObjectMeta.Name = key
					names[key] = true
					break
				}
				i++
			}
		}
	}

	return nil
}

def _initialize_expectations(self, config=None, data_asset_name=None):

        super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name)
        self._expectations_config["data_asset_type"] = "Dataset"

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


Question:
@param string $name
@param array $definition

@return \Spryker\Install\Stage\Section\SectionInterface

public function buildSection(string $name, array $definition): SectionInterface
    {
        $section = new Section($name);
        $this->setExcluded($section, $definition);
        $this->setPreCommand($section, $definition);
        $this->setPostCommand($section, $definition);

        return $section;
    }

function() {
      'use strict';
      var laxarIntegrationTechnology = this.config.get( 'laxarIntegrationTechnology' ) || 'plain';
      var artifactType = this.options.activity ? 'activity' : 'widget';

      var widgetName = util.determineArtifactName( this );
      this.widgetDirname = util.determineArtifactDirName( this, path.join( 'includes', 'widgets' ) );

      this.placeholder = {
         name: widgetName,
         description: '',
         licenseLabel: 'license',
         licenses: this.config.get( 'licenses' ),
         homepage: this.config.get( 'homepage' ),
         author: this.config.get( 'author' ),
         laxarIntegrationTechnology: laxarIntegrationTechnology,
         cssClassName: '',
         banner:  util.getBanner( this ),
         artifactType: artifactType,
         path: widgetName
      };

      this.placeholder.dependencies = bowerDefaults.dependencies;
      this.placeholder.devDependencies = bowerDefaults.devDependencies;
   }

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


Question: // Subtract returns new Money struct with value representing difference of Self and Other Money.

func (m *Money) Subtract(om *Money) (*Money, error) {
	if err := m.assertSameCurrency(om); err != nil {
		return nil, err
	}

	return &Money{amount: mutate.calc.subtract(m.amount, om.amount), currency: m.currency}, nil
}

func (node *ClientNode) RequestProcessed(reqID, index, maxCost, realCost uint64) (bv uint64) {
	node.lock.Lock()
	defer node.lock.Unlock()

	now := node.cm.clock.Now()
	node.update(now)
	node.cm.processed(node, maxCost, realCost, now)
	bv = node.bufValue + node.sumCost - node.accepted[index]
	if node.log != nil {
		node.log.add(now, fmt.Sprintf("processed  reqID=%d  bv=%d  maxCost=%d  realCost=%d  sumCost=%d  oldSumCost=%d  reportedBV=%d", reqID, node.bufValue, maxCost, realCost, node.sumCost, node.accepted[index], bv))
	}
	delete(node.accepted, index)
	return
}

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


Question:
Runs the action

@return string result content

public function run()
    {

        $model = $this->model;

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && isset($_POST['ajax'])) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return \yii\widgets\ActiveForm::validate($model);
        }

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {

                if ($this->isSaveAndNew) {
                    Yii::$app->response->format = Response::FORMAT_JSON;
                    return [
                        'message' => 'saveAndNew',
                        'saveAndNewUrl' => $this->saveAndNewUrl,
                    ];
                }

                Yii::$app->getSession()->setFlash('success', $this->successMsg);
                Yii::$app->response->format = Response::FORMAT_JSON;
                return [
                    'message' => 'success',
                    'success' => true,
                ];
            }

            Yii::$app->getSession()->setFlash('error', $this->errorMsg);
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                'message' => 'error',
                'success' => false,
                'error' => Json::encode($model->getErrors()),
            ];
        }

        return $this->controller->renderAjax($this->view, array_merge([
            'model' => $model,
        ], $this->params));
    }

def use_response_error_message?(request, response)
      if (request.path.include?('/data/') && !response.content_type.nil?)
        response.content_type.include? 'text/plain'
      else
        false
      end
    end

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *AllocateStaticIpInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "AllocateStaticIpInput"}
	if s.StaticIpName == nil {
		invalidParams.Add(request.NewErrParamRequired("StaticIpName"))
	}

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

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
Set the connection handle

@param mixed  $con connection handle
@param string $env environment

@return null

public static function setConnection($con, $env = null)
    {
        $env = self::selectEnvironment($env);
        self::$_connection[$env] = $con;

        // just send an exception when not on production mode
        if (in_array($env, array("development","test"))) {
            self::setErrorHandling(\PDO::ERRMODE_EXCEPTION);
        }
    }

private function parseHostedConfiguration(array $configuration, ContainerBuilder $container)
    {
        $entityId = ['entity_id_route' => $configuration['metadata']['entity_id_route']];
        $serviceProvider  = array_merge($configuration['service_provider'], $entityId);
        $identityProvider = array_merge($configuration['identity_provider'], $entityId);

        $container
            ->getDefinition('surfnet_saml.saml.attribute_dictionary')
            ->replaceArgument(0, $configuration['attribute_dictionary']['ignore_unknown_attributes']);

        $this->parseHostedSpConfiguration($serviceProvider, $container);
        $this->parseHostedIdpConfiguration($identityProvider, $container);
        $this->parseMetadataConfiguration($configuration, $container);
    }

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


Question:
Returns a wrapper for the given event.

        Usage:

            @dispatch.on("my_event")
            def handle_my_event(foo, bar, baz):
                ...

def on(self, event):

        handler = self._handlers.get(event, None)
        if not handler:
            raise ValueError("Unknown event '{}'".format(event))
        return handler.register

func (daemon *Daemon) LogContainerEvent(container *container.Container, action string) {
	daemon.LogContainerEventWithAttributes(container, action, map[string]string{})
}

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


Question:
Extract all actions from roles config

@param array $aclData
@return array

private function extractAllActions(array $aclData): array
    {
        $allRolesActions = [];

        // get all role actions available
        foreach ($aclData as $acl) {
            if (isset($acl['acl']['rolesActions']) && !empty ($acl['acl']['rolesActions'])) {
                foreach ($acl['acl']['rolesActions'] as $role => $actions) {
                    if (array_key_exists($role, $allRolesActions)) {
                        $allRolesActions[$role] = array_merge($allRolesActions[$role], $actions);
                    } else {
                        $allRolesActions[$role] = array_merge([], $actions);
                    }
                }
            }
        }

        return $allRolesActions;
    }

public function getAccounts()
    {
        $accounts = [];
        $groups   = $this->rpc->query("listAccounts", [0]);
        foreach($groups as $account => $balance) {
            $accounts[] = $account;
        }

        return $accounts;
    }

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


Question:
Get final dictionary. If ``crop`` is ``True``, apply
        :func:`.cnvrep.bcrop` to returned array.

def getdict(self, crop=True):

        global mp_D_Y0
        D = mp_D_Y0
        if crop:
            D = cr.bcrop(D, self.dstep.cri.dsz, self.dstep.cri.dimN)
        return D

async def prover_close_credentials_search(search_handle: int) -> None:

    logger = logging.getLogger(__name__)
    logger.debug("prover_close_credentials_search: >>> search_handle: %r",
                 search_handle)

    if not hasattr(prover_close_credentials_search, "cb"):
        logger.debug("prover_close_credentials_search: Creating callback")
        prover_close_credentials_search.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_search_handle = c_int32(search_handle)

    res = await do_call('indy_prover_close_credentials_search',
                        c_search_handle,
                        prover_close_credentials_search.cb)

    logger.debug("prover_close_credentials_search: <<< res: %r", res)
    return res

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


Question:
Computes the confidence 05 interval-factor. This value has to be combined with the mean to get the
confidence-interval.

@param meter the meter for the 05-confidence interval factor
@return the 99% confidence

public final double getConf05(final AbstractMeter meter) {
        checkIfMeterExists(meter);
        final AbstractUnivariateStatistic conf05 = new Percentile(5.0);
        final CollectionDoubleCollection doubleColl = new CollectionDoubleCollection(this.meterResults.get(meter));
        return conf05.evaluate(doubleColl.toArray(), 0, doubleColl.toArray().length);

    }

def intuition(args):
    '''

    '''

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

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

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

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

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

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

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

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


Question:
Gets the value for a parameter

@param $name
@return mixed

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

func (s *GetAttributeValuesInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetAttributeValuesInput"}
	if s.AttributeName == nil {
		invalidParams.Add(request.NewErrParamRequired("AttributeName"))
	}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.ServiceCode == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceCode"))
	}

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

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


Question: // SetSequenceNumber sets the SequenceNumber field's value.

func (s *GetShardIteratorInput) SetSequenceNumber(v string) *GetShardIteratorInput {
	s.SequenceNumber = &v
	return s
}

def update_master_key(self, seq_number, key):

    self.send_update_master_key(seq_number, key)
    self.recv_update_master_key()

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


Question:
Sets Kernel instance.

@param KernelInterface $kernel

public function setKernel(KernelInterface $kernel) {
        $this->kernel = $kernel;
        $this->container = $kernel->getContainer();
    }

def create(self, **kwargs):
        """"""
        if 'monitor' in kwargs:
            value = self._format_monitor_parameter(kwargs['monitor'])
            kwargs['monitor'] = value
        return super(Pool, self)._create(**kwargs)

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


Question:
Loads a YAML file to be processed

@param string $file Path to YAML source file

public function load(string $file)
    {
        $this->data = Yaml::parse(file_get_contents($file));
        $this->filename = basename($file);
    }

func GetConf(filename string, configuration interface{}) (err error) {

	configValue := reflect.ValueOf(configuration)
	if typ := configValue.Type(); typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
		return fmt.Errorf("configuration should be a pointer to a struct type")
	}

	err = getFromYAML(filename, configuration)
	if err == nil {
		getFromEnvVariables(configuration)
	}

	return
}

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


Question:
Creates the positions.

@param statsPositionList
the stats position list
@param positionsData
the positions data
@param docSet
the doc set
@throws IOException
Signals that an I/O exception has occurred.

private static void createPositions(List<ComponentPosition> statsPositionList,
      Map<Integer, Integer> positionsData, List<Integer> docSet)
      throws IOException {
    if (statsPositionList != null) {
      for (ComponentPosition position : statsPositionList) {
        position.dataCollector.initNewList(1);
        Integer tmpValue;
        long[] values = new long[docSet.size()];
        int value;
        int number = 0;
        for (int docId : docSet) {
          tmpValue = positionsData.get(docId);
          value = tmpValue == null ? 0 : tmpValue.intValue();
          if (((position.minimumLong == null)
              || (value >= position.minimumLong))
              && ((position.maximumLong == null)
                  || (value <= position.maximumLong))) {
            values[number] = value;
            number++;
          }
        }
        if (number > 0) {
          position.dataCollector.add(values, number);
        }
        position.dataCollector.closeNewList();
      }
    }
  }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
Lookup and set offsets for any partitions which are awaiting an
        explicit reset.

        Arguments:
            partitions (set of TopicPartitions): the partitions to reset

def reset_offsets_if_needed(self, partitions):

        for tp in partitions:
            # TODO: If there are several offsets to reset, we could submit offset requests in parallel
            if self._subscriptions.is_assigned(tp) and self._subscriptions.is_offset_reset_needed(tp):
                self._reset_offset(tp)

def setup_system(self, system, name_from_system='', **kwargs):

        if not self.system:
            self.system = system
        name, traits = self._passed_arguments
        new_name = self.system.get_unique_name(self, name, name_from_system)
        if not self in self.system.reverse:
            self.name = new_name
        self.logger = self.system.logger.getChild('%s.%s' % (self.__class__.__name__, self.name))
        self.logger.setLevel(self.log_level)
        if name is None and 'name' in traits:  # Only __setstate__ sets name to None. Default is ''.
            del traits['name']

        for cname in self.callables:
            if cname in traits:
                c = self._postponed_callables[cname] = traits.pop(cname)
                c.setup_callable_system(self.system)
            getattr(self, cname).setup_callable_system(self.system)

        if not self.traits_inited():
            super().__init__(**traits)
        self.name_changed_event = True
        self.setup()

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


Question:
// Find returns the element where the comparison function matches
// the node's value and the given key value.

func (t *Tree) Find(key interface{}) interface{} {
	if key != nil && t.root != nil {
		d := &findData{key, t.compare}
		node := d.finder(t.root)
		if node != nil {
			return node.value
		}
	}

	return nil
}

function(sectionName){
      var section = basis.array.search(this.childNodes, 'sectionName', sectionName);
      if (section)
        section.select();
    }

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


Question: Adds a point to this canvas.

public void point(char legend, Color color, double... coord) {
        add(new Point(legend, color, coord));
    }

function now() {
      var pos = {line: line, column: column}

      pos.offset = self.toOffset(pos)

      return pos
    }

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


Question: Calculates offsets and sizes of all collection parts the complete collection is divided in.

private void calculateCollectionPartDescriptions() {
		collectionPartIds = new CollectionPartDescription[this.getNrofParts()];

		int displayOffset = 0;
		int count = 0;
		for (count = 0; count < getNrofParts() - 1; count++) {
			displayOffset = count * maxPartSize;
			if (displayOffset != offset) {
				collectionPartIds[count] = new CollectionPartDescription(displayOffset, maxPartSize, false);
			}
			else {
				collectionPartIds[count] = new CollectionPartDescription(displayOffset, maxPartSize, true);
				currentCollectionPartIdIndex = count;
			}
		}
		displayOffset = count * maxPartSize;
		if (displayOffset != offset) {
			collectionPartIds[count] = new CollectionPartDescription(displayOffset, getLastPartSize(), false);
		}
		else {
			collectionPartIds[count] = new CollectionPartDescription(displayOffset, getLastPartSize(), true);
			currentCollectionPartIdIndex = count;
		}
	}

public function getFileSize()
    {
        $oFile = oxNew(\OxidEsales\Eshop\Application\Model\File::class);
        $oFile->load($this->oxorderfiles__oxfileid->value);

        return $oFile->getSize();
    }

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


public function load($file) {
		$this->_origin = $file;
		if(!is_null($file)) {
			if(file_exists($file)) {
				if (is_null($this->_name)) {
					$bits = explode('/', $file);
					$this->_name = preg_replace('~\.tmpl~', '', array_pop($bits));
				}
				$this->_contents = file_get_contents($file);
				$this->_dir = dirname($file);
			}
			else {
				throw new \InvalidArgumentException("file does not exist (". $file .")");
			}
		}
		return $this;
	}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Internal update mechanism of FeaturedTutorialSkills on Video

@param Video $model
@param mixed $data

protected function doUpdateFeaturedTutorialSkills(Video $model, $data) {
		// remove all relationships before
		SkillQuery::create()->filterByFeaturedTutorial($model)->delete();

		// add them
		$errors = [];
		foreach ($data as $entry) {
			if (!isset($entry['id'])) {
				$errors[] = 'Missing id for Skill';
			} else {
				$related = SkillQuery::create()->findOneById($entry['id']);
				$model->addFeaturedTutorialSkill($related);
			}
		}

		if (count($errors) > 0) {
			throw new ErrorsException($errors);
		}
	}

func (s *Channel) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Channel"}
	if s.ChannelName == nil {
		invalidParams.Add(request.NewErrParamRequired("ChannelName"))
	}
	if s.ChannelName != nil && len(*s.ChannelName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ChannelName", 1))
	}
	if s.DataSource == nil {
		invalidParams.Add(request.NewErrParamRequired("DataSource"))
	}
	if s.DataSource != nil {
		if err := s.DataSource.Validate(); err != nil {
			invalidParams.AddNested("DataSource", err.(request.ErrInvalidParams))
		}
	}
	if s.ShuffleConfig != nil {
		if err := s.ShuffleConfig.Validate(); err != nil {
			invalidParams.AddNested("ShuffleConfig", err.(request.ErrInvalidParams))
		}
	}

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

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


Question:
Save this scan template configuration to a Nexpose console.

 @param [Connection] nsc API connection to a Nexpose console.

def save(nsc)
      root = REXML::XPath.first(@xml, 'ScanTemplate')
      if root.attributes['id'] == '#NewScanTemplate#'
        response = JSON.parse(AJAX.post(nsc, '/data/scan/templates', xml))
        root.attributes['id'] = response['value']
      else
        response = JSON.parse(AJAX.put(nsc, "/data/scan/templates/#{URI.encode(id)}", xml))
      end
      response['value']
    end

protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
	{
		mps_network_config_responses result = (mps_network_config_responses) service.get_payload_formatter().string_to_resource(mps_network_config_responses.class, response);
		if(result.errorcode != 0)
		{
			if (result.errorcode == SESSION_NOT_EXISTS)
				service.clear_session();
			throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_network_config_response_array);
		}
		mps_network_config[] result_mps_network_config = new mps_network_config[result.mps_network_config_response_array.length];

		for(int i = 0; i < result.mps_network_config_response_array.length; i++)
		{
			result_mps_network_config[i] = result.mps_network_config_response_array[i].mps_network_config[0];
		}

		return result_mps_network_config;
	}

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


Question:
Returns the number of elements that the instruction *op* adds to the stack.

  # Arguments
  op (dis.Instruction): The instruction to retrieve the stackdelta value for.

  # Raises
  KeyError: If the instruction *op* is not supported.

def get_stackdelta(op):

  res = opstackd[op.opname]
  if callable(res):
    res = res(op)
  return res

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question:
Sanitize a regular expression check for javascript.

@param string $strCheck
@return mixed|string

protected function __sanitizeCheckForJs($strCheck)
    {
        $strCheck = (empty($strCheck)) ? "''" : str_replace("'", "\\'", $strCheck);
        $strCheck = (mb_substr($strCheck, -1) == "u") ? mb_substr($strCheck, 0, -1) : $strCheck;

        return $strCheck;
    }

function (char) {
                var
                    newState,
                    tagsOpened = 0 < this._openedTags.length;
                if ("#" === char) {
                    this._hLevel = 1;
                    newState = this._parseTitle;
                } else if ("*" === char || "0" <= char && "9" >= char ) {
                    if (char !== "*") {
                        this._numericList = 1;
                    } else {
                        this._numericList = 0;
                    }
                    newState = this._parseList;
                    tagsOpened = false; // Wait for disambiguation
                } else if (" " !== char && "\t" !== char && "\n" !== char) {
                    if (tagsOpened) {
                        this._output(" ");
                        tagsOpened = false; // Avoid closing below
                    } else {
                        this._openTag("p");
                    }
                    newState = this._parseContent(char);
                    if (!newState) {
                        newState = this._parseContent;
                    }
                }
                if (tagsOpened) {
                    this._closeTags();
                }
                return newState;
            }

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


Question:
// GetAWSEC2VPNGatewayWithName retrieves all AWSEC2VPNGateway items from an AWS CloudFormation template
// whose logical ID matches the provided name. Returns an error if not found.

func (t *Template) GetAWSEC2VPNGatewayWithName(name string) (*resources.AWSEC2VPNGateway, error) {
	if untyped, ok := t.Resources[name]; ok {
		switch resource := untyped.(type) {
		case *resources.AWSEC2VPNGateway:
			return resource, nil
		}
	}
	return nil, fmt.Errorf("resource %q of type AWSEC2VPNGateway not found", name)
}

def _create_network_interface(
        self, ip_config_name, nic_name, public_ip, region,
        resource_group_name, subnet, accelerated_networking=False
    ):

        nic_config = {
            'location': region,
            'ip_configurations': [{
                'name': ip_config_name,
                'private_ip_allocation_method': 'Dynamic',
                'subnet': {
                    'id': subnet.id
                },
                'public_ip_address': {
                    'id': public_ip.id
                },
            }]
        }

        if accelerated_networking:
            nic_config['enable_accelerated_networking'] = True

        try:
            nic_setup = self.network.network_interfaces.create_or_update(
                resource_group_name, nic_name, nic_config
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to create network interface: {0}.'.format(
                    error
                )
            )

        return nic_setup.result()

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