Question: is bad, just return false.

private boolean isValidShardDate(String shardDate) {
        try {
            // If the format is invalid, a ParseException is thrown.
            Utils.dateFromString(shardDate);
            return true;
        } catch (IllegalArgumentException ex) {
            return false;
        }
    }

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

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


public void configureWebApp() throws Exception
    {
        //cannot configure if the context is already started
        if (_context.isStarted())
        {
            if (log.isDebugEnabled()){log.debug("Cannot configure webapp after it is started");};
            return;
        }

        Resource webInf=getWebApplicationContext().getWebInf();
        // handle any WEB-INF descriptors
        if(webInf!=null&&webInf.isDirectory())
        {
            // do web.xml file
            Resource web=webInf.addPath("web.xml");
            if(!web.exists())
            {
                log.info("No WEB-INF/web.xml in "+getWebApplicationContext().getWAR()
                        +". Serving files and default/dynamic servlets only");
            }
            else
            {
                XmlParser.Node config=null;
                config=xmlParser.parse(web.getURL());
                initialize(config);
            }
        }
    }

def main(args=None):
    """"""

    if args is None:
        parser = get_argument_parser()
        args = parser.parse_args()

    input_file = args.annotation_file
    output_file = args.output_file
    species = args.species
    chrom_pat = args.chromosome_pattern
    field_name = args.field_name

    log_file = args.log_file
    quiet = args.quiet
    verbose = args.verbose

    # configure root logger
    log_stream = sys.stdout
    if output_file == '-':
        # if we print output to stdout, redirect log messages to stderr
        log_stream = sys.stderr

    logger = misc.get_logger(log_stream = log_stream, log_file = log_file,
            quiet = quiet, verbose = verbose)

    if chrom_pat is None:
        chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species])
    else:
        chrom_pat = re.compile(chrom_pat)

    logger.info('Regular expression used for filtering chromosome names: "%s"',
            chrom_pat.pattern)

    chromosomes = set()
    excluded_chromosomes = set()
    i = 0
    exons = 0
    logger.info('Parsing data...')
    if input_file == '-':
        input_file = None
    with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
            misc.smart_open_write(output_file) as ofh:
        #if i >= 500000: break
        reader = csv.reader(fh, dialect = 'excel-tab')
        writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
                quoting = csv.QUOTE_NONE , quotechar = '|')
        for l in reader:
            i += 1
            #if i % int(1e5) == 0:
            #   print '\r%d...' %(i), ; sys.stdout.flush() # report progress
            if len(l) > 1 and l[2] == field_name:
                attr = parse_attributes(l[8])
                type_ = attr['gene_biotype']
                if type_ in ['protein_coding','polymorphic_pseudogene']:

                    # test whether chromosome is valid
                    chrom = l[0]
                    m = chrom_pat.match(chrom)
                    if m is None:
                        excluded_chromosomes.add(chrom)
                        continue

                    chromosomes.add(chrom)
                    writer.writerow(l)
                    exons += 1

    logger.info('Done! (Parsed %d lines.)', i)

    logger.info('')
    logger.info('Gene chromosomes (%d):', len(chromosomes))
    logger.info('\t' + ', '.join(sorted(chromosomes)))
    logger.info('')
    logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
    logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
    logger.info('')
    logger.info('Total no. of exons: %d' %(exons))

    return 0

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


Question:
// Mount mounts a FileSystem with the given Config.
// Mount returns when the filesystem has been mounted or there is an error.

func Mount(cfg *Config) (*MountHandle, error) {
	err := loadDokanDLL(cfg)
	if err != nil {
		return nil, err
	}
	var ec = make(chan error, 2)
	var slot = fsTableStore(cfg.FileSystem, ec)
	flags := cfg.MountFlags
	go func() {
		ctx := allocCtx(slot)
		defer ctx.Free()
		ec <- ctx.Run(cfg.Path, flags)
		close(ec)
	}()
	// This gets a send from either
	// 1) DokanMain from ctx.Run returns an error before mount
	// 2) After the filesystem is mounted from handling the Mounted callback.
	// Thus either the filesystem was mounted ok or it was not mounted
	// and an err is not nil. DokanMain does not return errors after the
	// mount, but if such errors occured they can be catched by BlockTillDone.
	err = <-ec
	if err != nil {
		return nil, err
	}
	return &MountHandle{ec, cfg.Path}, nil
}

def _ParseShellItemPathSegment(self, shell_item):

    path_segment = None

    if isinstance(shell_item, pyfwsi.root_folder):
      description = shell_folder_ids.DESCRIPTIONS.get(
          shell_item.shell_folder_identifier, None)

      if description:
        path_segment = description
      else:
        path_segment = '{{{0:s}}}'.format(shell_item.shell_folder_identifier)

      path_segment = '<{0:s}>'.format(path_segment)

    elif isinstance(shell_item, pyfwsi.volume):
      if shell_item.name:
        path_segment = shell_item.name
      elif shell_item.identifier:
        path_segment = '{{{0:s}}}'.format(shell_item.identifier)

    elif isinstance(shell_item, pyfwsi.file_entry):
      long_name = ''
      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name

      if long_name:
        path_segment = long_name
      elif shell_item.name:
        path_segment = shell_item.name

    elif isinstance(shell_item, pyfwsi.network_location):
      if shell_item.location:
        path_segment = shell_item.location

    if path_segment is None and shell_item.class_type == 0x00:
      # TODO: check for signature 0x23febbee
      pass

    if path_segment is None:
      path_segment = '<UNKNOWN: 0x{0:02x}>'.format(shell_item.class_type)

    return path_segment

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


Question:
Notify all listeners and children that implements BeanContextServices of the event.

@see com.googlecode.openbeans.beancontext.BeanContextServicesListener#serviceAvailable(com.googlecode.openbeans.beancontext.BeanContextServiceAvailableEvent)

public void serviceAvailable(BeanContextServiceAvailableEvent event)
	{
		if (null == event)
		{
			throw new NullPointerException(Messages.getString("beans.1C")); //$NON-NLS-1$
		}
		if (services.containsKey(event.serviceClass))
		{
			return;
		}
		fireServiceAdded(event);
		Object childs[] = copyChildren();
		for (int i = 0; i < childs.length; i++)
		{
			if (childs[i] instanceof BeanContextServices)
			{
				((BeanContextServices) childs[i]).serviceAvailable(event);
			}
		}
	}

private static MBeanInfo createMBeanInfo(AttributeNodeForPojo rootNode, Class<?> monitorableClass) {
		String monitorableName = "";
		String monitorableDescription = "";
		MBeanAttributeInfo[] attributes = rootNode != null ?
				fetchAttributesInfo(rootNode) :
				new MBeanAttributeInfo[0];
		MBeanOperationInfo[] operations = fetchOperationsInfo(monitorableClass);
		return new MBeanInfo(
				monitorableName,
				monitorableDescription,
				attributes,
				null,  // constructors
				operations,
				null); //notifications
	}

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


Question: check number range

def setNumberRange(key, keyType, start, end):
    ''''''
    return And(
        And(keyType, error=SCHEMA_TYPE_ERROR % (key, keyType.__name__)),
        And(lambda n: start <= n <= end, error=SCHEMA_RANGE_ERROR % (key, '(%s,%s)' % (start, end))),
    )

def frange(start, end, step):

    val = start
    while val < end:
        yield val
        val += step

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


Question: // txnDispatch runs the given operations inside the state store transaction.

func (s *Store) txnDispatch(tx *memdb.Txn, idx uint64, ops structs.TxnOps) (structs.TxnResults, structs.TxnErrors) {
	results := make(structs.TxnResults, 0, len(ops))
	errors := make(structs.TxnErrors, 0, len(ops))
	for i, op := range ops {
		var ret structs.TxnResults
		var err error

		// Dispatch based on the type of operation.
		switch {
		case op.KV != nil:
			ret, err = s.txnKVS(tx, idx, op.KV)
		case op.Intention != nil:
			err = s.txnIntention(tx, idx, op.Intention)
		case op.Node != nil:
			ret, err = s.txnNode(tx, idx, op.Node)
		case op.Service != nil:
			ret, err = s.txnService(tx, idx, op.Service)
		case op.Check != nil:
			ret, err = s.txnCheck(tx, idx, op.Check)
		default:
			err = fmt.Errorf("no operation specified")
		}

		// Accumulate the results.
		results = append(results, ret...)

		// Capture any error along with the index of the operation that
		// failed.
		if err != nil {
			errors = append(errors, &structs.TxnError{
				OpIndex: i,
				What:    err.Error(),
			})
		}
	}

	if len(errors) > 0 {
		return nil, errors
	}

	return results, nil
}

func LoadToDepth(ctx context.Context, qs graph.QuadStore, dst interface{}, depth int, ids ...quad.Value) error {
	return global.LoadToDepth(ctx, qs, dst, depth, ids...)
}

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


Question:
Build query params
@return array

private function _buildQueryParams() {
		$query = [];

		$this->_where = is_array($this->_where) ? $this->_where : [];
		foreach ($this->_where as $key => $val) {
			$query[$key] = is_numeric($val) ? (int) $val : $val;
		}

		if(count($this->_select)) {
			$query[$this->selectFieldsKey] = implode(',', $this->_select);
		}
		if($this->_limit !== null) {
			$query[$this->limitKey] = $this->_limit;
		}
		if($this->_offset !== null) {
			$query[$this->offsetKey] = $this->_offset;
		}

		return $query;
	}

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

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


Question:
Class: mxValueChange

Action to change a user object in a model.

Constructor: mxValueChange

Constructs a change of a user object in the
specified model.

function mxValueChange(model, cell, value)
{
	this.model = model;
	this.cell = cell;
	this.value = value;
	this.previous = value;
}

func (r View) Dispatch(ctx context.Context) { // r as Response view.
	if r.Err != nil {
		if r.Code < 400 {
			r.Code = DefaultErrStatusCode
		}
		ctx.StatusCode(r.Code)
		ctx.WriteString(r.Err.Error())
		ctx.StopExecution()
		return
	}

	if r.Code > 0 {
		ctx.StatusCode(r.Code)
	}

	if r.Name != "" {
		r.Name = ensureExt(r.Name)

		if r.Layout != "" {
			r.Layout = ensureExt(r.Layout)
			ctx.ViewLayout(r.Layout)
		}

		if r.Data != nil {
			// In order to respect any c.Ctx.ViewData that may called manually before;
			dataKey := ctx.Application().ConfigurationReadOnly().GetViewDataContextKey()
			if ctx.Values().Get(dataKey) == nil {
				// if no c.Ctx.ViewData set-ed before (the most common scenario) then do a
				// simple set, it's faster.
				ctx.Values().Set(dataKey, r.Data)
			} else {
				// else check if r.Data is map or struct, if struct convert it to map,
				// do a range loop and modify the data one by one.
				// context.Map is actually a map[string]interface{} but we have to make that check:
				if m, ok := r.Data.(map[string]interface{}); ok {
					setViewData(ctx, m)
				} else if m, ok := r.Data.(context.Map); ok {
					setViewData(ctx, m)
				} else if di.IndirectValue(reflect.ValueOf(r.Data)).Kind() == reflect.Struct {
					setViewData(ctx, structs.Map(r))
				}
			}
		}

		ctx.View(r.Name)
	}
}

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


Question:
// NewChatAction sets a chat action.
// Actions last for 5 seconds, or until your next action.
//
// chatID is where to send it, action should be set via Chat constants.

func NewChatAction(chatID int64, action string) ChatActionConfig {
	return ChatActionConfig{
		BaseChat: BaseChat{ChatID: chatID},
		Action:   action,
	}
}

def get_context(self, context):
        """"""
        # forward pass
        i = 0
        while i < len(self.tagList):
            tag = self.tagList[i]

            # skip application stuff
            if tag.tagClass == Tag.applicationTagClass:
                pass

            # check for context encoded atomic value
            elif tag.tagClass == Tag.contextTagClass:
                if tag.tagNumber == context:
                    return tag

            # check for context encoded group
            elif tag.tagClass == Tag.openingTagClass:
                keeper = tag.tagNumber == context
                rslt = []
                i += 1
                lvl = 0
                while i < len(self.tagList):
                    tag = self.tagList[i]
                    if tag.tagClass == Tag.openingTagClass:
                        lvl += 1
                    elif tag.tagClass == Tag.closingTagClass:
                        lvl -= 1
                        if lvl < 0: break

                    rslt.append(tag)
                    i += 1

                # make sure everything balances
                if lvl >= 0:
                    raise InvalidTag("mismatched open/close tags")

                # get everything we need?
                if keeper:
                    return TagList(rslt)
            else:
                raise InvalidTag("unexpected tag")

            # try the next tag
            i += 1

        # nothing found
        return None

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


Question: // Normalize normalizes and checks for input violations.

func (p *Parameters) Normalize() (err error) {
	if err = p.Scheduling.Normalize(); err != nil {
		return
	}
	if err = p.Meta.Normalize(); err != nil {
		return
	}
	if err = p.Job.Normalize(); err != nil {
		return
	}
	return
}

def clean_description(self):

        description = self.cleaned_data.get("description")
        validation_helper = safe_import_module(settings.FORUM_TEXT_VALIDATOR_HELPER_PATH)
        if validation_helper is not None:
            return validation_helper(self, description)
        else:
            return description

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


Question:
Convenience method for getting a specific task directly.

@param pTaskName the task to get
@param pDepConfig the dependency configuration for which the task is intended
@return a task object

@Nonnull
    public Task getTask(@Nonnull final TaskNames pTaskName, @Nonnull final DependencyConfig pDepConfig)
    {
        return project.getTasks().getByName(pTaskName.getName(pDepConfig));
    }

private synchronized Collection<IResult> valuesToParameters(Process process, ValueMap<Output, OWLValue> values) throws NotYetImplementedException, OWLTranslationException
    {
        if (values.isEmpty())
        {
            return null;
        }
        Collection<IResult> parameters = new ArrayList<IResult>();
        Iterator<Entry<Output, OWLValue>> valuesIterator = values.iterator();
        while (valuesIterator.hasNext())
        {
            Entry<Output, OWLValue> valuesEntry = valuesIterator.next();
            final OWLSParameter parameter
                    = new OWLSParameter(
                            process.getOntology(),
                            valuesEntry.getKey().getName(),
                            valuesEntry.getValue());
            parameters.add(new IOutputValue()
            {
                @Override
                public IOutput getOutput()
                {
                    try
                    {
                        return output(parameter.name());
                    } catch (ModelException ex)
                    {
                        return null;
                    }
                }

                @Override
                public Object object() throws ModelException
                {
                    return parameter.object();
                }

                @Override
                public ISemanticIdentifier getSemanticAnnotation()
                {
                    return parameter.getSemanticAnnotation();
                }

                @Override
                public ISubject value() throws ModelException
                {
                    if (null != functionalityGrounding)
                    {
                        return functionalityGrounding.createOutput(parameter.object(), OWLSAtomicService.this).value();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        return parameters;
    }

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


Question:
@param \PhpParser\Node\Stmt\Function_ $node
@param \PHPStan\Analyser\Scope $scope

@return string[] errors

public function processNode(Node $node, Scope $scope): array
	{
		$functionReflection = $this->broker->getCustomFunction(new Node\Name($node->name->name), $scope);
		$returnType = ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getReturnType();

		if ($returnType instanceof MixedType && !$returnType->isExplicitMixed()) {
			return [
				sprintf(
					'Function %s() has no return typehint specified.',
					$functionReflection->getName()
				),
			];
		}

		return [];
	}

public function InstanceOfExpression()
    {
        $instanceOfExpression = new AST\InstanceOfExpression($this->IdentificationVariable());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $instanceOfExpression->not = true;
        }

        $this->match(Lexer::T_INSTANCE);
        $this->match(Lexer::T_OF);

        $exprValues = array();

        if ($this->lexer->isNextToken(Lexer::T_OPEN_PARENTHESIS)) {
            $this->match(Lexer::T_OPEN_PARENTHESIS);

            $exprValues[] = $this->InstanceOfParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);

                $exprValues[] = $this->InstanceOfParameter();
            }

            $this->match(Lexer::T_CLOSE_PARENTHESIS);

            $instanceOfExpression->value = $exprValues;

            return $instanceOfExpression;
        }

        $exprValues[] = $this->InstanceOfParameter();

        $instanceOfExpression->value = $exprValues;

        return $instanceOfExpression;
    }

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


Question: // Fatal logs to the default Logger. See Logger.Fatal

func Fatal(v ...interface{}) {
	DefaultLogger.Emit(1, fmt.Sprint(v...), nil)
	os.Exit(1)
}

def parseBasicOptions(parser):

    (options, args) = parser.parse_args()

    setLoggingFromOptions(options)

    #Set up the temp dir root
    if options.tempDirRoot == "None":
        options.tempDirRoot = os.getcwd()

    return options, args

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


Question:
Order the root file items of the outline explorer as in the tabbar
        of the current EditorStack.

def _sync_outlineexplorer_file_order(self):

        if self.outlineexplorer is not None:
            self.outlineexplorer.treewidget.set_editor_ids_order(
                [finfo.editor.get_document_id() for finfo in self.data])

def SetPackageView(self, directoryView):
        """"""
        self.directoryView = not self.directoryView
        self.packageMenuItem.Check(self.directoryView)
        self.packageViewTool.SetValue(self.directoryView)
        if self.loader:
            self.SetModel(self.loader)
        self.RecordHistory()

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


Question: // Delete implements Service.Delete but does nothing.

func (e *EmptyService) Delete(ctx context.Context, options options.Delete) error {
	return nil
}

public static <K, V> MapDataStore<K, V> emptyStore() {
        return (MapDataStore<K, V>) EMPTY_MAP_DATA_STORE;
    }

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


Question:
Start the Messaging Engine if it is enabled

@throws Exception

public void startConditional() throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "startConditional", this);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Activating MBean for ME " + getName());
        setState(STATE_STARTING);
        start(JsConstants.ME_START_DEFAULT);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "startConditional");
    }

private static boolean isCreatingPlatformMBeanServer(int threshold) {
        int count = 0;
        for (final StackTraceElement ste : Thread.currentThread().getStackTrace()) {
            if ("java.lang.management.ManagementFactory".equals(ste.getClassName())
                && "getPlatformMBeanServer".equals(ste.getMethodName())) {
                count++;
                if (count >= threshold) {
                    return true;
                }
            }
        }
        return false;
    }

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


Question:
{@inheritDoc}
@see \ImageStack\StorageBackend\FileStorageBackend::storeImage()

public function storeImage(ImageInterface $image, ImagePathInterface $path) {
		$this->optimizerImageManipulator->manipulateImage($image, $path);
		$this->writeImageFile($image, $path);
	}

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

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

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

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

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


Question:
// GetStaleProbes returns a map of stale probes which key is a probe name and
// value is a time when the last instance of the probe has been started.
//
// A probe is declared stale if it hasn't returned in FailureThreshold.

func (c *Collector) GetStaleProbes() map[string]time.Time {
	c.RLock()
	defer c.RUnlock()

	probes := make(map[string]time.Time)

	for p := range c.staleProbes {
		probes[p] = c.probeStartTime[p]
	}

	return probes
}

def handle_single_message(self, msg):

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

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


Question: get monitor acquired on current stackframe, null when it was acquired earlier or not monitor is held

private Monitor getMonitorJustAcquired(List<ThreadLock.Monitor> monitors) {
        if (monitors.isEmpty()) return null;
        Monitor monitor = monitors.get(0);
        if (monitor.getDepth() != 0) return null;

        for (Monitor duplicateCandidate: monitors) {
            if (monitor.equals(duplicateCandidate)) continue; // skip first - equality includes monitor depth

            if (monitor.getLock().equals(duplicateCandidate.getLock())) return null; // Acquired earlier
        }

        return monitor;
    }

def get_context(self, context):
        """"""
        # forward pass
        i = 0
        while i < len(self.tagList):
            tag = self.tagList[i]

            # skip application stuff
            if tag.tagClass == Tag.applicationTagClass:
                pass

            # check for context encoded atomic value
            elif tag.tagClass == Tag.contextTagClass:
                if tag.tagNumber == context:
                    return tag

            # check for context encoded group
            elif tag.tagClass == Tag.openingTagClass:
                keeper = tag.tagNumber == context
                rslt = []
                i += 1
                lvl = 0
                while i < len(self.tagList):
                    tag = self.tagList[i]
                    if tag.tagClass == Tag.openingTagClass:
                        lvl += 1
                    elif tag.tagClass == Tag.closingTagClass:
                        lvl -= 1
                        if lvl < 0: break

                    rslt.append(tag)
                    i += 1

                # make sure everything balances
                if lvl >= 0:
                    raise InvalidTag("mismatched open/close tags")

                # get everything we need?
                if keeper:
                    return TagList(rslt)
            else:
                raise InvalidTag("unexpected tag")

            # try the next tag
            i += 1

        # nothing found
        return None

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


Question:
Set commands for modules.

@param Command $service

private function setShopAwareCommands(Command $service)
    {
        if ($service instanceof AbstractShopAwareCommand && $service->isActive()) {
            $this->commands[] = $service;
        }
    }

public void setInstallModules(String value) {

        m_installModules = CmsStringUtil.splitAsList(value, "|", true);
        try {
            m_installModules = CmsModuleManager.topologicalSort(m_installModules, getModuleFolder());
        } catch (CmsConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

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


Question:
/*
ApplyCachedImpulse applies the cached impulse to the connected bodies.
*/

func (joint *SimpleMotor) ApplyCachedImpulse(dt_coef vect.Float) {
	a := joint.BodyA
	b := joint.BodyB

	j := joint.jAcc*dt_coef
	a.w -= j*a.i_inv
	b.w += j*b.i_inv
}

def _flush(self):

        # Upload segment with workers
        name = self._segment_name % self._seek
        response = self._workers.submit(
            self._client.put_object, self._container, name,
            self._get_buffer())

        # Save segment information in manifest
        self._write_futures.append(dict(
            etag=response, path='/'.join((self._container, name))))

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


Question:
Set the value of [content_id] column.

@param      int $v new value
@return   \Dealer\Model\DealerContent The current object (for fluent API support)

public function setContentId($v)
    {
        if ($v !== null) {
            $v = (int) $v;
        }

        if ($this->content_id !== $v) {
            $this->content_id = $v;
            $this->modifiedColumns[DealerContentTableMap::CONTENT_ID] = true;
        }

        if ($this->aContent !== null && $this->aContent->getId() !== $v) {
            $this->aContent = null;
        }

        return $this;
    }

public function change()
    {
        $tableName = 'language_translations';
        if (!$this->hasTable($tableName)) {
            $tableName = 'translations';
        }

        $table = $this->table($tableName);
        if ($table->hasColumn('created')) {
            $table->changeColumn('created', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        if ($table->hasColumn('modified')) {
            $table->changeColumn('modified', 'datetime', [
                'default' => null,
                'null' => true
            ]);
        }
        $table->save();
    }

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


Question:
Edit the Command.

@param string $name Name of the command
@param string $description Command description
@param string $code Unique code for this command
@return XiboCommand

public function edit($name, $description, $code)
	{
		$this->command = $name;
		$this->description = $description;
		$this->code = $code;
		$this->getLogger()->info('Editing display command ID ' . $this->commandId);
		$response = $this->doPut('/command/' . $this->commandId, $this->toArray());

		return $this->hydrate($response);
	}

function executeCommand(parameters) {
    if (parameters.environment === undefined) { parameters.environment = plugin.myrmex.getConfig('environment'); }

    return plugin.loadTemplates()
    .then(templates => {
      // If the parameter "all" is set, we deploy all templates
      if (!parameters.all) {
        templates = _.filter(templates, template => { return parameters.templateIdentifiers.indexOf(template.getIdentifier()) !== -1; });
      }

      icli.print();
      icli.print('Deploying ' + icli.format.info(templates.length) + ' template(s):');
      icli.print('  AWS region: ' + icli.format.info(parameters.region));
      icli.print('  Environement: ' + icli.format.info(parameters.environment || 'no environment specified'));
      icli.print();
      icli.print('This operation may last a little');

      return Promise.map(templates, template => {
        const context = {
          environment: parameters.environment
        };
        return template.deploy(parameters.region, context);
      });
    })
    .then(reports => {
      console.log(reports);
    })
    .catch(e => {
      if (e.code === 'AccessDeniedException' && e.cause && e.cause.message) {
        icli.print('\n    ' + icli.format.error('Insufficient permissions to perform the action\n'));
        icli.print('The IAM user/role you are using to perform this action does not have sufficient permissions.\n');
        icli.print(e.cause.message + '\n');
        icli.print('Please update the policies of the user/role before trying again.\n');
        process.exit(1);
      }
      throw e;
    });
  }

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


Question: // ParseForm parse http form

func ParseForm(req *http.Request) (err error) {
	if IsMultipart(req) {
		if err = req.ParseMultipartForm(111); err != nil {
			return err
		}
	} else {
		if err = req.ParseForm(); err != nil {
			return err
		}
	}
	return nil
}

public function addStopWords($stopWords)
    {
        $this->initializeStopWordsUrl();
        $json = $this->stopWordParser->toJson($stopWords);
        return $this->_sendRawPost($this->_stopWordsUrl, $json, 'application/json');
    }

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


Question:
Display page to get some details on a appbox

@param  Request $request    The current HTTP request
@param  integer $databox_id The requested databox
@return Response

public function getDetails(Request $request, $databox_id)
    {
        $databox = $this->findDataboxById($databox_id);

        $details = [];
        $total = ['total_subdefs' => 0, 'total_size' => 0];

        foreach ($databox->get_record_details($request->query->get('sort')) as $collName => $colDetails) {
            $details[$collName] = [
                'total_subdefs' => 0,
                'total_size' => 0,
                'medias' => []
            ];

            foreach ($colDetails as $subdefName => $subdefDetails) {
                $details[$collName]['total_subdefs'] += $subdefDetails['n'];
                $total['total_subdefs'] += $subdefDetails['n'];
                $details[$collName]['total_size'] += $subdefDetails['siz'];
                $total['total_size'] += $subdefDetails['siz'];

                $details[$collName]['medias'][] = [
                    'subdef_name' => $subdefName,
                    'total_subdefs' => $subdefDetails['n'],
                    'total_size' => $subdefDetails['siz'],
                ];
            }
        }

        return $this->render('admin/databox/details.html.twig', [
            'databox' => $databox,
            'table'   => $details,
            'total'   => $total
        ]);
    }

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
Get by Primary Key

@param $pk
@return null

public function findByPK($pk)
    {
        $this->createQuery();
        $q = $this->getQuery();

        $q .= ' WHERE ' . $this->table() . '.' . $this->getPK()->identifier() . ' = ?';
        $this->setQuery($q);
        $this->setParams($pk);

        GapOrm::getDriver()->query($this->getQuery(), [$pk]);
        $obj = GapOrm::getDriver()->selectOnce();

        if (is_null($obj)) {
            return null;
        }

        $obj = $this->convertFromDB($obj);

        if ($obj) {
            return $obj;
        }

        return null;
    }

public static function findParamValue(&$value, &$operator): bool
    {
        if (is_array($value) || is_object($value)) {
            $value = static::assembleParamValue($value, $operator);
        } else {
            self::normalizeEmptyValue($value);

            $operator = self::parseParamOperator($value);

            if (is_numeric($value)) {
                $value = self::prependOperator($value, $operator);
            } else {
                $value = StringHelper::toLowerCase($value);

                if ($value !== ':empty:' || $value !== 'not :empty:') {
                    // Trim any whitespace from the value
                    $value = StringHelper::trim($value);

                    return false;
                }
            }
        }

        return true;
    }

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


Question:
Fetches all the resources of the specified type in the subscription.

@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<VaultInner> object

public Observable<Page<VaultInner>> listAsync() {
        return listWithServiceResponseAsync()
            .map(new Func1<ServiceResponse<Page<VaultInner>>, Page<VaultInner>>() {
                @Override
                public Page<VaultInner> call(ServiceResponse<Page<VaultInner>> response) {
                    return response.body();
                }
            });
    }

func (m *MockArticle) Read(arg0 bool, arg1 content.User, arg2 ...content.QueryOpt) error {
	varargs := []interface{}{arg0, arg1}
	for _, a := range arg2 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "Read", varargs...)
	ret0, _ := ret[0].(error)
	return ret0
}

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


Question:
预载入关联查询（JOIN方式）
@access public
@param  Query    $query       查询对象
@param  string   $relation    关联名
@param  mixed    $field       关联字段
@param  string   $joinType    JOIN方式
@param  \Closure $closure     闭包条件
@param  bool     $first
@return void

public function eagerly(Query $query, $relation, $field, $joinType, $closure, $first)
    {
        $name = Db::parseName(basename(str_replace('\\', '/', get_class($this->parent))));

        if ($first) {
            $table = $query->getTable();
            $query->table([$table => $name]);

            if ($query->getOptions('field')) {
                $masterField = $query->getOptions('field');
                $query->removeOption('field');
            } else {
                $masterField = true;
            }

            $query->field($masterField, false, $table, $name);
        }

        // 预载入封装
        $joinTable = $this->query->getTable();
        $joinAlias = $relation;
        $joinType  = $joinType ?: $this->joinType;

        $query->via($joinAlias);

        if ($this instanceof BelongsTo) {
            $joinOn = $name . '.' . $this->foreignKey . '=' . $joinAlias . '.' . $this->localKey;
        } else {
            $joinOn = $name . '.' . $this->localKey . '=' . $joinAlias . '.' . $this->foreignKey;
        }

        if ($closure) {
            // 执行闭包查询
            $closure($query);
            // 使用withField指定获取关联的字段，如
            // $query->where(['id'=>1])->withField('id,name');
            if ($query->getOptions('with_field')) {
                $field = $query->getOptions('with_field');
                $query->removeOption('with_field');
            }
        }

        $query->join([$joinTable => $joinAlias], $joinOn, $joinType)
            ->field($field, false, $joinTable, $joinAlias, $relation . '__');
    }

private Collection getInValuesCollection(Expression inClauseValues)
    {
        Collection inParameterCollection = new ArrayList<>();
        if (inClauseValues instanceof NullExpression)
        {
            log.debug("No items passed in IN clause values, returning blank IN values list");
            return inParameterCollection;
        }

        if (inClauseValues instanceof InputParameter)
        {
            Object inValues = kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());
            log.debug(inClauseValues.toParsedText() + "named parameter found in query, Replacing parameter with "
                    + inValues);

            inParameterCollection = inValues.getClass().isArray() ? Arrays.asList((Object[]) inValues)
                    : (Collection) kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());

            return inParameterCollection;
        }

        if (inClauseValues instanceof CollectionExpression)
        {
            Iterator inValueIterator = ((CollectionExpression) inClauseValues).children().iterator();

            log.debug("Collection object found for IN clause values");
            while (inValueIterator.hasNext())
            {
                Expression value = (Expression) inValueIterator.next();
                inParameterCollection.add(value.toParsedText());
            }
            return inParameterCollection;
        }

        throw new KunderaException(inClauseValues.toParsedText() + " not supported for IN clause");
    }

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


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

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

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_port_type = ET.SubElement(fcoe_intf_list, "fcoe-intf-port-type")
        fcoe_intf_port_type.text = kwargs.pop('fcoe_intf_port_type')

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

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


Question:
Parses the given pattern and returns the antlr parse tree.

        :param pattern_str: The STIX pattern
        :return: The parse tree
        :raises ParseException: If there is a parse error

def __do_parse(self, pattern_str):

        in_ = antlr4.InputStream(pattern_str)
        lexer = STIXPatternLexer(in_)
        lexer.removeErrorListeners()  # remove the default "console" listener
        token_stream = antlr4.CommonTokenStream(lexer)

        parser = STIXPatternParser(token_stream)
        parser.removeErrorListeners()  # remove the default "console" listener
        error_listener = ParserErrorListener()
        parser.addErrorListener(error_listener)

        # I found no public API for this...
        # The default error handler tries to keep parsing, and I don't
        # think that's appropriate here.  (These error handlers are only for
        # handling the built-in RecognitionException errors.)
        parser._errHandler = antlr4.BailErrorStrategy()

        # To improve error messages, replace "<INVALID>" in the literal
        # names with symbolic names.  This is a hack, but seemed like
        # the simplest workaround.
        for i, lit_name in enumerate(parser.literalNames):
            if lit_name == u"<INVALID>":
                parser.literalNames[i] = parser.symbolicNames[i]

        # parser.setTrace(True)

        try:
            tree = parser.pattern()
            # print(tree.toStringTree(recog=parser))

            return tree
        except antlr4.error.Errors.ParseCancellationException as e:
            # The cancellation exception wraps the real RecognitionException
            # which caused the parser to bail.
            real_exc = e.args[0]

            # I want to bail when the first error is hit.  But I also want
            # a decent error message.  When an error is encountered in
            # Parser.match(), the BailErrorStrategy produces the
            # ParseCancellationException.  It is not a subclass of
            # RecognitionException, so none of the 'except' clauses which would
            # normally report an error are invoked.
            #
            # Error message creation is buried in the ErrorStrategy, and I can
            # (ab)use the API to get a message: register an error listener with
            # the parser, force an error report, then get the message out of the
            # listener.  Error listener registration is above; now we force its
            # invocation.  Wish this could be cleaner...
            parser._errHandler.reportError(parser, real_exc)

            # should probably chain exceptions if we can...
            # Should I report the cancellation or recognition exception as the
            # cause...?
            six.raise_from(ParseException(error_listener.error_message),
                           real_exc)

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

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


Question:
Determine grid size (nrow, ncol) that could be used
for displaying a given number of elements.

@param nElem number of elements
@return grid dimensions (integers)

static Dimension determineGrid(int nElem) {
        switch (nElem) {
            case 0:
                return new Dimension(0, 0);
            case 1:
                return new Dimension(1, 1);
            case 2:
                return new Dimension(2, 1);
            case 3:
                return new Dimension(3, 1);
            case 4:
                return new Dimension(2, 2);
            case 5:
                return new Dimension(3, 2);
            case 6:
                return new Dimension(3, 2);
            case 7:
                return new Dimension(4, 2);
            case 8:
                return new Dimension(4, 2);
            case 9:
                return new Dimension(3, 3);
            default:
                // not great but okay
                int nrow = (int) Math.floor(Math.sqrt(nElem));
                int ncol = (int) Math.ceil(nElem / (double) nrow);
                return new Dimension(ncol, nrow);
        }
    }

def select_where(self, where_col_list, where_value_list, col_name=''):

        res = []        # list of rows to be returned
        col_ids = []    # ids of the columns to check
        #print('select_where  : arr = ',  len(self.arr), 'where_value_list = ',  where_value_list)
        for col_id, col in enumerate(self.header):
            if col in where_col_list:
                col_ids.append([col_id, col])
        #print('select_where    : col_ids = ',  col_ids)   # correctly prints [[0, 'TERM'], [2, 'ID']]

        for row_num, row in enumerate(self.arr):
            keep_this_row = True
            #print('col_ids=', col_ids, ' row = ', row_num, row)
            for ndx, where_col in enumerate(col_ids):
                #print('type where_value_list[ndx] = ', type(where_value_list[ndx]))
                #print('type row[where_col[0]] = ', type(row[where_col[0]]))

                if row[where_col[0]] != where_value_list[ndx]:
                    keep_this_row = False
            if keep_this_row is True:
                if col_name == '':
                    res.append([row_num, row])
                else:   # extracting a single column only
                    l_dat = self.get_col_by_name(col_name)
                    if l_dat is not None:
                        res.append(row[l_dat])
        return res

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


Question:
Get a client instance for a given server key
@param $serverKey An entry in the configuration section 'remoteserver'
@return A client instance or null

private function getClient($serverKey) {
    if (!isset($this->clients[$serverKey])) {
      $config = ObjectFactory::getInstance('configuration');
      $serverDef = $config->getValue($serverKey, 'remoteserver');
      // get remote the user
      $user = $this->getRemoteUser($serverKey);

      $client = null;
      if (strpos($serverDef, 'http://') === 0 || strpos($serverDef, 'https://') === 0) {
        $client = new HTTPClient($serverDef, $user);
      }
      else {
        $client = new RPCClient($serverDef, $user);
      }
      $this->clients[$serverKey] = $client;
    }
    return $this->clients[$serverKey];
  }

func (_m *MockProvider) Configure(clusterId string, isRoot bool, rawConfig map[string]interface{}) error {
	ret := _m.Called(clusterId, isRoot, rawConfig)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, bool, map[string]interface{}) error); ok {
		r0 = rf(clusterId, isRoot, rawConfig)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

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


Question: Gets the target object for a call to the RetainedWith wrapper.

private Expression getRetainedWithTarget(Assignment node, VariableElement var) {
    Expression lhs = node.getLeftHandSide();
    if (!(lhs instanceof FieldAccess)) {
      return new ThisExpression(ElementUtil.getDeclaringClass(var).asType());
    }
    // To avoid duplicating the target expression we must save the result to a local variable.
    FieldAccess fieldAccess = (FieldAccess) lhs;
    Expression target = fieldAccess.getExpression();
    VariableElement targetVar = GeneratedVariableElement.newLocalVar(
        "__rw$" + rwCount++, target.getTypeMirror(), null);
    TreeUtil.asStatementList(TreeUtil.getOwningStatement(lhs))
        .add(0, new VariableDeclarationStatement(targetVar, null));
    fieldAccess.setExpression(new SimpleName(targetVar));
    CommaExpression commaExpr = new CommaExpression(
        new Assignment(new SimpleName(targetVar), target));
    node.replaceWith(commaExpr);
    commaExpr.addExpression(node);
    return new SimpleName(targetVar);
  }

func WithPullLabel(key, value string) RemoteOpt {
	return func(_ *Client, rc *RemoteContext) error {
		if rc.Labels == nil {
			rc.Labels = make(map[string]string)
		}

		rc.Labels[key] = value
		return nil
	}
}

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


Question:
Set the character to use for line endings.

@param string $lineEnding The character to use for line endings

@return static

public function setLineEnding($lineEnding)
    {
        if (!is_string($lineEnding) || strlen($lineEnding) < 1) {
            throw new \InvalidArgumentException("Invalid line ending specified, must be a string at least 1 character long");
        }

        $this->lineEnding = $lineEnding;

        return $this;
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: // HasResource checks if there is enough "res" in the "resources" argument

func HasResource(res *api.GenericResource, resources []*api.GenericResource) bool {
	for _, r := range resources {
		if Kind(res) != Kind(r) {
			continue
		}

		switch rtype := r.Resource.(type) {
		case *api.GenericResource_DiscreteResourceSpec:
			if res.GetDiscreteResourceSpec() == nil {
				return false
			}

			if res.GetDiscreteResourceSpec().Value < rtype.DiscreteResourceSpec.Value {
				return false
			}

			return true
		case *api.GenericResource_NamedResourceSpec:
			if res.GetNamedResourceSpec() == nil {
				return false
			}

			if res.GetNamedResourceSpec().Value != rtype.NamedResourceSpec.Value {
				continue
			}

			return true
		}
	}

	return false
}

def _wrapper_enabled?
        return false unless request.has_content_type?

        ref = request.content_mime_type.ref
        _wrapper_formats.include?(ref) && _wrapper_key && !request.parameters.key?(_wrapper_key)
      end

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


Question:
Fetch the method signature of a method when we have already created a \ReflectionClass
@param \ReflectionClass $reflectionClass
@param string $methodName
@return array
@throws \ReflectionException

public function getSignatureByReflectionClass(\ReflectionClass $reflectionClass, $methodName)
    {
        $className = $reflectionClass->getName();
        return $this->getMethodSignature($className, $methodName, $reflectionClass);
    }

public static function formatMessage($callable, $parameterName)
    {

        switch (true) {
            case is_array($callable):
                $message = sprintf('%s::%s()', get_class($callable[0]), $callable[1]);
                break;
            case is_object($callable):
                $message = get_class($callable);
                break;
            default:
                $message = (string)$callable;
                break;
        }

        return 'Unable to match parameter named [' . $parameterName . '] for the callable [' . $message . ']';
    }

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


Question:
// NewSourceInfo - create a compose-object/copy-object source info
// object.
//
// `decryptSSEC` is the decryption key using server-side-encryption
// with customer provided key. It may be nil if the source is not
// encrypted.

func NewSourceInfo(bucket, object string, sse encrypt.ServerSide) SourceInfo {
	r := SourceInfo{
		bucket:     bucket,
		object:     object,
		start:      -1, // range is unspecified by default
		encryption: sse,
		Headers:    make(http.Header),
	}

	// Set the source header
	r.Headers.Set("x-amz-copy-source", s3utils.EncodePath(bucket+"/"+object))
	return r
}

func (client *SSHClient) GetSSHPrivateKey() string {
	client.Creds.mu.Lock()
	defer client.Creds.mu.Unlock()
	return client.Creds.SSHPrivateKey
}

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


Question: // Text returns the value of a literal as a string.

func (l *Literal) Text() (string, error) {
	if l.t != Text {
		return "", fmt.Errorf("literal.Text: literal is of type %v; cannot be converted to a string", l.t)
	}
	return l.v.(string), nil
}

public static boolean isIntLiteral(final RexNode rexNode)
  {
    return rexNode instanceof RexLiteral && SqlTypeName.INT_TYPES.contains(rexNode.getType().getSqlTypeName());
  }

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


Question:
Called when a player chats.

@param Player $player
@param        $text

@return void

public function onPlayerChat(Player $player, $text)
    {
        if ($player->getPlayerId() === 0) {
            return;
        }
        if (substr($text, 0, 1) == "/") {
            return;
        }

        if ($text == "++") {
            $this->setVote($player->getLogin(), 100);
        }

        if ($text == "--") {
            $this->setVote($player->getLogin(), 0);
        }

    }

function( data, client ) {

    this.client = client;

    /**
     * @summary Linked channels
     *
     * @name Channel#links
     * @type Channel[]
     */
    this.links = [];

    /**
     * @summary Child channels
     *
     * @name Channel#children
     * @type Channel[]
     */
    this.children = [];

    /**
     * @summary Users in the channel
     *
     * @name Channel#users
     * @type User[]
     */
    this.users = [];

    this._checkParent( data ); // Needs to be done seperate
    this._applyProperties( data );

    // TODO: Description
}

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


Question:
Identify that the comparison failed
@param field Which field failed
@param exception exception containing details of match failure
@return result of comparision

public JSONCompareResult fail(String field, ValueMatcherException exception) {
    	fail(field + ": " + exception.getMessage(), exception.getExpected(), exception.getActual());
        return this;
    }

def parse_data_to_internal(self, data=None):

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

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


Question:
Append patch version to $version if $version only contains
major and minor versions.

@param string $version
@return string

static public function appendPatchVersion($version)
    {
        $shortKnownVersions = array('2.0', '2.1', '2.2');
        if (in_array($version, $shortKnownVersions) === true) {
            $version = $version . '.0';
        }

        return $version;
    }

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

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


Question:
Sets an array of submitted data
@param string|array|null $key
@param mixed $value
@param boolean|string $filter
@return array

public function setSubmitted($key = null, $value = null, $filter = true)
    {
        if (!isset($key)) {

            if (isset($value)) {
                return $this->submitted = (array) $value;
            }

            $this->submitted = (array) $this->request->post(null, array(), $filter, 'array');
            return $this->submitted;
        }

        if (!isset($value) && empty($this->submitted)) {
            $this->post_key = (string) $key;
            $this->submitted = (array) $this->request->post($key, array(), $filter, 'array');
            return $this->submitted;
        }

        gplcart_array_set($this->submitted, $key, $value);
        return $this->submitted;
    }

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
POST (C)RUD - Store data.

@param \Illuminate\Http\Request $request

@return \Illuminate\Http\RedirectResponse

public function store(Request $request)
    {
        $slug = $this->getSlug($request);

        $dataType = Admin::model('DataType')->where('slug', '=', $slug)->first();
        $model = app($dataType->model_name);

        // Check permission
        $this->authorize('edit', $model);

        if ($model instanceof ModelValidator) {
            // Model validation
            $validator = $model->validate($request);
        } else {
            // Crud validation
            $validator = $this->validateCrud($request->all(), $dataType->addRows);
        }

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->messages()]);
        }

        if (!$request->ajax()) {
            $data = $this->insertUpdateData($request, $slug, $dataType->addRows, new $dataType->model_name());

            event(new CrudDataAdded($request, $slug, $dataType, $data));

            $redirect = redirect(admin_route($dataType->slug . ".index"));

            if ($dataType->isBackToParentCrud()) {
                $requestQuery = (object) $request->query();

                $redirect = redirect(admin_route($requestQuery->crud_slug . '.' . $requestQuery->crud_action, $requestQuery->crud_id));
            }

            if ($dataType->isBackToEdit()) {
                $redirect = redirect(admin_route($dataType->slug . '.edit', $data->id));
            }

            return $redirect->with([
                'message'    => __('admin.generic.successfully_updated')." {$dataType->display_name_singular}",
                'alert-type' => 'success',
            ]);
        }
    }

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: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *Lease) DeepCopyInto(out *Lease) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
	in.Spec.DeepCopyInto(&out.Spec)
	return
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

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


Question: // Implementation of http.FileSystem

func (f *FileSystem) Open(p string) (http.File, error) {
	p = path.Clean(p)

	if len(f.LocalPath) != 0 {
		return http.Dir(f.LocalPath).Open(p)
	}

	if fi, ok := f.Files[p]; ok {
		if !fi.IsDir() {
			// Make a copy for reading
			ret := fi
			ret.buf = bytes.NewReader(ret.Data)

			return ret, nil
		}

		return fi, nil
	}

	return nil, os.ErrNotExist
}

public function addHandler( IVfsHandler $handler ) : IVfsManager
   {

      $this->_handlers[ $handler->getName() ] = $handler;

      return $this;

   }

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


Question:
// handleConfigMapFromEnvFileSource adds the specified env file source information
// into the provided configMap

func handleConfigMapFromEnvFileSource(configMap *v1.ConfigMap, envFileSource string) error {
	info, err := os.Stat(envFileSource)
	if err != nil {
		switch err := err.(type) {
		case *os.PathError:
			return fmt.Errorf("error reading %s: %v", envFileSource, err.Err)
		default:
			return fmt.Errorf("error reading %s: %v", envFileSource, err)
		}
	}
	if info.IsDir() {
		return fmt.Errorf("env config file cannot be a directory")
	}

	return addFromEnvFile(envFileSource, func(key, value string) error {
		return addKeyFromLiteralToConfigMap(configMap, key, value)
	})
}

def environment_context_path(cls, project, environment, user, session,
                                 context):
        """"""
        return google.api_core.path_template.expand(
            'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}',
            project=project,
            environment=environment,
            user=user,
            session=session,
            context=context,
        )

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


Question: Updates the version of MTP-common

def set_version(context: Context, version=None, bump=False):

    if bump and version:
        raise TaskError('You cannot bump and set a specific version')
    if bump:
        from mtp_common import VERSION

        version = list(VERSION)
        version[-1] += 1
    else:
        try:
            version = list(map(int, version.split('.')))
            assert len(version) == 3
        except (AttributeError, ValueError, AssertionError):
            raise TaskError('Version must be in the form N.N.N')

    dotted_version = '.'.join(map(str, version))
    replacements = [
        (r'^VERSION =.*$',
         'VERSION = (%s)' % ', '.join(map(str, version)),
         'mtp_common/__init__.py'),
        (r'^  "version":.*$',
         '  "version": "%s",' % dotted_version,
         'package.json'),
    ]
    for search, replacement, path in replacements:
        with open(os.path.join(root_path, path)) as f:
            content = f.read()
        content = re.sub(search, replacement, content, flags=re.MULTILINE)
        with open(os.path.join(root_path, path), 'w') as f:
            f.write(content)
    context.debug('Updated version to %s' % dotted_version)

public void setType(JvmType newType)
	{
		JvmType oldType = type;
		type = newType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, TypesPackage.JVM_ANY_TYPE_REFERENCE__TYPE, oldType, type));
	}

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


Question:
readGif(filename, asNumpy=True)

    Read images from an animated GIF file.  Returns a list of numpy
    arrays, or, if asNumpy is false, a list if PIL images.

def readGif(filename, asNumpy=True):

    # Check PIL
    if PIL is None:
        raise RuntimeError("Need PIL to read animated gif files.")

    # Check Numpy
    if np is None:
        raise RuntimeError("Need Numpy to read animated gif files.")

    # Check whether it exists
    if not os.path.isfile(filename):
        raise IOError('File not found: ' + str(filename))

    # Load file using PIL
    pilIm = PIL.Image.open(filename)
    pilIm.seek(0)

    # Read all images inside
    images = []
    try:
        while True:
            # Get image as numpy array
            tmp = pilIm.convert()  # Make without palette
            a = np.asarray(tmp)
            if len(a.shape) == 0:
                raise MemoryError("Too little memory to convert PIL image to array")
            # Store, and next
            images.append(a)
            pilIm.seek(pilIm.tell() + 1)
    except EOFError:
        pass

    # Convert to normal PIL images if needed
    if not asNumpy:
        images2 = images
        images = []
        for im in images2:
            images.append(PIL.Image.fromarray(im))

    # Done
    return images

def _init_nt_hdr(self, line):
        """"""
        line = line.replace('.', '_')
        line = line.replace(' ', '_')
        line = line.replace('#', 'N')
        line = line.replace('-', '_')
        line = line.replace('"', '')
        #line = re.sub(r"_$", r"", line)
        hdrs = re.split(self.sep, line)
        if '' in hdrs:
            hdrs = NCBIgeneFileReader.replace_nulls(hdrs)
        # Init indexes which will be converted to int or float
        self.idxs_int = [idx for idx, hdr in enumerate(hdrs) if hdr in self.int_hdrs]
        self.idxs_float = [idx for idx, hdr in enumerate(hdrs) if hdr in self.float_hdrs]
        assert hdrs[6] == 'Aliases'
        return namedtuple('ntncbi', ' '.join(hdrs))

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


Question:
Update filtered balancer pools

@param loadBalancerPoolFilter load balancer pool filter
@param config load balancer pool config
@return OperationFuture wrapper for load balancer pool list

public OperationFuture<List<LoadBalancerPool>> update(
            LoadBalancerPoolFilter loadBalancerPoolFilter,
            LoadBalancerPoolConfig config
    ) {
        checkNotNull(loadBalancerPoolFilter, "Load balancer pool filter must be not null");

        List<LoadBalancerPool> loadBalancerPoolList = findLazy(loadBalancerPoolFilter)
            .map(metadata -> LoadBalancerPool.refById(
                metadata.getId(),
                LoadBalancer.refById(
                    metadata.getLoadBalancerId(),
                    DataCenter.refById(metadata.getDataCenterId())
                )
            ))
            .collect(toList());

        return update(loadBalancerPoolList, config);
    }

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:
用于Model对象转化为DO对象

@param throughputStat
@return throughputStatDO

private ThroughputStatDO throughputStatModelToDo(ThroughputStat throughputStat) {
        ThroughputStatDO throughputStatDO = new ThroughputStatDO();
        throughputStatDO.setId(throughputStat.getId());
        throughputStatDO.setPipelineId(throughputStat.getPipelineId());
        throughputStatDO.setStartTime(throughputStat.getStartTime());
        throughputStatDO.setEndTime(throughputStat.getEndTime());
        throughputStatDO.setType(throughputStat.getType());
        throughputStatDO.setNumber(throughputStat.getNumber());
        throughputStatDO.setSize(throughputStat.getSize());
        throughputStatDO.setGmtCreate(throughputStat.getGmtCreate());
        throughputStatDO.setGmtModified(throughputStat.getGmtModified());
        return throughputStatDO;
    }

public static function route() :void {

		// marker
		Profiler::setMarker('Router.route', 'framework');
		// get the requested url
		$request_url = Request::getUrl();
		// get the requested method
		$request_method = Request::getMethod();
		// Loop over each route and test to see if they are valid
		foreach(self::$_routes as $route) {
			// if the route matches
			if(self::routeMatch($request_url, $request_method, $route)) {
				// get it
				$matching_route = $route;
				// stop trying
				break;
			}
		}
		// marker
		Profiler::releaseMarker('Router.route');
		// if no match is found and we don't have an error route to fallback on
		if(!isset($matching_route)) {
			// throw a native exception since there is no cleaner alternative
			Throw new Exception('Router::route() no matching route', 404);
		}
		// send the matching route to the dispatcher
		self::forward($matching_route);

	}

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


Question: // Determines if the given items are all in the set

func (set WordSet) ContainsAll(i ...string) bool {
	for _, v := range i {
		if !set.Contains(v) {
			return false
		}
	}
	return true
}

func gt(lhs Expression, rhs interface{}) BooleanExpression {
	return boolean{op: GT_OP, lhs: lhs, rhs: rhs}
}

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


Question:
Quit chat.

@param string $chatId
@param string $opUser

@return \EntWeChat\Support\Collection

public function quit($chatId, $opUser)
    {
        $params = [
            'chatid'  => $chatId,
            'op_user' => $opUser,
        ];

        return $this->parseJSON('json', [self::API_QUIT, $params]);
    }

func (c *ChannelsHistoryCall) Values() (url.Values, error) {
	if err := c.ValidateArgs(); err != nil {
		return nil, errors.Wrap(err, `failed validation`)
	}
	v := url.Values{}
	v.Set(`token`, c.service.token)

	v.Set("channel", c.channel)

	if c.count > 0 {
		v.Set("count", strconv.Itoa(c.count))
	}

	if c.inclusive {
		v.Set("inclusive", "true")
	}

	if len(c.latest) > 0 {
		v.Set("latest", c.latest)
	}

	if len(c.oldest) > 0 {
		v.Set("oldest", c.oldest)
	}

	if len(c.timestamp) > 0 {
		v.Set("ts", c.timestamp)
	}

	if c.unreads {
		v.Set("unreads", "true")
	}
	return v, nil
}

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


Question:
Generates a 16-byte UUID that encodes the given Offset as a Backpointer (to some other offset).
Format {0(64)}{Offset}
- MSB is 0
- LSB is Offset.

@param offset The offset to generate a backpointer from.
@return A UUID representing the Attribute Key.

protected UUID getBackpointerAttributeKey(long offset) {
        Preconditions.checkArgument(offset >= 0, "offset must be a non-negative number.");
        return new UUID(TableBucket.BACKPOINTER_PREFIX, offset);
    }

@Override
  public void commitBlock(long workerId, long usedBytesOnTier, String tierAlias, long blockId,
      long length) throws NotFoundException, UnavailableException {
    LOG.debug("Commit block from workerId: {}, usedBytesOnTier: {}, blockId: {}, length: {}",
        workerId, usedBytesOnTier, blockId, length);

    MasterWorkerInfo worker = mWorkers.getFirstByField(ID_INDEX, workerId);
    // TODO(peis): Check lost workers as well.
    if (worker == null) {
      throw new NotFoundException(ExceptionMessage.NO_WORKER_FOUND.getMessage(workerId));
    }

    // Lock the worker metadata first.
    try (JournalContext journalContext = createJournalContext()) {
      synchronized (worker) {
        try (LockResource lr = lockBlock(blockId)) {
          Optional<BlockMeta> block = mBlockStore.getBlock(blockId);
          if (!block.isPresent() || block.get().getLength() != length) {
            if (block.isPresent() && block.get().getLength() != Constants.UNKNOWN_SIZE) {
              LOG.warn("Rejecting attempt to change block length from {} to {}",
                  block.get().getLength(), length);
            } else {
              mBlockStore.putBlock(blockId, BlockMeta.newBuilder().setLength(length).build());
              BlockInfoEntry blockInfo =
                  BlockInfoEntry.newBuilder().setBlockId(blockId).setLength(length).build();
              journalContext.append(JournalEntry.newBuilder().setBlockInfo(blockInfo).build());
            }
          }

          // Update the block metadata with the new worker location.
          mBlockStore.addLocation(blockId, BlockLocation.newBuilder()
              .setWorkerId(workerId)
              .setTier(tierAlias)
              .build());
          // This worker has this block, so it is no longer lost.
          mLostBlocks.remove(blockId);

          // Update the worker information for this new block.
          // TODO(binfan): when retry commitBlock on master is expected, make sure metrics are not
          // double counted.
          worker.addBlock(blockId);
          worker.updateUsedBytes(tierAlias, usedBytesOnTier);
          worker.updateLastUpdatedTimeMs();
        }
      }
    }
  }

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


Question: Show the content of the PeekView by adding it to the android.R.id.content FrameLayout.

public void show() {
        androidContentView.addView(this);

        // set the translations for the content view
        content.setTranslationX(distanceFromLeft);
        content.setTranslationY(distanceFromTop);

        // animate the alpha of the PeekView
        ObjectAnimator animator = ObjectAnimator.ofFloat(this, View.ALPHA, 0.0f, 1.0f);
        animator.addListener(new AnimatorEndListener() {
            @Override
            public void onAnimationEnd(Animator animator) {
                if (callbacks != null) {
                    callbacks.shown();
                }
            }
        });
        animator.setDuration(options.useFadeAnimation() ? ANIMATION_TIME : 0);
        animator.setInterpolator(INTERPOLATOR);
        animator.start();
    }

public static LoaderPipe getPipe(String name, Activity activity) {
        Pipe pipe = pipes.get(name);
        LoaderAdapter adapter = new LoaderAdapter(activity, pipe, name);
        adapter.setLoaderIds(loaderIdsForNamed);
        return adapter;
    }

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


Question: Hacks to make the filesystem look normal.

def FileHacks(self):
    """"""
    if sys.platform == "win32":
      import win32api  # pylint: disable=g-import-not-at-top

      # Make the filesystem look like the topmost level are the drive letters.
      if self.path == "/":
        self.files = win32api.GetLogicalDriveStrings().split("\x00")
        # Remove empty strings and strip trailing backslashes.
        self.files = [drive.rstrip("\\") for drive in self.files if drive]

      # This regex will match the various windows devices. Raw hard disk devices
      # must be considered files, however in windows, if we try to list them as
      # directories this also works. Since the code above distinguished between
      # files and directories using the file listing property, we must force
      # treating raw devices as files.
      elif re.match(r"/*\\\\.\\[^\\]+\\?$", self.path) is not None:
        # Special case windows devices cant seek to the end so just lie about
        # the size
        self.size = 0x7fffffffffffffff

        # Windows raw devices can be opened in two incompatible modes. With a
        # trailing \ they look like a directory, but without they are the raw
        # device. In GRR we only support opening devices in raw mode so ensure
        # that we never append a \ to raw device name.
        self.path = self.path.rstrip("\\")

        # In windows raw devices must be accessed using sector alignment.
        self.alignment = 512
    elif sys.platform == "darwin":
      # On Mac, raw disk devices are also not seekable to the end and have no
      # size so we use the same approach as on Windows.
      if re.match("/dev/r?disk.*", self.path):
        self.size = 0x7fffffffffffffff
        self.alignment = 512

func (d *FileDepot) Get(tag *Tag) ([]byte, error) {
	if err := d.check(tag); err != nil {
		return nil, err
	}
	return ioutil.ReadFile(d.path(tag.name))
}

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


Question: // Load loads credential information from a reader.

func (c *CredentialsStore) Load(r io.Reader) error {
	dec := json.NewDecoder(r)
	// Read open bracket
	_, err := dec.Token()
	if err != nil {
		return err
	}

	var cred Credential
	for dec.More() {
		err := dec.Decode(&cred)
		if err != nil {
			return err
		}
		c.store[cred.Username] = cred.Password
		c.perms[cred.Username] = make(map[string]bool, len(cred.Perms))
		for _, p := range cred.Perms {
			c.perms[cred.Username][p] = true
		}
	}

	// Read closing bracket.
	_, err = dec.Token()
	if err != nil {
		return err
	}

	return nil
}

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

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


Question:
Required by the ArrayAccess interface.

@param  string $offset
@param  string $value
@return string

public function offsetSet($offset, $value)
    {
        $this->ensureAppended();

        if (strpos($offset, ':') !== false) {
            list($ns, $attr) = explode(':', $offset, 2);
            return $this->_element->setAttributeNS(Zend_Feed::lookupNamespace($ns), $attr, $value);
        } else {
            return $this->_element->setAttribute($offset, $value);
        }
    }

private Response query(ChaincodeStub stub, List<String> args) {
        if (args.size() != 1) {
            return newErrorResponse("Incorrect number of arguments. Expecting name of the person to query");
        }
        String key = args.get(0);
        //byte[] stateBytes
        String val	= stub.getStringState(key);
        if (val == null) {
            return newErrorResponse(String.format("Error: state for %s is null", key));
        }
        _logger.info(String.format("Query Response:\nName: %s, Amount: %s\n", key, val));
        return newSuccessResponse(val, ByteString.copyFrom(val, UTF_8).toByteArray());
    }

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


Question: // Kill a container

func (r *Runtime) Kill(sig string) (err error) {
	var args []string
	args = append(args, "kill")
	if r.ID != "" {
		args = append(args, r.ID)
	}
	if sig != "" {
		// TODO: runc does not support this
		//	args = append(args, "--signal", sig)
		args = append(args, sig)
	} else {
		args = append(args, DefaultSignal)
	}

	cmd := exec.Command(r.RuntimeCommand, args...)
	return execWithStderrFallbackToStdout(cmd)
}

function reset() {
		globalConfig = {};
		modules = {};
		services = {};
		behaviors = {};
		instances = {};
		initialized = false;

		for (var i = 0; i < exports.length; i++) {
			delete application[exports[i]];
			delete Box.Context.prototype[exports[i]];
		}
		exports = [];
	}

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


Question:
Always fetch the value from the source. That is a copy of getEntryInternal
without freshness checks.

protected void loadAndReplace(K key) {
    Entry e;
    for (;;) {
      e = lookupOrNewEntry(key);
      synchronized (e) {
        e.waitForProcessing();
        if (e.isGone()) {
          metrics.goneSpin();
          continue;
        }
        e.startProcessing(Entry.ProcessingState.LOAD);
        break;
      }
    }
    boolean _finished = false;
    try {
      load(e);
      _finished = true;
    } finally {
      e.ensureAbort(_finished);
    }
  }

def get_grade_entries_by_search(self, grade_entry_query, grade_entry_search):
        """"""
        # Implemented from azosid template for -
        # osid.resource.ResourceSearchSession.get_resources_by_search_template
        if not self._can('search'):
            raise PermissionDenied()
        return self._provider_session.get_grade_entries_by_search(grade_entry_query, grade_entry_search)

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


Question:
@param ActionEvent $event

@return ListenerHandler[]

private function getListeners(ActionEvent $event): iterable
    {
        $prioritizedListeners = $this->events[$event->getName()] ?? [];

        \krsort($prioritizedListeners, SORT_NUMERIC);

        foreach ($prioritizedListeners as $listenersByPriority) {
            foreach ($listenersByPriority as $listenerHandler) {
                yield $listenerHandler;
            }
        }
    }

public void fireTagParseEvent(TagParseEvent tpe)
	{
		for (int i = 0; i < tagParseListeners.size(); i++)
		{
			TagParseListener l = tagParseListeners.get(i);
			l.tagParsed(tpe);
		}
	}

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


Question: Returns a builder for the specified text tag.

public static <E extends HTMLElement> TextContentBuilder<E> textElement(String tag, Class<E> type) {
        return new TextContentBuilder<>(createElement(tag, type));
    }

public function process(ContainerBuilder $container)
    {
        $checkers = array();
        foreach ($container->findTaggedServiceIds('avoo.resource_generator.template') as $id => $attributes) {
            $checkers[$attributes[0]['type']] = $id;
        }

        $container->setParameter('avoo.resource_generator.templates', $checkers);
    }

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


Question:
Given a weighted set and sample size return the probabilty that the
        weight `i` will be present in the sample.

        Created to test the output of the `SomeOf` maker class. The math was
        provided by Andy Blackshaw - thank you dad :)

def p(i, sample_size, weights):

        # Determine the initial pick values
        weight_i = weights[i]
        weights_sum = sum(weights)

        # Build a list of weights that don't contain the weight `i`. This list will
        # be used to build the possible picks before weight `i`.
        other_weights = list(weights)
        del other_weights[i]

        # Calculate the probability
        probability_of_i = 0
        for picks in range(0, sample_size):

            # Build the list of possible permutations for this pick in the sample
            permutations = list(itertools.permutations(other_weights, picks))

            # Calculate the probability for this permutation
            permutation_probabilities = []
            for permutation in permutations:

                # Calculate the probability for each pick in the permutation
                pick_probabilities = []
                pick_weight_sum = weights_sum

                for pick in permutation:
                    pick_probabilities.append(pick / pick_weight_sum)

                    # Each time we pick we update the sum of the weight the next
                    # pick is from.
                    pick_weight_sum -= pick

                # Add the probability of picking i as the last pick
                pick_probabilities += [weight_i / pick_weight_sum]

                # Multiply all the probabilities for the permutation together
                permutation_probability = reduce(
                    lambda x, y: x * y, pick_probabilities
                    )
                permutation_probabilities.append(permutation_probability)

            # Add together all the probabilities for all permutations together
            probability_of_i += sum(permutation_probabilities)

        return probability_of_i

protected function queue($key) {
        $queue_name=isset($this->options['queue_name'])?$this->options['queue_name']:'think_queue';
        $value  =  F($queue_name);
        if(!$value) {
            $value   =  array();
        }
        // 进列
        if(false===array_search($key, $value)) array_push($value,$key);
        if(count($value) > $this->options['length']) {
            // 出列
            $key =  array_shift($value);
            // 删除缓存
            $this->rm($key);
            if (APP_DEBUG) {
                    //调试模式下记录出队次数
                        $counter = Think::instance('SaeCounter');
                        if ($counter->exists($queue_name.'_out_times'))
                            $counter->incr($queue_name.'_out_times');
                        else
                            $counter->create($queue_name.'_out_times', 1);
           }
        }
        return F($queue_name,$value);
    }

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


Question:
Sets the status of the ASG.

@param asgName The name of the ASG
@param enabled true to enable, false to disable

public void setStatus(String asgName, boolean enabled) {
        String asgAccountId = getASGAccount(asgName);
        asgCache.put(new CacheKey(asgAccountId, asgName), enabled);
    }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
Install packages.

@throws \Bolt\Exception\PackageManagerException

@return int 0 on success or a positive error code on failure

public function execute()
    {
        /** @var $composer \Composer\Composer */
        $composer = $this->getComposer();
        $io = $this->getIO();
        $config = $composer->getConfig();

        $optimize = $this->getOptions()->optimizeAutoloader() || $config->get('optimize-autoloader');
        $authoritative = $this->getOptions()->classmapAuthoritative() || $config->get('classmap-authoritative');

        $install = Installer::create($io, $composer)
            ->setDryRun($this->getOptions()->dryRun())
            ->setVerbose($this->getOptions()->verbose())
            ->setPreferSource($this->getOptions()->preferSource())
            ->setPreferDist($this->getOptions()->preferDist())
            ->setDevMode(!$this->getOptions()->noDev())
            ->setDumpAutoloader(!$this->getOptions()->noAutoloader())
            ->setRunScripts(!$this->getOptions()->noScripts())
            ->setOptimizeAutoloader($optimize)
            ->setClassMapAuthoritative($authoritative)
            ->setIgnorePlatformRequirements($this->getOptions()->ignorePlatformReqs())
        ;

        try {
            return $install->run();
        } catch (\Exception $e) {
            $msg = sprintf('%s received an error from Composer: %s in %s::%s', __METHOD__, $e->getMessage(), $e->getFile(), $e->getLine());
            $this->app['logger.system']->critical($msg, ['event' => 'exception', 'exception' => $e]);
            throw new PackageManagerException($e->getMessage(), $e->getCode(), $e);
        }
    }

public static function execute($value, ContextInterface $context): array
    {
        if (is_string($value) === true) {
            $lcValue = strtolower($value);
            if ($lcValue === 'true' || $lcValue === '1' || $lcValue === 'on' || $lcValue === 'yes') {
                $reply = static::createSuccessReply(true);
            } elseif ($lcValue === 'false' || $lcValue === '0' || $lcValue === 'off' || $lcValue === 'no') {
                $reply = static::createSuccessReply(false);
            } else {
                $reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []);
            }
        } elseif (is_bool($value) === true) {
            $reply = static::createSuccessReply($value);
        } else {
            $reply = static::createErrorReply($context, $value, ErrorCodes::IS_BOOL, Messages::IS_BOOL, []);
        }

        return $reply;
    }

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


Question:
Recoursively creates new item tree structures based on a provided
ItemConfiguration object

@param   {Object} config ItemConfig
@param   {[ContentItem]} parent The item the newly created item should be a child of

@returns {lm.items.ContentItem}

function( config, parent ) {
		var typeErrorMsg, contentItem;

		if( typeof config.type !== 'string' ) {
			throw new lm.errors.ConfigurationError( 'Missing parameter \'type\'', config );
		}

		if( !this._typeToItem[ config.type ] ) {
			typeErrorMsg = 'Unknown type \'' + config.type + '\'. ' +
				'Valid types are ' + lm.utils.objectKeys( this._typeToItem ).join( ',' );

			throw new lm.errors.ConfigurationError( typeErrorMsg );
		}

		/**
		 * We add an additional stack around every component that's not within a stack anyways
		 */
		if( config.type === 'component' && !( parent instanceof lm.items.Stack ) && !!parent ) {
			config = {
				type: 'stack',
				isClosable: config.isClosable,
				width: config.width,
				height: config.height,
				content: [ config ]
			};
		}

		contentItem = new this._typeToItem[ config.type ]( this, config, parent );

		return contentItem;
	}

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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