Question:
// From returns a new Storm Node with a new bucket root below the current.
// All DB operations on the new node will be executed relative to this bucket.

func (n node) From(addend ...string) Node {
	n.rootBucket = append(n.rootBucket, addend...)
	return &n
}

function processBundleFile(file, bundleExt, variables, bundleHandler, errorCallback) {
	// get bundle files
	var lines = file.contents.toString().split('\n');
	var resultFilePaths = [];
	lines.forEach(function (line) {
		var filePath = getFilePathFromLine(file, line, variables);
		if (filePath)
			resultFilePaths.push(filePath);
	});

	if (!errorCallback)
		errorCallback = function () { };

	// find files and send to buffer
	var bundleSrc = fs.src(resultFilePaths)
		.on('error', errorCallback) // handle file not found errors
		.pipe(plumber(errorCallback)) // handle other errors inside pipeline
		.pipe(recursiveBundle(bundleExt, variables, errorCallback));

	if (bundleHandler && typeof bundleHandler === 'function')
		bundleSrc = bundleHandler(bundleSrc);
	return bundleSrc.pipe(plumber.stop());
}

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


Question:
Convert the value data type to int or returns false if the value is out of the integer value range.

@param mixed $value The value to be converted

@return int|false The converted value

private function getInt32Value($value)
    {
        if ($value > self::$int32Max || $value < -self::$int32Max - 1) {
            return false;
        }

        return (int) $value;
    }

func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
	input := i.Filters
	result := map[string]string{}
	pairings := map[string]interface{}{
		"filter[status]":           input.Status,
		"filter[rule][accuracy]":   input.Accuracy,
		"filter[rule][maturity]":   input.Maturity,
		"filter[rule][message]":    input.Message,
		"filter[rule][revision]":   input.Revision,
		"filter[rule][rule_id]":    input.RuleID,
		"filter[rule][tags]":       input.TagID,
		"filter[rule][tags][name]": input.TagName,
		"filter[rule][version]":    input.Version,
		"include":                  input.Tags,
		"page[size]":               input.MaxResults,
		"page[number]":             input.Page, // starts at 1, not 0
	}
	// NOTE: This setup means we will not be able to send the zero value
	// of any of these filters. It doesn't appear we would need to at present.
	for key, value := range pairings {
		switch t := reflect.TypeOf(value).String(); t {
		case "string":
			if value != "" {
				result[key] = value.(string)
			}
		case "int":
			if value != 0 {
				result[key] = strconv.Itoa(value.(int))
			}
		case "[]int":
			// convert ints to strings
			toStrings := []string{}
			values := value.([]int)
			for _, i := range values {
				toStrings = append(toStrings, strconv.Itoa(i))
			}
			// concat strings
			if len(values) > 0 {
				result[key] = strings.Join(toStrings, ",")
			}
		}
	}
	return result
}

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


Question:
Initialize this channel object for writing.

@throws IOException

public void initialize() throws IOException {
    // Create a pipe such that its one end is connected to the input stream used by
    // the uploader and the other end is the write channel used by the caller.
    PipedInputStream pipeSource = new PipedInputStream(pipeBufferSize);
    OutputStream pipeSink = new PipedOutputStream(pipeSource);
    pipeSinkChannel = Channels.newChannel(pipeSink);

    // Connect pipe-source to the stream used by uploader.
    InputStreamContent objectContentStream = new InputStreamContent(contentType, pipeSource);
    // Indicate that we do not know length of file in advance.
    objectContentStream.setLength(-1);
    objectContentStream.setCloseInputStream(false);

    T request = createRequest(objectContentStream);
    request.setDisableGZipContent(true);

    // Change chunk size from default value (10MB) to one that yields higher performance.
    clientRequestHelper.setChunkSize(request, uploadChunkSize);

    // Given that the two ends of the pipe must operate asynchronous relative
    // to each other, we need to start the upload operation on a separate thread.
    uploadOperation = threadPool.submit(new UploadOperation(request, pipeSource));

    isInitialized = true;
  }

public static Writable newInstance(Class<? extends Writable> c,
      Configuration conf) {
    return newInstance(c, conf, true);
  }

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


Question:
Checks if the given subject contains an object

@param mixed $subject
@return boolean If it contains an object or not

protected function containsObject($subject)
    {
        if (is_object($subject)) {
            return true;
        }
        if (!is_array($subject)) {
            return false;
        }
        foreach ($subject as $value) {
            if ($this->containsObject($value)) {
                return true;
            }
        }
        return false;
    }

public final EObject entryRuleTypeReferenceWithTypeArgs() throws RecognitionException {
        EObject current = null;

        EObject iv_ruleTypeReferenceWithTypeArgs = null;

        try {
            // InternalSARL.g:9222:66: (iv_ruleTypeReferenceWithTypeArgs= ruleTypeReferenceWithTypeArgs EOF )
            // InternalSARL.g:9223:2: iv_ruleTypeReferenceWithTypeArgs= ruleTypeReferenceWithTypeArgs EOF
            {
            if ( state.backtracking==0 ) {
               newCompositeNode(grammarAccess.getTypeReferenceWithTypeArgsRule());
            }
            pushFollow(FOLLOW_1);
            iv_ruleTypeReferenceWithTypeArgs=ruleTypeReferenceWithTypeArgs();

            state._fsp--;
            if (state.failed) return current;
            if ( state.backtracking==0 ) {
               current =iv_ruleTypeReferenceWithTypeArgs;
            }
            match(input,EOF,FOLLOW_2); if (state.failed) return current;

            }

        }

            catch (RecognitionException re) {
                recover(input,re);
                appendSkippedTokens();
            }
        finally {
        }
        return current;
    }

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


Question:
Transform summary information to HTML.

@param htmlWriter
the Writer to write the HTML output to

public void transformSummaryToHTML(Writer htmlWriter) throws IOException, TransformerException {

        ByteArrayOutputStream summaryOut = new ByteArrayOutputStream(8096);
        reportSummary(summaryOut);

        StreamSource in = new StreamSource(new ByteArrayInputStream(summaryOut.toByteArray()));
        StreamResult out = new StreamResult(htmlWriter);
        InputStream xslInputStream = this.getClass().getClassLoader().getResourceAsStream("summary.xsl");
        if (xslInputStream == null) {
            throw new IOException("Could not load summary stylesheet");
        }
        StreamSource xsl = new StreamSource(xslInputStream);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer(xsl);
        transformer.transform(in, out);

        Reader rdr = in.getReader();
        if (rdr != null) {
            rdr.close();
        }
        htmlWriter.close();
        InputStream is = xsl.getInputStream();
        if (is != null) {
            is.close();
        }
    }

public void setChannelSummaries(java.util.Collection<ChannelSummary> channelSummaries) {
        if (channelSummaries == null) {
            this.channelSummaries = null;
            return;
        }

        this.channelSummaries = new java.util.ArrayList<ChannelSummary>(channelSummaries);
    }

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


Question:
Register Antvel services in the container.

@return void

protected function registerServices()
    {
        foreach (Antvel::bindings() as $key => $value) {
            is_numeric($key)
                ? $this->app->singleton($value)
                : $this->app->singleton($key, $value);
        }
    }

public function initialize(Server $server)
    {
        $this->server = $server;
        $server->on('method:GET', [$this, 'httpGet'], 90);
        $server->on('propFind', [$this, 'propFind']);

        $server->xml->namespaceMap[self::NS_CALENDARSERVER] = 'cs';
        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Notifications\\ICollection'] = '{'.self::NS_CALENDARSERVER.'}notification';

        array_push($server->protectedProperties,
            '{'.self::NS_CALENDARSERVER.'}notification-URL',
            '{'.self::NS_CALENDARSERVER.'}notificationtype'
        );
    }

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


Question:
InExpression ::= SingleValuedPathExpression ["NOT"] "IN" "(" (InParameter {"," InParameter}* | Subselect) ")"

@return AST\InExpression

public function InExpression()
    {
        $inExpression = new AST\InExpression($this->ArithmeticExpression());

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

        $this->match(Lexer::T_IN);
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->subselect = $this->Subselect();
        } else {
            $literals   = [];
            $literals[] = $this->InParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
                $literals[] = $this->InParameter();
            }

            $inExpression->literals = $literals;
        }

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

        return $inExpression;
    }

protected XmlElement buildSqlClause(IntrospectedTable introspectedTable) {

    XmlElement sql = new XmlElement("sql");
    sql.addAttribute(new Attribute("id", IDENTIFIERS_ARRAY_CONDITIONS));

    XmlElement foreach = new XmlElement("foreach");
    foreach.addAttribute(new Attribute("collection", "array"));
    foreach.addAttribute(new Attribute("item", "item"));
    foreach.addAttribute(new Attribute("index", "index"));
    foreach.addAttribute(new Attribute("separator", " and "));

    StringBuilder sb = new StringBuilder();
    for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
      XmlElement isEqualElement = new XmlElement("if");
      sb.setLength(0);
      sb.append("item == \'");
      sb.append(introspectedColumn.getJavaProperty());
      sb.append("\'");
      isEqualElement.addAttribute(new Attribute("test", sb.toString()));
      foreach.addElement(isEqualElement);

      sb.setLength(0);
      sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
      sb.append(" = ");
      sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, PROPERTY_PREFIX));

      isEqualElement.addElement(new TextElement(sb.toString()));
    }

    sql.addElement(foreach);
    return sql;
  }

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


Question: XXX(sam) I don't understand why we create an instance if one doesn't exist yet. We don't appear to need it, why not let it come into existence on deploy or start?

function findOrCreateInstance(callback) {
    var models = self._meshApp.models;
    var Instance = models.ServiceInstance;

    service.instances(function(err, instances) {
      if (err) return callback(err);
      if (instances.length > 0) return callback();

      debug('onServiceUpdate: create first instance');

      var instance = new Instance({
        executorId: 1,
        serverServiceId: service.id,
        groupId: 1,
        cpus: 'STRONGLOOP_CLUSTER' in process.env ?
          process.env.STRONGLOOP_CLUSTER : 'CPU',

        // allow starting tracing on all instances via env for testing purposes
        tracingEnabled: !!process.env.STRONGLOOP_TRACING || false,
      });
      instance.save(callback);
    });
  }

public function initializeObject()
    {
        $client = new \Raven_Client($this->dsn);
        $errorHandler = new \Raven_ErrorHandler($client, true);
        $errorHandler->registerShutdownFunction();
        $this->client = $client;

        $this->setTags();
        $this->setEnvironment();
        $this->setRelease();
        $this->setAppPath();
        $this->setPrefixes();

        $this->emitSentryClientCreated($client);
    }

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


Question:
Returns a new interval based on this interval but with a different start
date.

@param date the new start date
@return a new interval

public Interval withStartDate(LocalDate date) {
        requireNonNull(date);
        return new Interval(date, startTime, endDate, endTime, zoneId);
    }

function mutualInformationProvider(publicAPI, model) {
  let hasData = false;
  const onMutualInformationReady = publicAPI.onMutualInformationReady;
  const mutualInformationData = PMI.initializeMutualInformationData();
  const deltaHandling = {
    added: [],
    removed: [],
    modified: [],
    previousMTime: {},
    currentMTime: {},
    processed: true,
  };

  function updateHistogram2D(histograms) {
    // even if histograms only has maxCount = 0, run through PMI.updateMI
    // so deltaHandling.removed array is handled properly.
    const invalidAxis = [];
    // Extract mtime
    deltaHandling.modified = [];
    deltaHandling.previousMTime = deltaHandling.currentMTime;
    deltaHandling.currentMTime = {};
    if (Object.keys(histograms).length > 1) {
      model.mutualInformationParameterNames.forEach((name) => {
        if (histograms[name] && histograms[name][name]) {
          // Validate range
          if (histograms[name][name].x.delta === 0) {
            invalidAxis.push(name);
            deltaHandling.currentMTime[name] = 0;
          } else {
            deltaHandling.currentMTime[name] = histograms[name][name].x.mtime;
          }

          if (
            deltaHandling.added.indexOf(name) === -1 &&
            deltaHandling.currentMTime[name] &&
            (deltaHandling.previousMTime[name] || 0) <
              deltaHandling.currentMTime[name]
          ) {
            deltaHandling.modified.push(name);
          }
        }
      });
    }
    // Check mutualInformationParameterNames are consistent with the current set of data
    // if not just for the next notification...
    try {
      PMI.updateMutualInformation(
        mutualInformationData,
        [].concat(deltaHandling.added, deltaHandling.modified),
        [].concat(deltaHandling.removed, invalidAxis),
        histograms
      );

      // Push the new mutual info
      deltaHandling.processed = true;
      hasData = true;
      publicAPI.fireMutualInformationReady(mutualInformationData);
    } catch (e) {
      console.log('PMI error', e);
    }
  }

  publicAPI.onMutualInformationReady = (callback) => {
    if (hasData) {
      callback(mutualInformationData);
    }
    return onMutualInformationReady(callback);
  };

  publicAPI.setHistogram2dProvider = (provider) => {
    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.unsubscribe();
    }
    model.histogram2dProvider = provider;
    if (provider) {
      model.histogram2dProviderSubscription = provider.subscribeToHistogram2D(
        updateHistogram2D,
        listToPair(model.mutualInformationParameterNames),
        { symmetric: true, partial: false }
      );
    }
  };

  publicAPI.setMutualInformationParameterNames = (names) => {
    if (deltaHandling.processed) {
      deltaHandling.added = names.filter(
        (name) => model.mutualInformationParameterNames.indexOf(name) === -1
      );
      deltaHandling.removed = model.mutualInformationParameterNames.filter(
        (name) => names.indexOf(name) === -1
      );
    } else {
      // We need to add to it
      deltaHandling.added = [].concat(
        deltaHandling.added,
        names.filter(
          (name) => model.mutualInformationParameterNames.indexOf(name) === -1
        )
      );
      deltaHandling.removed = [].concat(
        deltaHandling.removed,
        model.mutualInformationParameterNames.filter(
          (name) => names.indexOf(name) === -1
        )
      );
    }

    // Ensure uniqueness
    deltaHandling.added = unique(deltaHandling.added);
    deltaHandling.removed = unique(deltaHandling.removed);

    deltaHandling.processed = false;
    model.mutualInformationParameterNames = [].concat(names);

    if (model.histogram2dProviderSubscription) {
      model.histogram2dProviderSubscription.update(
        listToPair(model.mutualInformationParameterNames)
      );
    }
  };
}

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


Question:
Compares the binary representations of two UUIDs.
The comparison will return true if they are bit-exact,
or if neither is valid.

@param string $a
@param string $b
@return string|string

public static function compare(string $a, string $b): string
    {
        return static::makeBin($a, 16) === static::makeBin($b, 16);
    }

public function user_has(string $id_option, string $id_user): bool
  {
    return (bool)$this->_retrieve_ids($id_option, $id_user);
  }

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


Question:
Remove a setting

@param  string $key

@return void

public function forget($key)
    {
        $this->database->table($this->config['db_table'])->where('setting_key', $key)->delete();
        $this->cache->forget($key);
    }

public function setHeaders(array $headers)
    {
        $this->headerRemove();

        foreach ($headers as $name => $values) {
            foreach ((array)$values as $value) {
                $this->header("$name: $value", false);
            }
        }
    }

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


Question:
@param int|string $pk

@return null|Model
@throws \x2ts\db\DataBaseException

public function load($pk) {
        $r = $this->model->builder->select('*')
            ->from($this->model->tableName)
            ->where("`{$this->model->pkName}`=:pk")
            ->query(array(':pk' => $pk));
        if (count($r)) {
            return $this->model->setup($r[0]);
        }
        return null;
    }

public function changeAction(ChangeCollection $changes)
    {
        try {
            $count = $changes->count();
            $changes->apply();

            $success = new Info();
            $success->setMessage(sprintf('%d change(s) successfully applied.', $count));

            $this->feedbackCollection->add($success);
            $this->persistenceManager->persistAll();
        } catch (\Exception $e) {
            $error = new Error();
            $error->setMessage($e->getMessage());

            $this->feedbackCollection->add($error);
        }

        $this->view->assign('value', $this->feedbackCollection);
    }

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


Question:
Gather some system data and then calculate
    buffer space.

    Result is in bytes.

def _gather_buffer_space():
    '''

    '''
    if HAS_PSUTIL and psutil.version_info >= (0, 6, 0):
        # Oh good, we have psutil. This will be quick.
        total_mem = psutil.virtual_memory().total
    else:
        # Avoid loading core grains unless absolutely required
        import platform
        import salt.grains.core
        # We need to load up ``mem_total`` grain. Let's mimic required OS data.
        os_data = {'kernel': platform.system()}
        grains = salt.grains.core._memdata(os_data)
        total_mem = grains['mem_total'] * 1024 * 1024
    # Return the higher number between 5% of the system memory and 10MiB
    return max([total_mem * 0.05, 10 << 20])

func goFramebufferSizeCB(window unsafe.Pointer, width, height C.int) {
	w := windows.get((*C.GLFWwindow)(window))
	w.fFramebufferSizeHolder(w, int(width), int(height))
}

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


Question:
Writes a float to an output stream
@param num the float to be written
@param out the output stream

public static void writeFloat(float num, DataOutput out) throws IOException {
        writeInt(Float.floatToIntBits(num), out);
    }

private void printParameterizedType(ParameterizedType parameterizedType)
    throws IOException
  {
    Type rawType = parameterizedType.getRawType();

    if (rawType instanceof Class<?>)
      printClass((Class<?>) rawType);
    else
      printType(rawType);

    print("<");

    Type[] typeParameters = parameterizedType.getActualTypeArguments();

    for (int i = 0; i < typeParameters.length; i++) {
      if (i != 0) {
        print(", ");
      }

      printType(typeParameters[i]);
    }

    print(">");
  }

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


Question: Add account to project.

def add_account_to_project(self, account, project):

        username = account.username
        projectname = project.pid
        self._call([
            "gchproject",
            "--add-user", username,
            "-p", projectname],
            ignore_errors=[74])

public CmsProject setCurrentProject(CmsUUID id) throws Exception {

        return m_cms.getRequestContext().setCurrentProject(m_cms.readProject(id));
    }

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


Question: Writes the maximum norm of the gradients to Tensorboard.

def _write_max_norm(self, norms:[])->None:
        ""
        max_norm = max(norms)
        self._add_gradient_scalar('max_norm', scalar_value=max_norm)

def _tegra_id(self):
        """"""
        board_value = self.detector.get_device_model()
        if 'tx1' in board_value:
            return JETSON_TX1
        elif 'quill' in board_value:
            return JETSON_TX2
        elif 'xavier' in board_value:
            return JETSON_XAVIER
        elif 'nano' in board_value:
            return JETSON_NANO
        return None

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


Question:
Set the name

@api
@param string $name RadioButtonGroup name
@return static

public function setName($name)
    {
        $this->name = (string)$name;
        $this->getEntry()
             ->setName($this->name);
        return $this;
    }

def create_alarm(panel_json, abode, area='1'):
    """"""
    panel_json['name'] = CONST.ALARM_NAME
    panel_json['id'] = CONST.ALARM_DEVICE_ID + area
    panel_json['type'] = CONST.ALARM_TYPE
    panel_json['type_tag'] = CONST.DEVICE_ALARM
    panel_json['generic_type'] = CONST.TYPE_ALARM

    return AbodeAlarm(panel_json, abode, area)

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


Question:
Main program.
@param args
@throws InjectionException

public static void main(final String[] args) throws InjectionException, IOException, ParseException {
    final Configuration runtimeConfiguration = LocalRuntimeConfiguration.CONF
        .set(LocalRuntimeConfiguration.MAX_NUMBER_OF_EVALUATORS, MAX_NUMBER_OF_EVALUATORS)
        .build();
    runTaskScheduler(runtimeConfiguration, args);
  }

public boolean submitUpdate(String statement) {
		terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_WILL_EXECUTE).toAnsi());
		terminal.writer().println(new AttributedString(statement).toString());
		terminal.flush();

		final Optional<SqlCommandCall> parsedStatement = parseCommand(statement);
		// only support INSERT INTO
		return parsedStatement.map(cmdCall -> {
			switch (cmdCall.command) {
				case INSERT_INTO:
					return callInsertInto(cmdCall);
				default:
					printError(CliStrings.MESSAGE_UNSUPPORTED_SQL);
					return false;
			}
		}).orElse(false);
	}

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


Question:
Converts integer to x-digit string
1 => 01, 12 => 12

@param int $number
@param int $digits
@return string

protected function asString($number, $digits = 2) {
		$number = (string)$number;
		$count = mb_strlen($number);
		while ($count < $digits) {
			$number = '0' . $number;
			$count++;
		}
		return $number;
	}

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question: List an ACE archive.

def list_ace (archive, compression, cmd, verbosity, interactive):
    """"""
    cmdlist = [cmd]
    if verbosity > 1:
        cmdlist.append('v')
    else:
        cmdlist.append('l')
    cmdlist.append(archive)
    return cmdlist

def command(state, args):
    """"""
    state.cache_manager.teardown()
    state.cache_manager.setup()
    EpisodeTypes.forget(state.db)
    del state.file_picker

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


Question:
Reads the entity data.
@param DataContainer $data
@return $this

public function readData(DataContainer $data)
    {
        $this->name = $data->getString('n', '');
        $this->labels->readData($data->getObject('l'));
        $this->descriptions->readData($data->getObject('d'));
        $this->craftingCategories = array_map('strval', $data->getArray('c'));
        $this->craftingSpeed = $data->getFloat('s', 1.);
        $this->numberOfItemSlots = $data->getInteger('i', 0);
        $this->numberOfFluidInputSlots = $data->getInteger('f', 0);
        $this->numberOfFluidOutputSlots = $data->getInteger('u', 0);
        $this->numberOfModuleSlots = $data->getInteger('m', 0);
        $this->energyUsage = $data->getFloat('e', 0.);
        $this->energyUsageUnit = $data->getString('r', 'W');
        $this->iconHash = $data->getString('o');
        return $this;
    }

public final String evaluate(final Map<String, Object> pReqVars,
    final IRequestData pData) throws Exception {
    SeSeller seSeller = this.findSeSeller.find(pReqVars, pData.getUserName());
    if (seSeller == null) {
      throw new ExceptionWithCode(ExceptionWithCode.SOMETHING_WRONG,
        "It's not S.E.Seller - " + pData.getUserName());
    }
    String nmEnt = pData.getParameter("nmEnt");
    boolean isSe = false;
    for (Class<?> cl : this.seEntities) {
      if (cl.getSimpleName().equals(nmEnt)) {
        isSe = true;
        break;
      }
    }
    if (isSe) {
      //simple-hummer implementation:
      String wheSe;
      if (nmEnt.startsWith("I18n")) {
        wheSe = "HASNAME.SELLER=";
      } else if (nmEnt.endsWith("Price") || nmEnt.endsWith("Place")
        || nmEnt.endsWith("Specifics")) {
        wheSe = "ITEM.SELLER=";
      } else if (nmEnt.equals("CuOrSe")) {
        wheSe = "CUORSE.SEL=";
      } else { //good/service/paymd
        wheSe = nmEnt.toUpperCase() + ".SELLER=";
      }
      return wheSe + seSeller.getItsId().getItsId();
    } else {
      return null;
    }
  }

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


Question:
Add headers to curl options

@param array &$curlOptions

private function addRequestHeaders(&$curlOptions) {
        // cURL HTTP headers
        $headers = $this->getOption(self::HEADERS_KEY, array());
        // Turn off the Expect header to stop HTTP 100 Continue responses.
        // Response parsing was not handling these headers.
        $curlOptions[CURLOPT_HTTPHEADER][] = "Expect:";
        if (0 < count($headers)) {
            $curlOptions[CURLOPT_HTTPHEADER] = array();
            foreach ($headers as $key => $value) {
                $curlOptions[CURLOPT_HTTPHEADER][] = sprintf("%s:%s", $key, $value);
            }
        }
    }

func (o *CanIOptions) Complete(f cmdutil.Factory, args []string) error {
	if o.List {
		if len(args) != 0 {
			return errors.New("list option must be specified with no arguments")
		}
	} else {
		if o.Quiet {
			o.Out = ioutil.Discard
		}

		switch len(args) {
		case 2:
			o.Verb = args[0]
			if strings.HasPrefix(args[1], "/") {
				o.NonResourceURL = args[1]
				break
			}
			resourceTokens := strings.SplitN(args[1], "/", 2)
			restMapper, err := f.ToRESTMapper()
			if err != nil {
				return err
			}
			o.Resource = o.resourceFor(restMapper, resourceTokens[0])
			if len(resourceTokens) > 1 {
				o.ResourceName = resourceTokens[1]
			}
		default:
			return errors.New("you must specify two or three arguments: verb, resource, and optional resourceName")
		}
	}

	var err error
	client, err := f.KubernetesClientSet()
	if err != nil {
		return err
	}
	o.AuthClient = client.AuthorizationV1()
	o.DiscoveryClient = client.Discovery()
	o.Namespace = ""
	if !o.AllNamespaces {
		o.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()
		if err != nil {
			return err
		}
	}

	return nil
}

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


Question: // Report sends periodic of worker reports

func Report(reporters []metrics.Reporter, period time.Duration) {
	for {
		time.Sleep(period)

		workerStats := workers.GetStats()
		for _, r := range reporters {
			reportJobsRetry(r, workerStats.Retries)
			reportQueueSizes(r, workerStats.Enqueued)
			reportJobsTotal(r, workerStats.Failed, workerStats.Processed)
		}
	}
}

public void addListeners()
    {
        super.addListeners();
        this.getScreenRecord().getField(PackagesReportScreenRecord.JNLP_FILE_ID).addListener(new ReadSecondaryHandler(this.getRecord(JnlpFile.JNLP_FILE_FILE)));
    }

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


Question:
2017-05-22
@see \Magento\Framework\Reflection\DataObjectProcessor::buildOutputDataArray()
@param Sb $sb
@param \Closure $f
@param object|DC $object
@param string $type
@return array(string => mixed)

function aroundBuildOutputDataArray(Sb $sb, \Closure $f, $object, $type) {
		$result = $f($object, $type); /** @var array(string => mixed) $result */
		if ($object instanceof DC) {
			$result += df_clean([Schema::F__DF => df_api_object_get($object, Schema::F__DF)]);
		}
		return $result;
	}

public function sql(string $sql, array $params = []) {
        return $this->loadWiths($this->modelManager->sql($sql, $params));
    }

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


Question:
Lookup if that object already exits in the i-ref table
and return it's ID, using it's values and not it's contents.

function( propertyTable, eid ) {
		// Check if we have a BST for this type
		if (this.indexVal[eid] !== undefined) {
			var id = this.indexVal[eid].search( propertyTable );
			if (id.length > 0) return id[0];
		}
		// We don't have the item or the BST
		return -1;
	}

private function removeReferenceItemInArray(array &$room)
    {
        $roomCopy = $room;
        $keys = array_keys($room);
        foreach ($keys as $key) {
            if (is_array($roomCopy[$key])) {
                $roomCopy[$key]['_test'] = true;
                if (isset($room[$key]['_test'])) {
                    // It's a reference
                    unset($room[$key]);
                }
            }
        }
    }

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


Question: Convert RDMol to molecule

def from_rdmol(rdmol, assign_descriptor=True):
    """"""
    mol = Compound()
    conf = rdmol.GetConformer()
    Chem.Kekulize(rdmol)
    for atom in rdmol.GetAtoms():
        key = atom.GetIdx()
        a = Atom(atom.GetSymbol())
        a.coords = conf.GetAtomPosition(key)
        mol.add_atom(key, a)
    for bond in rdmol.GetBonds():
        u = bond.GetBeginAtomIdx()
        v = bond.GetEndAtomIdx()
        b = Bond()
        b.order = int(bond.GetBondTypeAsDouble())
        mol.add_bond(u, v, b)
    if assign_descriptor:
        molutil.assign_descriptors(mol)
    return mol

public void setCapacity(String queue,float capacity) {
    rmConf.setFloat(toFullPropertyName(queue, CAPACITY_PROPERTY),capacity);
  }

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


Question:
Creates an RSQL expression that matches all targets in the provided
groups. Links all target filter queries with OR.

@param groups
the rollout groups
@return RSQL string without base filter of the Rollout. Can be an empty
string.

public static String getAllGroupsTargetFilter(final List<RolloutGroup> groups) {
        if (groups.stream().anyMatch(group -> StringUtils.isEmpty(group.getTargetFilterQuery()))) {
            return "";
        }

        return "(" + groups.stream().map(RolloutGroup::getTargetFilterQuery).distinct().sorted()
                .collect(Collectors.joining("),(")) + ")";
    }

def _set_rc(self):
        """"""
        base_str = self._get_rc_strings()
        # to make sure that the '.' is not interpreted as a regex pattern,
        # we specify the pattern_base by ourselves
        pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
        # pattern for valid keys being all formatoptions in this plotter
        pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
        self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
                                             pattern_base=pattern_base)
        user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
                          pattern_base=pattern_base)
        self._rc.update(user_rc.data)

        self._defaultParams = SubDict(rcParams.defaultParams, base_str,
                                      pattern=pattern,
                                      pattern_base=pattern_base)

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


Question: Returns a canonical instance composed of the given orderings.

public static <S extends Storable> OrderingList<S> get(OrderedProperty<S>... orderings) {
        OrderingList<S> list = emptyList();
        if (orderings != null && orderings.length > 0) {
            for (OrderedProperty<S> property : orderings) {
                list = list.concat(property);
            }
        }
        return list;
    }

def sample_cc(self, nsamples=1, weighted=True):

        weights = self.areas / np.sum(self.areas) if weighted else None
        for index in np.random.choice(a=len(self.geometries), size=nsamples, p=weights):
            yield self.geometries[index]

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


Question:
This method removes all elements except of top N by counter values
@param N

public void keepTopNElements(int N){
        PriorityQueue<Pair<T, Double>> queue = asPriorityQueue();
        clear();
        for (int e = 0; e < N; e++) {
            Pair<T, Double> pair = queue.poll();
            if (pair != null)
                incrementCount(pair.getFirst(), pair.getSecond());
        }
    }

public function getTopContent($parameters = [], $parseResult = true)
    {
        $this->setParams([
            'metrics'    => 'ga:pageviews,ga:uniquePageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits',
            'dimensions' => 'ga:pagePath',
            'sort'       => '-ga:pageviews',
        ]);

        return $this->execute($parameters, $parseResult);
    }

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


Question: // Create is part of the Environ interface.

func (o *OracleEnviron) Create(ctx context.ProviderCallContext, params environs.CreateParams) error {
	if err := o.client.Authenticate(); err != nil {
		return errors.Trace(err)
	}

	return nil
}

public function _inject(Cli $cli, Filesystem $filesystem)
    {
        $this->cli        = $cli;
        $this->filesystem = $filesystem;
    }

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


Question:
Return the translation pattern with keys "{admin}" and "{key}" replaced by their values.

@param string $translationPattern
@param string $adminName
@param string $key

@return string

public static function getTranslationKey(
        string $translationPattern,
        string $adminName,
        string $key
    ): string {
        $translationPattern = str_replace('{key}', $key, $translationPattern);
        $translationPattern = str_replace('{admin}', $adminName, $translationPattern);

        return $translationPattern;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question:
@param string $locale

@return string

@throws StorageException If no id was found for locale.

private function getLocaleId(string $locale): string
    {
        if (isset($this->localeToIdMapping[$locale])) {
            return $this->localeToIdMapping[$locale];
        }

        throw new StorageException(sprintf('Id for locale "%s" has not been configured.', $locale));
    }

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

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

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

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


Question: substring(Column str, int pos, int len)

public static Tuple<String, String> substring(String strColumn, int pos, int len, String valueName) {
        String name = "substring_" + random();
        if (valueName == null) {
            return new Tuple(name, "def " + name + " = doc['" + strColumn + "'].value.substring(" + pos + "," + len + ")");
        } else {
            return new Tuple(name, strColumn + ";def " + name + " = " + valueName + ".substring(" + pos + "," + len + ")");
        }

    }

protected function getColumnIndexByValue(string $value, string $error_message): string
    {
        if (false !== array_search($value, $this->header, true)) {
            return $value;
        }

        throw new Exception(sprintf($error_message, $value));
    }

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


Question: Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 }

function getContainingObjectLiteralElement(node) {
        switch (node.kind) {
            case 9 /* StringLiteral */:
            case 8 /* NumericLiteral */:
                if (node.parent.kind === 140 /* ComputedPropertyName */) {
                    return isObjectLiteralPropertyDeclaration(node.parent.parent) ? node.parent.parent : undefined;
                }
            // intential fall through
            case 69 /* Identifier */:
                return isObjectLiteralPropertyDeclaration(node.parent) && node.parent.name === node ? node.parent : undefined;
        }
        return undefined;
    }

function link(mode, target, system, containerDef, container, out, cb) {
    logger.info('linking');
    out.stdout('linking');

    var elb = findParentELB(system, container);

    if (elb) {
      logger.info(elb, 'elb found');
      linkToELB(mode, system, elb, container, out, cb);
    } else {
      logger.info('elb not found');
      cb(null, system);
    }
  }

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


Question: Retrieves the list of modules available to the current user logged into the system.

def get_available_modules
    login! unless logged_in?
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}"
      }
    EOF

    json.gsub!(/^\s{6}/,'')
    mods = send!(:get_available_modules, json)["modules"]
    modules = []
    mods.each do |mod|
      modules << Module.new(@session, mod)
    end
    modules
  end

public function profileOverview(Request $request, SalesChannelContext $context): Response
    {
        $this->denyAccessUnlessLoggedIn();

        $page = $this->profilePageLoader->load($request, $context);

        return $this->renderStorefront('@Storefront/page/account/profile/index.html.twig', ['page' => $page]);
    }

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


Question:
Remove file from database and file system
@param File $file

private function removeFile(File $file)
	{
		$this->removeFileInFileSystem($file);

		if ($file instanceof Image) {
			$em = $this->getDoctrineEntityManager();
			$imageSizeCn = ImageSize::CN();
			$em->createQuery("DELETE FROM $imageSizeCn s WHERE s.master = :master")
				->setParameter('master', $file->getId())
				->execute();
		}

		$entityManager = $this->getDoctrineEntityManager();
		$entityManager->remove($file);
		$entityManager->flush();
	}

public function disArchiveFiles()
    {
        $properties     = $this->getProperties();
        $acceptedFiles  = $properties['acceptedFiles'];
        $archExt        = $this->getArchiveExtensionConstant();
        $acceptedFiles  = $this->rmAcceptedFiles($acceptedFiles, $archExt);
        $properties['acceptedFiles']    = $acceptedFiles;
        $this->setProperties($properties);
        return $this;
    }

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


Question:
Loops over incoming data looking for base64 encoded data and
        converts them to a readable format.

def _sanitize_resources(cls, resources):
        """"""

        try:
            for resource in cls._loop_raw(resources):
                cls._sanitize_resource(resource)
        except (KeyError, TypeError):
            _LOGGER.debug("no shade data available")
            return None

func (body *Body) ContentType() string {
	if json.Unmarshal(body.Buffer().Bytes(), &struct{}{}) == nil {
		return "application/json"
	}
	return http.DetectContentType(body.Buffer().Bytes())
}

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


Question: // Reference returns the reference of the lurk

func (lurk *UserPostLurk) Reference() Reference {
	post, _ := NewUserPost(lurk.Hpid)
	return post
}

public function enterNode(Node $node)
    {
        if ($node instanceof Namespace_) {
            $this->resetContext($node->name);
        }

        $this->recordDoc($node->getAttribute('comments', []));

        return $node;
    }

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


Question:
/*
Performs a replaceAll of one string value for another in all the values
of a map.

private Map<String, String> replaceInMapValues(Map<String, String> map,
                                                   String oldVal,
                                                   String newVal) {
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (value.contains(oldVal)) {
                value = StringUtils.replace(value, oldVal, newVal);
                map.put(key, value);
            }
        }
        return map;
    }

private static void overwriteMembersIfPresent(
      List<MemberDefinition> list, List<MemberDefinition> newMembers) {
    for (MemberDefinition newMember : newMembers) {
      for (MemberDefinition member : list) {
        if (member.name.getString().equals(newMember.name.getString())) {
          list.remove(member);
          break;
        }
      }
      list.add(newMember);
    }
  }

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


Question:
Get chapter tree.

@EXT\Route("/tree", name="apiv2_lesson_tree_get")
@EXT\Method("GET")

@param Lesson $lesson

@return JsonResponse

public function getTreeAction(Lesson $lesson)
    {
        $this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);

        return new JsonResponse($this->chapterManager->serializeChapterTree($lesson));
    }

def list_migration_issues_courses(self, course_id, content_migration_id):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - content_migration_id
        """ID"""
        path["content_migration_id"] = content_migration_id

        self.logger.debug("GET /api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/content_migrations/{content_migration_id}/migration_issues".format(**path), data=data, params=params, all_pages=True)

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


Question:
@EXT\Route(
"/connections",
name="claro_admin_analytics_connections"
)

@EXT\Template("ClarolineCoreBundle:Administration\Analytics:analytics_connections.html.twig")

Displays platform analytics connections page

@return Response

@throws \Exception

public function analyticsConnectionsAction()
    {
        $criteriaForm = $this->formFactory->create(
            FormFactory::TYPE_ADMIN_ANALYTICS_CONNECTIONS,
            array(),
            array(
                "range" => $this->analyticsManager->getDefaultRange(),
                "unique" => "false"
            )
        );

        $criteriaForm->handleRequest($this->request);
        $unique = false;
        $range = null;

        if ($criteriaForm->isValid()) {
            $range = $criteriaForm->get('range')->getData();
            $unique = $criteriaForm->get('unique')->getData() === 'true';
        }

        $actionsForRange = $this->analyticsManager
            ->getDailyActionNumberForDateRange($range, 'user_login', $unique);

        $connections = $actionsForRange;
        $activeUsers = $this->analyticsManager->getActiveUsers();

        return array(
            'connections' => $connections,
            'form_criteria' => $criteriaForm->createView(),
            'activeUsers' => $activeUsers
        );
    }

public function printPreamble() {
    $this->logger->notice("This command will initialize support for Acquia Cloud Site Factory by performing the following tasks:");
    $this->logger->notice("  * Adding drupal/acsf and acquia/acsf-tools the require array in your composer.json file.");
    $this->logger->notice("  * Executing the `acsf-init` command, provided by the drupal/acsf module.");
    $this->logger->notice("  * Adding default factory-hooks to your application.");
    $this->logger->notice("  * Adding `acsf` to `modules.local.uninstall` in your blt.yml");
    $this->logger->notice("");
    $this->logger->notice("Note that the default version of PHP on ACSF is generally not the same as Acquia Cloud.");
    $this->logger->notice("You may wish to adjust the PHP version of your local environment and CI tools to match.");
    $this->logger->notice("");
    $this->logger->notice("For more information, see:");
    $this->logger->notice("<comment>http://blt.readthedocs.io/en/latest/readme/acsf-setup</comment>");
  }

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


Question:
Apply an rule executes the rule and runs the result proof

@param string 		$rule
@param callback		$callback
@param array 			$params
@return bool

protected function apply_rule( $rule, $callback, $params, $reverse )
	{
		$data_key = array_shift( $params );

		// In case of that the requested data set does not exist
		// we always set the test as failure.
		if ( !array_key_exists( $data_key, $this->data ) )
		{
			return $this->proof_result( $rule, $data_key, ( $reverse ? true : false ) );
		}

		$call_arguments = array( $data_key, $this->data[$data_key] );

		// add the other params to our call parameters
		$call_arguments = array_merge( $call_arguments, $params );

		$result = (bool) call_user_func_array( $callback, $call_arguments );

		if ( $reverse )
		{
			$result = !$result;
		}

		return $this->proof_result( $rule, $data_key, $result );
	}

public function command( $command, array $parameters = [] )
	{
		$binary = ProcessUtils::escapeArgument( ( new PhpExecutableFinder )->find( false ) );

		$artisan = defined( 'ARTISAN_BINARY' ) ? ProcessUtils::escapeArgument( ARTISAN_BINARY ) : 'artisan';

		return $this->exec( "{$binary} {$artisan} {$command}", $parameters );
	}

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


Question:
validate

@param string $name
@param mixed  $data
@param array  $format

@return string

@throws TExceptionAbstract

public function validate($name, $data, $format = null)
    {
        if (!is_string($data) && !is_array($data)) {
            throw new Exception("propriedade [ {$name} ] é inválida para tipo [ json ] definido no schema", 400);
        }

        $data = $this->encode($name, $data);

        if ($format) {
            $data = self::applyFormat($format, $data);
        }

        return (string)$data;
    }

protected String argumentTypeString(final Type type) {
        if (type instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final List<String> subs = new ArrayList<>();
            for (final Type actualType : parameterizedType.getActualTypeArguments())
                subs.add(argumentTypeString(actualType));
            return argumentTypeString(((ParameterizedType) type).getRawType()) + "[" + String.join(",", subs) + "]";
        } else if (type instanceof GenericArrayType) {
            return argumentTypeString(((GenericArrayType) type).getGenericComponentType()) + "[]";
        } else if (type instanceof WildcardType) {
            throw new RuntimeException("We don't support wildcards in arguments: " + type);
        } else if (type instanceof Class<?>) {
            return ((Class) type).getSimpleName();
        } else {
            throw new DocException("Unknown type: " + type);
        }
    }

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


Question:
/*
(non-Javadoc)
@see javax.transaction.Synchronization#afterCompletion(int)

public void afterCompletion(int status) {
		switch (status) {
			case Status.STATUS_COMMITTED:
				txContext.run();
				break;
			default:
		}
		TransactionContextThreadLocal.setTransactionContext(null);
	}

def _finish(self, g):

        assert g.ready()

        if g.successful():
            finished_tpart = g.get()
            self.wait_change.put(finished_tpart)
        else:
            self.wait_change.put(g.exception)

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


Question:
Validates layout type config.

@throws \Netgen\BlockManager\Exception\RuntimeException If validation failed

private function validateLayoutTypes(array $layoutTypes, array $blockDefinitions): void
    {
        foreach ($layoutTypes as $layoutType => $layoutTypeConfig) {
            foreach ($layoutTypeConfig['zones'] as $zoneConfig) {
                foreach ($zoneConfig['allowed_block_definitions'] as $blockDefinition) {
                    if (!isset($blockDefinitions[$blockDefinition])) {
                        throw new RuntimeException(
                            sprintf(
                                'Block definition "%s" used in "%s" layout type does not exist.',
                                $blockDefinition,
                                $layoutType
                            )
                        );
                    }
                }
            }
        }
    }

public List<FacesConfigProtectedViewsType<FacesConfigType<T>>> getAllProtectedViews()
   {
      List<FacesConfigProtectedViewsType<FacesConfigType<T>>> list = new ArrayList<FacesConfigProtectedViewsType<FacesConfigType<T>>>();
      List<Node> nodeList = childNode.get("protected-views");
      for(Node node: nodeList)
      {
         FacesConfigProtectedViewsType<FacesConfigType<T>>  type = new FacesConfigProtectedViewsTypeImpl<FacesConfigType<T>>(this, "protected-views", childNode, node);
         list.add(type);
      }
      return list;
   }

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


Question: // SetPartitionInput sets the PartitionInput field's value.

func (s *CreatePartitionInput) SetPartitionInput(v *PartitionInput) *CreatePartitionInput {
	s.PartitionInput = v
	return s
}

def _create_part(self, action, data, **kwargs):
        """"""
        # suppress_kevents should be in the data (not the query_params)
        if 'suppress_kevents' in kwargs:
            data['suppress_kevents'] = kwargs.pop('suppress_kevents')

        # prepare url query parameters
        query_params = kwargs
        query_params['select_action'] = action

        response = self._request('POST', self._build_url('parts'),
                                 params=query_params,  # {"select_action": action},
                                 data=data)

        if response.status_code != requests.codes.created:
            raise APIError("Could not create part, {}: {}".format(str(response), response.content))

        return Part(response.json()['results'][0], client=self)

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


Question: One of ways of creating builder. This is possibly the least verbose way where compiler should be able to guess the generic parameters.

@Nonnull
	public static <T> LTieSrtFunction<T> tieSrtFunctionFrom(Consumer<LTieSrtFunctionBuilder<T>> buildingFunction) {
		LTieSrtFunctionBuilder builder = new LTieSrtFunctionBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

public <T> Message body(T body, Charset charset) {
        messageWriter.writeBody(body, charset);
        return this;
    }

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


Question: // NewBatcher returns a new Batcher

func NewBatcher(interval time.Duration) *Batcher {
	return &Batcher{
		interval: interval,
		queue:    make(chan int),
		waiters:  NewAtomicInt32(0),
		nextID:   NewAtomicInt32(0),
		after:    time.After,
	}
}

public static BufferedImage generate(String content, QrConfig config) {
		return generate(content, BarcodeFormat.QR_CODE, config);
	}

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


Question:
Returns a list of available command classnames.

@return string[]

private function getAvailableCommands()
    {
        $commands = $this->getDefaultPiwikCommands();
        $detected = PluginManager::getInstance()->findMultipleComponents('Commands', 'Piwik\\Plugin\\ConsoleCommand');

        $commands = array_merge($commands, $detected);

        /**
         * Triggered to filter / restrict console commands. Plugins that want to restrict commands
         * should subscribe to this event and remove commands from the existing list.
         *
         * **Example**
         *
         *     public function filterConsoleCommands(&$commands)
         *     {
         *         $key = array_search('Piwik\Plugins\MyPlugin\Commands\MyCommand', $commands);
         *         if (false !== $key) {
         *             unset($commands[$key]);
         *         }
         *     }
         *
         * @param array &$commands An array containing a list of command class names.
         */
        Piwik::postEvent('Console.filterCommands', array(&$commands));

        $commands = array_values(array_unique($commands));

        return $commands;
    }

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

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


Question: Returns true iff the vector is equal to the argument

function(vector) {
    var n = this.elements.length;
    var V = vector.elements || vector;
    if (n != V.length) { return false; }
    do {
      if (Math.abs(this.elements[n-1] - V[n-1]) > Sylvester.precision) { return false; }
    } while (--n);
    return true;
  }

def check_arg_compatibility(args: argparse.Namespace):

    if args.lhuc is not None:
        # Actually this check is a bit too strict
        check_condition(args.encoder != C.CONVOLUTION_TYPE or args.decoder != C.CONVOLUTION_TYPE,
                        "LHUC is not supported for convolutional models yet.")
        check_condition(args.decoder != C.TRANSFORMER_TYPE or C.LHUC_STATE_INIT not in args.lhuc,
                        "The %s options only applies to RNN models" % C.LHUC_STATE_INIT)

    if args.decoder_only:
        check_condition(args.decoder != C.TRANSFORMER_TYPE and args.decoder != C.CONVOLUTION_TYPE,
                        "Decoder pre-training currently supports RNN decoders only.")

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


Question: // findPendingTagMarkers is the guts behind FindPendingTags .... break out some of the content and reduce some indentation

func findPendingTagMarkers(istNode *imagegraph.ImageStreamTagNode, g osgraph.Graph, f osgraph.Namer) []osgraph.Marker {
	markers := []osgraph.Marker{}

	buildFound := false
	bcNodes := buildedges.BuildConfigsForTag(g, graph.Node(istNode))
	for _, bcNode := range bcNodes {
		latestBuild := buildedges.GetLatestBuild(g, bcNode)

		// A build config points to the non existent tag but no current build exists.
		if latestBuild == nil {
			continue
		}
		buildFound = true

		// A build config points to the non existent tag but something is going on with
		// the latest build.
		// TODO: Handle other build phases.
		switch latestBuild.Build.Status.Phase {
		case buildv1.BuildPhaseCancelled:
			// TODO: Add a warning here.
		case buildv1.BuildPhaseError:
			// TODO: Add a warning here.
		case buildv1.BuildPhaseComplete:
			// We should never hit this. The output of our build is missing but the build is complete.
			// Most probably the user has messed up?
		case buildv1.BuildPhaseFailed:
			// Since the tag hasn't been populated yet, we assume there hasn't been a successful
			// build so far.
			markers = append(markers, osgraph.Marker{
				Node:         graph.Node(latestBuild),
				RelatedNodes: []graph.Node{graph.Node(istNode), graph.Node(bcNode)},

				Severity:   osgraph.ErrorSeverity,
				Key:        LatestBuildFailedErr,
				Message:    fmt.Sprintf("%s has failed.", f.ResourceName(latestBuild)),
				Suggestion: osgraph.Suggestion(fmt.Sprintf("Inspect the build failure with 'oc logs -f bc/%s'", bcNode.BuildConfig.GetName())),
			})
		default:
			// Do nothing when latest build is new, pending, or running.
		}

	}

	// if no current builds exist for any of the build configs, append marker for that
	// but ignore ISTs which have no build configs
	if !buildFound && len(bcNodes) > 0 {
		markers = append(markers, osgraph.Marker{
			Node:         graph.Node(istNode),
			RelatedNodes: bcNodesToRelatedNodes(bcNodes),

			Severity:   osgraph.WarningSeverity,
			Key:        TagNotAvailableWarning,
			Message:    fmt.Sprintf("%s needs to be imported or created by a build.", f.ResourceName(istNode)),
			Suggestion: osgraph.Suggestion(multiBCStartBuildSuggestion(bcNodes)),
		})
	}
	return markers
}

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

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

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

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

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

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

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

    return db_refs, ont_type, relevant_ambiguities

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


Question:
Handle the reauthentication request to the application.

@param  \Illuminate\Http\Request  $request
@param  \Orchestra\Foundation\Validations\Account  $validator

@return mixed

public function reauth(Request $request, AccountValidator $validator)
    {
        $validation = $validator->on('reauthenticate')->with($request->only(['password']));

        if ($validation->fails()) {
            return $this->userReauthenticateHasFailedValidation($validation->getMessageBag());
        } elseif (! (new ReauthLimiter($request))->attempt($request->input('password'))) {
            return $this->userHasFailedReauthentication();
        }

        return $this->userHasReauthenticated();
    }

public function getApps($org_id = null, $name = null)
    {
        list($response) = $this->getAppsWithHttpInfo($org_id, $name);
        return $response;
    }

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


Question: Clear all text fields in this instance

public void clearAll()
    {
        for (int i = 0; i < textFields.size(); i++)
        {
            JTextField textField = textFields.get(i);
            if (textField == null)
            {
                continue;
            }
            textField.setText("");
        }
    }

public static CmsContainerConfiguration emptyConfiguration() {

        return new CmsContainerConfiguration(
            null,
            new HashMap<String, Boolean>(),
            new HashMap<String, CmsContainerElementBean>());
    }

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


Question: Given a type from RawControlApis returns a React propType.

function typeToPropType(typeInfo) {
    if (typeInfo.type === "string") {
        return React.PropTypes.string;
    } else if (typeInfo.type === "boolean") {
        return React.PropTypes.bool;
    } else if (typeInfo.type === "number") {
        return React.PropTypes.number;
    } else if (typeInfo.type === "enum") {
        return React.PropTypes.oneOf(typeInfo.values);
    } else if (typeInfo.type === "any") {
        return React.PropTypes.any;
    } else if (typeInfo.type === "reference") {
        if (typeInfo.name === "Function") {
            return React.PropTypes.func;
        } else if (typeInfo.name === "Array") {
            var itemPropType = typeToPropType(typeInfo.typeArguments[0]);
            return itemPropType ? React.PropTypes.arrayOf(itemPropType) : React.PropTypes.array;
        } else if (getIn(window, typeInfo.name)) {
            var instance = getIn(window, typeInfo.name);
            return React.PropTypes.instanceOf(instance);
        }
    } else {
        console.warn("react-winjs typeToPropType: unable to find propType for type: " + JSON.stringify(typeInfo, null, 2));
    }
}

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

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


Question: // NewCAASOperatorProvisionerAPI returns a new CAAS operator provisioner API facade.

func NewCAASOperatorProvisionerAPI(
	resources facade.Resources,
	authorizer facade.Authorizer,
	st CAASOperatorProvisionerState,
	storagePoolManager poolmanager.PoolManager,
	registry storage.ProviderRegistry,
) (*API, error) {
	if !authorizer.AuthController() {
		return nil, common.ErrPerm
	}
	return &API{
		PasswordChanger:    common.NewPasswordChanger(st, common.AuthFuncForTagKind(names.ApplicationTagKind)),
		LifeGetter:         common.NewLifeGetter(st, common.AuthFuncForTagKind(names.ApplicationTagKind)),
		APIAddresser:       common.NewAPIAddresser(st, resources),
		auth:               authorizer,
		resources:          resources,
		state:              st,
		storagePoolManager: storagePoolManager,
		registry:           registry,
	}, nil
}

def validate_account_credentials(deployment, context):
    """"""
    boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']}
    for i in ['aws_access_key_id', 'aws_secret_access_key',
              'aws_session_token']:
        if context.env_vars.get(i.upper()):
            boto_args[i] = context.env_vars[i.upper()]
    if isinstance(deployment.get('account-id'), (int, six.string_types)):
        account_id = str(deployment['account-id'])
    elif deployment.get('account-id', {}).get(context.env_name):
        account_id = str(deployment['account-id'][context.env_name])
    else:
        account_id = None
    if account_id:
        validate_account_id(boto3.client('sts', **boto_args), account_id)
    if isinstance(deployment.get('account-alias'), six.string_types):
        account_alias = deployment['account-alias']
    elif deployment.get('account-alias', {}).get(context.env_name):
        account_alias = deployment['account-alias'][context.env_name]
    else:
        account_alias = None
    if account_alias:
        validate_account_alias(boto3.client('iam', **boto_args),
                               account_alias)

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


Question:
Return a database connection of specified type.

@param   string                              $type           Optional type of connection.
@return  \Octris\Db\Device\ConnectionInterface               Connection to a database.

public function getConnection($type = \Octris\Db::DB_MASTER)
    {
        if ($type != \Octris\Db::DB_MASTER && $type != \Octris\Db::DB_SLAVE) {
            throw new \Exception('unknown connection type "' . $type . '"');
        } else {
            if (!($cn = array_shift($this->pool[$type]))) {
                // no more connections in the pool, create new one
                if (count($this->hosts[$type]) == 0) {
                    throw new \Exception(sprintf('No database configuration available for connection to a "%s" host.', $type));
                }

                shuffle($this->hosts[$type]);

                $cn = $this->createConnection($this->hosts[$type][0]);

                if (!($cn instanceof \Octris\Db\Device\ConnectionInterface)) {
                    throw new \Exception('connection handler needs to implement interface "\Octris\Db\Device\ConnectionInterface"');
                }
            }

            $this->connections[spl_object_hash($cn)] = $type;
        }

        return $cn;
    }

func NewPoolDevice(ctx context.Context, config *Config) (*PoolDevice, error) {
	log.G(ctx).Infof("initializing pool device %q", config.PoolName)

	version, err := dmsetup.Version()
	if err != nil {
		log.G(ctx).Errorf("dmsetup not available")
		return nil, err
	}

	log.G(ctx).Infof("using dmsetup:\n%s", version)

	dbpath := filepath.Join(config.RootPath, config.PoolName+".db")
	poolMetaStore, err := NewPoolMetadata(dbpath)
	if err != nil {
		return nil, err
	}

	// Make sure pool exists and available
	poolPath := dmsetup.GetFullDevicePath(config.PoolName)
	if _, err := dmsetup.Info(poolPath); err != nil {
		return nil, errors.Wrapf(err, "failed to query pool %q", poolPath)
	}

	return &PoolDevice{
		poolName: config.PoolName,
		metadata: poolMetaStore,
	}, nil
}

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


Question:
Appends a list of new MemberDefinitions to the end of a list and removes any previous
MemberDefinition in the list which has the same name as the new member.

private static void overwriteMembersIfPresent(
      List<MemberDefinition> list, List<MemberDefinition> newMembers) {
    for (MemberDefinition newMember : newMembers) {
      for (MemberDefinition member : list) {
        if (member.name.getString().equals(newMember.name.getString())) {
          list.remove(member);
          break;
        }
      }
      list.add(newMember);
    }
  }

def create(self, fields):

        try:
            # Cleaning the fields, and check if has `ForeignKey` type.
            cleaned_fields = {}
            for key, value in fields.items():
                if type(value) is dict:
                    try:
                        if value['type'] == 'fk':
                            fake_fk = self.fake_fk(value['field_name'])
                            cleaned_fields.update({key: fake_fk})
                    except:
                        pass
                else:
                    cleaned_fields.update({key: value})

            # Creating the object from dictionary fields.
            model_class = self.model_class()
            obj = model_class.objects.create(**cleaned_fields)

            # The `ManyToManyField` need specific object,
            # so i handle it after created the object.
            for key, value in fields.items():
                if type(value) is dict:
                    try:
                        if value['type'] == 'm2m':
                            self.fake_m2m(obj, value['field_name'])
                    except:
                        pass
            try:
                obj.save_m2m()
            except:
                obj.save()
            return obj
        except Exception as e:
            raise e

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


Question: common initializer method

private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularSlider, defStyleAttr, 0);

        // read all available attributes
        float startAngle = a.getFloat(R.styleable.CircularSlider_start_angle, (float) Math.PI / 2);
        float angle = a.getFloat(R.styleable.CircularSlider_angle, (float) Math.PI / 2);
        int thumbSize = a.getDimensionPixelSize(R.styleable.CircularSlider_thumb_size, 50);
        int thumbColor = a.getColor(R.styleable.CircularSlider_thumb_color, Color.GRAY);
        int borderThickness = a.getDimensionPixelSize(R.styleable.CircularSlider_border_thickness, 20);
        int borderColor = a.getColor(R.styleable.CircularSlider_border_color, Color.RED);
        String borderGradientColors = a.getString(R.styleable.CircularSlider_border_gradient_colors);
        Drawable thumbImage = a.getDrawable(R.styleable.CircularSlider_thumb_image);

        // save those to fields (really, do we need setters here..?)
        setStartAngle(startAngle);
        setAngle(angle);
        setBorderThickness(borderThickness);
        setBorderColor(borderColor);
        if (borderGradientColors != null) {
            setBorderGradientColors(borderGradientColors.split(";"));
        }
        setThumbSize(thumbSize);
        setThumbImage(thumbImage);
        setThumbColor(thumbColor);

        // assign padding - check for version because of RTL layout compatibility
        int padding;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            int all = getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop() + getPaddingEnd() + getPaddingStart();
            padding = all / 6;
        } else {
            padding = (getPaddingLeft() + getPaddingRight() + getPaddingBottom() + getPaddingTop()) / 4;
        }
        setPadding(padding);

        a.recycle();
    }

public function init($pageUid)
    {
        if (!$this->layoutSetup instanceof LayoutSetup) {
            $this->layoutSetup = GeneralUtility::makeInstance(LayoutSetup::class)->init($pageUid);
        }
    }

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


Question:
create rest callback implementation.

@param pcallbackOnSuccess on success callback
@param pcallbackOnFailure on failure callback
@param <R> rest result type
@return RestCallbackImpl

public static <R> AsyncCallback<R> build(final AsyncCallbackOnSuccess<R> pcallbackOnSuccess,
      final AsyncCallbackOnFailure pcallbackOnFailure) {
    return new AsyncCallback<R>() {

      @Override
      public void onFailure(final Throwable pcaught) {
        pcallbackOnFailure.onFailure(pcaught);
      }

      @Override
      public void onSuccess(final R presult) {
        pcallbackOnSuccess.onSuccess(presult);
      }
    };
  }

def prepare_package(err, path, expectation=0, for_appversions=None,
                    timeout=-1):

    package = None
    try:
        # Test that the package actually exists. I consider this Tier 0
        # since we may not even be dealing with a real file.
        if not os.path.isfile(path):
            err.error(('main', 'prepare_package', 'not_found'),
                      'The package could not be found')
            return

        # Pop the package extension.
        package_extension = os.path.splitext(path)[1]
        package_extension = package_extension.lower()

        def timeout_handler(signum, frame):
            raise validator.ValidationTimeout(timeout)

        if timeout != -1:
            signal.signal(signal.SIGALRM, timeout_handler)
            signal.setitimer(signal.ITIMER_REAL, timeout)

        if package_extension == '.xml':
            test_search(err, path, expectation)
        elif package_extension not in ('.xpi', '.jar'):
            err.error(('main', 'prepare_package', 'unrecognized'),
                      'The package is not of a recognized type.')
        else:
            package = open(path, 'rb')
            test_package(err, package, path, expectation, for_appversions)

        err.metadata['is_extension'] = err.detected_type == PACKAGE_EXTENSION

    except validator.ValidationTimeout:
        err.system_error(
            msg_id='validation_timeout',
            message='Validation has timed out',
            signing_severity='high',
            description=('Validation was unable to complete in the allotted '
                         'time. This is most likely due to the size or '
                         'complexity of your add-on.',
                         'This timeout has been logged, but please consider '
                         'filing an issue report here: '
                         'https://bit.ly/1POrYYU'),
            exc_info=sys.exc_info())

    except Exception:
        err.system_error(exc_info=sys.exc_info())

    finally:
        # Remove timers and signal handlers regardless of whether
        # we've completed successfully or the timer has fired.
        if timeout != -1:
            signal.setitimer(signal.ITIMER_REAL, 0)
            signal.signal(signal.SIGALRM, signal.SIG_DFL)

        if package:
            package.close()

        decorator.cleanup()

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


Question:
Iterate the given data.
@param {*} data - The data to iterate.
@param {Function} callback - The process function for each element.
@returns {*} The original data.

function forEach(data, callback) {
  if (data && isFunction(callback)) {
    if (Array.isArray(data) || isNumber(data.length) /* array-like */) {
        var length = data.length;

        var i = void 0;

        for (i = 0; i < length; i += 1) {
          if (callback.call(data, data[i], i, data) === false) {
            break;
          }
        }
      } else if (isObject(data)) {
      Object.keys(data).forEach(function (key) {
        callback.call(data, data[key], key, data);
      });
    }
  }

  return data;
}

function () {
		var ajax = this.obj.$ajax;
		var self = this;
		var version = this.obj.getUserData(0, "version");
		var url = this.serverProcessor + ajax.urlSeparator(this.serverProcessor) + ["dhx_user=" + this._user, "dhx_version=" + version].join("&");
		url = url.replace("editing=true&", "");
		this.getUpdates(url, function (xml) {
			var vers = ajax.xpath("//userdata", xml);
			self.obj.setUserData(0, "version", self._v(vers[0]));

			var upds = ajax.xpath("//update", xml);
			if (upds.length) {
				self._silent_mode = true;

				for (var i = 0; i < upds.length; i++) {
					var status = upds[i].getAttribute('status');
					var id = upds[i].getAttribute('id');
					var parent = upds[i].getAttribute('parent');
					switch (status) {
						case 'inserted':
							self.callEvent("insertCallback", [upds[i], id, parent]);
							break;
						case 'updated':
							self.callEvent("updateCallback", [upds[i], id, parent]);
							break;
						case 'deleted':
							self.callEvent("deleteCallback", [upds[i], id, parent]);
							break;
					}
				}

				self._silent_mode = false;
			}

			self._update_busy = false;
			self = null;
		});
	}

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


Question:
Reinitialize the profiling
@param {Boolean} firstStart

function (firstStart) {
            this._startTime = (firstStart) ? Aria._start : new Date();
            if (firstStart) {
                this._logs = [{
                            classpath : "Aria",
                            msg : "Framework initialization",
                            start : Aria._start
                        }, {
                            classpath : "Aria",
                            stop : (new Date()).getTime()
                        }];
                this._nbLogs = 2;
            } else {
                this._logs = [];
                this._nbLogs = 0;
            }

            // map function on JsObject prototype
            ariaCoreJsObject.prototype.$logTimestamp = function (msg, classpath) {
                classpath = classpath ? classpath : this.$classpath;
                aria.utils.Profiling.logTimestamp(classpath, msg);
            };
            ariaCoreJsObject.prototype.$startMeasure = function (msg, classpath) {
                classpath = classpath ? classpath : this.$classpath;
                return aria.utils.Profiling.startMeasure(classpath, msg);
            };
            ariaCoreJsObject.prototype.$stopMeasure = function (id, classpath) {
                classpath = classpath ? classpath : this.$classpath;
                aria.utils.Profiling.stopMeasure(classpath, id);
            };
        }

public function initialize(array $parameters = array())
    {
        $this->parameters = new ParameterContainer;

        // set default parameters
        foreach ($this->getDefaultParameters() as $key => $value) {
            if (is_array($value)) {
                $this->parameters->set($key, reset($value));
            } else {
                $this->parameters->set($key, $value);
            }
        }

        Helper::initialize($this, $parameters);

        return $this;
    }

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


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

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

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

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

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

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

	parser.simple_key_allowed = false

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

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


Question:
// finish flushes the rest of the buffered bytes, and then sends a final empty
// packet signifying the end of the block.

func (s *blockWriteStream) finish() error {
	if s.closed {
		return nil
	}
	s.closed = true

	if err := s.getAckError(); err != nil {
		return err
	}

	err := s.flush(true)
	if err != nil {
		return err
	}

	// The last packet has no data; it's just a marker that the block is finished.
	lastPacket := outboundPacket{
		seqno:     s.seqno,
		offset:    s.offset,
		last:      true,
		checksums: []byte{},
		data:      []byte{},
	}
	s.packets <- lastPacket
	err = s.writePacket(lastPacket)
	if err != nil {
		return err
	}
	close(s.packets)

	// Wait for the ack loop to finish.
	<-s.acksDone

	// Check one more time for any ack errors.
	if err := s.getAckError(); err != nil {
		return err
	}

	return nil
}

def print(self, indent=2):
        """"""
        status = {
            ResultCode.NOT_IMPLEMENTED: '{}not implemented{}'.format(
                Fore.YELLOW, Style.RESET_ALL),
            ResultCode.IGNORED: '{}failed (ignored){}'.format(
                Fore.YELLOW, Style.RESET_ALL),
            ResultCode.FAILED: '{}failed{}'.format(
                Fore.RED, Style.RESET_ALL),
            ResultCode.PASSED: '{}passed{}'.format(
                Fore.GREEN, Style.RESET_ALL),
        }.get(self.code)
        print('{bold}{group}{provider}{checker}: {none}{status}{none}'.format(
            bold=Style.BRIGHT,
            group=(self.group.name + ' – ') if self.group.name else '',
            provider=(self.provider.name + ' – ') if self.provider else '',
            checker=self.checker.name,
            none=Style.RESET_ALL,
            status=status))
        if self.messages:
            for message in self.messages.split('\n'):
                print(pretty_description(message, indent=indent))
            if self.checker.hint:
                print(pretty_description(
                    'Hint: ' + self.checker.hint, indent=indent))

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


Question:
Resets the specified attribute's value to its initial value.
@method resetValue
@param {String} key The name of the attribute
@param {Boolean} silent Whether or not to suppress change events
@return {Boolean} Whether or not the value was set

function(key, silent){
            this._configs = this._configs || {};
            if (this._configs[key]) {
                this.set(key, this._configs[key]._initialConfig.value, silent);
                return true;
            }
            return false;
        }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
/*
HELPER FUNCS
--------------------------------------------------------
 /*
HEXTORGB
public
Takes a hex string and outputs an rgb vector as a
length 3 int array [red, green, blue]
where 0 <= rgb values <= 255

function hex2rgb(hex) {
    //validate hex string
    hex = String(hex).replace(/[^0-9a-f]/gi, '')
    // If 3 digit hex color
    if (hex.length < 6) {
      hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]
    }
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? [
      parseInt(result[1], 16)
    , parseInt(result[2], 16)
    , parseInt(result[3], 16)
    ] : null;
  }

def random_color(hue: rand(360), saturation: rand, brightness: rand, kelvin: DEFAULT_KELVIN)
      Color.new(hue, saturation, brightness, kelvin)
    end

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


Question:
Retrieve the referrer URL from the HttpServletRequest's cookies.
This will decode the URL and restore the host name if it was removed.

@param req
@return referrerURL

@Sensitive
    public String getReferrerURLFromCookies(HttpServletRequest req, String cookieName) {
        Cookie[] cookies = req.getCookies();
        String referrerURL = CookieHelper.getCookieValue(cookies, cookieName);
        if (referrerURL != null) {
            StringBuffer URL = req.getRequestURL();
            referrerURL = decodeURL(referrerURL);
            referrerURL = restoreHostNameToURL(referrerURL, URL.toString());
        }
        return referrerURL;
    }

public String getTemplateNameForResult(Route route, Result response) {
        String template = response.template();

        if (template == null) {
            if (route != null) {
                String controllerPath = RouterHelper.getReverseRouteFast(route.getController());

                // Look for a controller named template first
                if (new File(realPath + controllerPath + templateSuffix).exists()) {
                    return controllerPath;
                }

                //TODO Route(r).reverseRoute
                return controllerPath + "/" + route.getActionName();
            } else {
                return null;
            }
        } else {
            if (template.endsWith(templateSuffix)) {
                return template.substring(0, template.length() - templateSuffixLengthToRemove);
            }
            return template;
        }
    }

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


Question: // SetErrorDetail sets the ErrorDetail field's value.

func (s *TableVersionError) SetErrorDetail(v *ErrorDetail) *TableVersionError {
	s.ErrorDetail = v
	return s
}

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

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

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


Question:
Set configuration value(s)

@param string|array $path key or key-=value array
@param mixed        $val  value

@return void

public function setCfg($path, $val = null)
    {
        if (\is_array($path)) {
            $cfgPassed = $path;
        } else {
            $cfgPassed = array();
            ArrayUtil::path($cfgPassed, $path, $val);
        }
        $this->cfg = ArrayUtil::mergeDeep($this->cfg, $cfgPassed);
    }

protected function _initResource($config)
    {
        if (!empty($config['data']) && !empty($config['filename'])) {
            throw new InvalidArgumentException("The `'data'` or `'filename'` option must be defined.");
        }
        if ($config['filename']) {
            $this->_filename = $config['filename'];
            if ($this->_filename === 'php://input') {
                $this->_mode = 'r';
            }
            $this->_resource = fopen($this->_filename, $this->_mode);
            return;
        }
        if (is_resource($config['data'])) {
            $this->_resource = $config['data'];
            return;
        } elseif (is_scalar($config['data'])) {
            $this->_resource = fopen('php://temp', 'r+');
            fwrite($this->_resource, (string) $config['data']);
            rewind($this->_resource);
        }
    }

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


Question:
Read data from socket
@param int $size the max number of bytes to be read.
@return mixed the read string, null when has not data, or false on error.

public function read($size = 8192)
    {
        $buf = @fread($this->sock, $size);
        if ($buf === '' || $buf === false) {
            $buf = $this->ioEmptyError() ? false : null;
        }
        $this->ioFlagReset();
        return $buf;
    }

public boolean readMetaDataIfNeeded() throws IOException {
    if (eofReached) {
      return false;
    }
    if (rawBlockOffset == 0) {
      try {
        metaDataConsumer.readMetaData(in, metaDataBlockSize);
        rawBlockOffset += metaDataBlockSize;
      } catch (EOFException e) {
        eofReached = true;
        return false;
      }
    }
    return true;
  }

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