Question:
Create required directory structore for this azure deployment if not
exists already.

@return void

public function create()
    {
        $filesystem = new Filesystem();
        if (! file_exists($this->configDir)) {
            $filesystem->mkdir($this->configDir, 0777);
            $filesystem->copy(__DIR__ . '/../Resources/role_template/ServiceConfiguration.cscfg', $this->configDir . '/ServiceConfiguration.cscfg');
            $filesystem->copy(__DIR__ . '/../Resources/role_template/ServiceDefinition.csdef', $this->configDir . '/ServiceDefinition.csdef');
            $filesystem->mirror(__DIR__ . '/../Resources/role_template/resources', $this->configDir . '/resources', null, array(
                'copy_on_windows' => true
            ));
            $filesystem->mirror(__DIR__ . '/../Resources/role_template/php', $this->configDir . '/php', null, array(
                'copy_on_windows' => true
            ));
        }

        if (! file_exists($this->binDir)) {
            $filesystem->mkdir($this->binDir, 0777);
        }
        $filesystem->mirror(__DIR__ . '/../Resources/role_template/bin', $this->binDir, null, array(
            'copy_on_windows' => true
        ));
    }

func (in *RecreateDeploymentStrategyParams) DeepCopy() *RecreateDeploymentStrategyParams {
	if in == nil {
		return nil
	}
	out := new(RecreateDeploymentStrategyParams)
	in.DeepCopyInto(out)
	return out
}

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


Question: Removes any present error message.<p>

public void removeValidationMessage() {

        if (m_hasError) {
            m_messageText.setInnerText("");
            removeStyleName(formCss().hasError());
            removeStyleName(formCss().hasWarning());
            m_hasError = false;
        }

    }

private function addHtmlMessage($type, $html = null, $css_selector = null)
    {
        return $this->add($type, array(
            'value' => $html,
            'selector' => $css_selector,
        ));
    }

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


Question:
Builds template message structure.

@return array

public function buildMessage()
    {
        if (!empty($this->message)) {
            return $this->message;
        }

        $templateMessage = [
            'type' => MessageType::TEMPLATE,
            'altText' => $this->altText,
            'template' => $this->templateBuilder->buildTemplate(),
        ];

        if ($this->quickReply) {
            $templateMessage['quickReply'] = $this->quickReply->buildQuickReply();
        }

        $this->message[] = $templateMessage;

        return $this->message;
    }

public function leave(ResponseInterface $response = null)
    {
        $this->ends = [
            'wt' => microtime(true),
            'mu' => memory_get_usage(),
            'pmu' => memory_get_peak_usage(),
        ];
        if ($response) {
            $this->response = [
                'headers' => $response->getHeaders(),
                'statusCode' => $response->getStatusCode(),
                'body' => (string)$response->getBody(),
            ];
        }
    }

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


Question:
This method will cast {@code Set<?>} to {@code Set<T>}
assuming {@code ?} is castable to {@code T}.

@param <T> the generic type
@param set a {@code Set} object
@return a casted {@code Set} object

@SuppressWarnings("unchecked")
    private static <T> Set<T> cast(Set<?> set) {
        return (Set<T>)set;
    }

public static TemplateMetadata fromTemplate(TemplateNode template) {
    TemplateMetadata.Builder builder =
        builder()
            .setTemplateName(template.getTemplateName())
            .setSourceLocation(template.getSourceLocation())
            .setSoyFileKind(SoyFileKind.SRC)
            .setContentKind(template.getContentKind())
            .setStrictHtml(template.isStrictHtml())
            .setDelPackageName(template.getDelPackageName())
            .setVisibility(template.getVisibility())
            .setParameters(Parameter.directParametersFromTemplate(template))
            .setDataAllCallSituations(DataAllCallSituation.fromTemplate(template));
    switch (template.getKind()) {
      case TEMPLATE_BASIC_NODE:
        builder.setTemplateKind(Kind.BASIC);
        break;
      case TEMPLATE_DELEGATE_NODE:
        builder.setTemplateKind(Kind.DELTEMPLATE);
        TemplateDelegateNode deltemplate = (TemplateDelegateNode) template;
        builder.setDelTemplateName(deltemplate.getDelTemplateName());
        builder.setDelTemplateVariant(deltemplate.getDelTemplateVariant());
        break;
      case TEMPLATE_ELEMENT_NODE:
        builder.setTemplateKind(Kind.ELEMENT);
        break;
      default:
        throw new AssertionError("unexpected template kind: " + template.getKind());
    }
    return builder.build();
  }

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


Question:
Runs the system handler.

@param   string  $link   The route to be set to.
@param   string  $method The method to be set to.

@return string

public function run(string $link = null, string $method = null): string
    {
        if ($link === null) {
            if (isset($_SERVER['REQUEST_URI']) === false) {
                $_SERVER['REQUEST_URI'] = '/';
            }
            $link = str_replace("?" . $_SERVER["QUERY_STRING"], "", $_SERVER["REQUEST_URI"]);
        }
        $link = '/' . trim($link, '/');
        if ($link == '/Core-Framework') {
            $link .= '/';
        }

        if ($method === null) {
            if (isset($_SERVER['REQUEST_METHOD']) === false) {
                $_SERVER['REQUEST_METHOD'] = 'GET';
            }
            $method = $_SERVER['REQUEST_METHOD'];
        }
        if ($method == 'POST' && empty($_POST['_method']) === false) {
            $method = $_POST['_method'];
            unset($_POST['_method']);
        }

        $result = $this->router->match($link, $method);
        $this->templates->addData([
            'template' => isset($_GET['template'])
        ]);

        try {
            if ($result !== false) {
                if (func_num_args() > 2) {
                    $arguments_list = func_get_args();
                    array_shift($arguments_list);array_shift($arguments_list);
                    foreach ($arguments_list as $argument) {
                        $result['params'][] = $argument;
                    }
                } elseif ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) === false) {
                    $result['params'][] = $_POST;
                } elseif ($_SERVER['REQUEST_METHOD'] == 'GET' && empty($_GET) === false) {
                    $result['params'][] = $_GET;
                }
                if (is_string($result['target']) === true) {
                    $result['target'] = explode("@", $result['target']);
                } else {
                    $result['target'] = [$result['target']];
                }
                if (count($result['target']) === 1 && $result['target'][0] == "API") {
                    return $this->api($result['params'][0])->run();
                } elseif (count($result['target']) === 1 && is_callable($result['target'][0]) === true) {
                    return call_user_func_array($result['target'][0], $result['params']);
                } elseif (count($result['target']) === 2 && class_exists("TheCMSThread\\Core\\Admin\\Controller\\" . $result['target'][0]) === true && method_exists("TheCMSThread\\Core\\Admin\\Controller\\" . $result['target'][0], $result['target'][1]) === true) {
                    $controller = new \ReflectionClass("TheCMSThread\\Core\\Admin\\Controller\\" . $result['target'][0]);
                    $controller = $controller->newInstance($this->core, $this->router, $this->templates, $this->container);
                    return call_user_func_array([
                        $controller,
                        $result['target'][1]
                    ], $result['params']);
                } else {
                    throw new \LogicException("Cannot find route handler");
                }
            } else {
                if (headers_sent() === false) {
                    header('X-PHP-Response-Code: 404', true, 404);
                }
                return $this->templates->render("404");
            }
        } catch (\Throwable $e) {
                if (headers_sent() === false) {
                    header('X-PHP-Response-Code: 500', true, 500);
                }
            return $this->templates->render("500", [
                "error" => $e,
                "result" => $result
            ]);
        }
    }

public function getUrl() {
        try {
            if ($this->getRequestMethod()!= \Request::HTTP_GET) {
                    throw new \common_exception_NotImplemented('Only GET method is accepted to request this service.');
            }

            if(!$this->hasRequestParameter('deliveryId')) {
                $this->returnFailure(new \common_exception_MissingParameter('At least one mandatory parameter was required but found missing in your request'));
            }

            $selectedDelivery = new \core_kernel_classes_Resource($this->getRequestParameter('deliveryId'));
            if(!$selectedDelivery->isInstanceOf(new \core_kernel_classes_Class(TaoOntology::CLASS_URI_DELIVERY))) {
                $this->returnFailure(new \common_exception_NotFound('Delivery not found'));
            }

            $this->returnSuccess(LTIDeliveryTool::singleton()->getLaunchUrl(array('delivery' => $selectedDelivery->getUri())));

        } catch (\Exception $ex) {
             $this->returnFailure($ex);
        }

    }

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


Question:
@param       $table
@param null  $on
@param null  $where
@param array $binds

@return $this

public function join($table, $on = null, $where = null, $binds = [])
    {
        if (!$on) {
            $this->join[] = $table;
        } else {
            $this->join[] = $table . (strpos($table, ' ON ') ? ' AND ' : ' ON ') . $on;
        }

        if ($where) {
            $this->where(new Raw($where));
        }

        if ($binds) {
            foreach ($binds as $bind) {
                $this->bind($bind, 'join');
            }
        }

        return $this;
    }

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:
(non-PHPdoc)
@see \oat\taoDelivery\model\authorization\AuthorizationProvider::verifyStartAuthorization()
@param string $deliveryId
@param User $user

public function verifyStartAuthorization($deliveryId, User $user)
    {
        /** @var TestTakerAuthorizationService $service */
        $service = $this->getServiceLocator()->get(TestTakerAuthorizationService::SERVICE_ID);
        $service->verifyStartAuthorization($deliveryId, $user);
    }

function getClient()
    {
        $transport = $this->getTransport();
        $transport->setAuth($this->username, $this->password);

        return new Client($transport);
    }

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


Question:
returns a list of all methods

@return  array<MoufXmlReflectionMethod>

public function getMethods()
    {
        $moufMethods = array();
        foreach ($this->xmlRoot->method as $method) {
            $moufMethods[] = new MoufXmlReflectionMethod($this, $method);
        }

        return $moufMethods;
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Method to load an asset by it's name.

@param   string  $name
@return  object

public static function oneByName($name)
	{
		$model = self::all()
			->whereEquals('name', $name)
			->row();

		if (!$model)
		{
			$model = self::blank();
		}

		return $model;
	}

public void marshall(AttachInstancesToLoadBalancerRequest attachInstancesToLoadBalancerRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(attachInstancesToLoadBalancerRequest.getLoadBalancerName(), LOADBALANCERNAME_BINDING);
            protocolMarshaller.marshall(attachInstancesToLoadBalancerRequest.getInstanceNames(), INSTANCENAMES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Loads the local configuration from "~/.localhook/config.json" file.

protected function loadConfiguration()
    {
        try {
            $configuration = $this->configurationStorage->loadFromFile()->get();
        } catch (NoConfigurationException $e) {

            $this->io->comment($e->getMessage());

            if (!$this->secret) {
                $this->secret = $this->io->ask('Secret');
            }
            $configuration = $this->parseConfigurationKey();
        }
        $this->serverUrl = $configuration['socket_url'];
        $this->secret = $configuration['secret'];
        $this->configurationStorage->merge($configuration)->save();
    }

func (mutatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateMutatingWebhookConfigurationUpdate(obj.(*admissionregistration.MutatingWebhookConfiguration), old.(*admissionregistration.MutatingWebhookConfiguration))
}

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


Question: // SetLocation sets the Location field's value.

func (s *CreateDistributionOutput) SetLocation(v string) *CreateDistributionOutput {
	s.Location = &v
	return s
}

public void fixAddress(String name) throws IOException
    {
        Label label = labels.get(name);
        if (label == null)
        {
            label = new Label(name);
            labels.put(name, label);
        }
        int pos = position();
        label.setAddress(pos);
        labelMap.put(pos, label);
    }

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


Question:
Populate the ``_private_notes`` key.

    Also populates the ``_export_to`` key through side effects.

def _private_notes(self, key, value):

    def _is_for_cds(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'CDS' in normalized_c_values

    def _is_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'HAL' in normalized_c_values

    def _is_not_for_hal(value):
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        return 'NOT HAL' in normalized_c_values

    _private_notes = self.get('_private_notes', [])
    _export_to = self.get('_export_to', {})

    for value in force_list(value):
        if _is_for_cds(value):
            _export_to['CDS'] = True

        if _is_for_hal(value):
            _export_to['HAL'] = True
        elif _is_not_for_hal(value):
            _export_to['HAL'] = False

        source = force_single_element(value.get('9'))
        for _private_note in force_list(value.get('a')):
            _private_notes.append({
                'source': source,
                'value': _private_note,
            })

    self['_export_to'] = _export_to
    return _private_notes

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


Question:
- Make table, if it doesn't exist.
        - Add fields that aren't there.
        - Warn about superfluous fields, but don't delete them, unless
          ``drop_superfluous_columns == True``.
        - Make indexes, if requested.

def create_or_update_table(self,
                               tablename: str,
                               fieldspeclist: FIELDSPECLIST_TYPE,
                               drop_superfluous_columns: bool = False,
                               dynamic: bool = False,
                               compressed: bool = False) -> None:

        # 1. Make table, if it doesn't exist
        self.make_table(tablename, fieldspeclist, dynamic=dynamic,
                        compressed=compressed)

        # 2. Are all the fields there?
        # ... copes fine with fieldnames coming back in Unicode and being
        #     compared to str
        fields_in_db = set(self.fetch_column_names(tablename))
        desired_fieldnames = set(
            self.fieldnames_from_fieldspeclist(fieldspeclist))
        missing_fieldnames = desired_fieldnames - fields_in_db
        missing_fieldspecs = self.fieldspec_subset_by_name(fieldspeclist,
                                                           missing_fieldnames)
        for f in missing_fieldspecs:
            self.add_column(tablename, f)

        # 3. Anything superfluous?
        superfluous_fieldnames = fields_in_db - desired_fieldnames
        for f in superfluous_fieldnames:
            if drop_superfluous_columns:
                log.warning("... dropping superfluous field: " + f)
                self.drop_column(tablename, f)
            else:
                log.warning("... superfluous field (ignored): " + f)

        # 4. Make indexes, if some have been requested:
        for fs in fieldspeclist:
            self.create_index_from_fieldspec(tablename, fs)

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Determine the depth of this configuration so we know how to pad the outputted table of data.
@param  array $config
@return integer

private function getConfigDepth($config) {
        $total_depth = 1;

        foreach ($config as $data) {
            if (is_array($data)) {
                $depth = $this->getConfigDepth($data) + 1;

                if ($depth > $total_depth) {
                    $total_depth = $depth;
                }
            }
        }

        return $total_depth;
    }

public function transactionRollback($toSavepoint = false)
	{
		if (!$toSavepoint || $this->transactionDepth <= 1)
		{
			$this->connect();

			if ($this->connection->rollback())
			{
				$this->transactionDepth = 0;
			}

			return;
		}

		$savepoint = 'SP_' . ($this->transactionDepth - 1);

		if ($this->executeUnpreparedQuery('ROLLBACK TO SAVEPOINT ' . $this->quoteName($savepoint)))
		{
			$this->transactionDepth--;
		}
	}

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


Question:
generate the subscribe stub headers based on the supplied config
        :return: i

def _generate_subscribe_headers(self):

        headers =[]
        headers.append(('predix-zone-id', self.eventhub_client.zone_id))

        token = self.eventhub_client.service._get_bearer_token()
        headers.append(('subscribername', self._config.subscriber_name))
        headers.append(('authorization', token[(token.index(' ') + 1):]))

        if self._config.topics is []:
            headers.append(('topic', self.eventhub_client.zone_id + '_topic'))
        else:
            for topic in self._config.topics:
                headers.append(('topic', topic))

        headers.append(('offset-newest', str(self._config.recency == self._config.Recency.NEWEST).lower()))

        headers.append(('acks', str(self._config.acks_enabled).lower()))
        if self._config.acks_enabled:
            headers.append(('max-retries', str(self._config.ack_max_retries)))
            headers.append(('retry-interval', str(self._config.ack_retry_interval_seconds) + 's'))
            headers.append(('duration-before-retry', str(self._config.ack_duration_before_retry_seconds) + 's'))

        if self._config.batching_enabled:
            headers.append(('batch-size', str(self._config.batch_size)))
            headers.append(('batch-interval', str(self._config.batch_interval_millis) + 'ms'))

        return headers

def write_source(self, source, comment=None, reject=False):

        if not self._header_written:
            observations = [reading.get_observation() for reading in source.get_readings()]
            self.write_headers(observations, self.sys_header)

        self._write_source(source, comment=comment, reject=reject)

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


Question: Closes the WebSocket connection.

def close(self, code: int = None, reason: str = None) -> None:
        """"""
        if not self.server_terminated:
            if not self.stream.closed():
                if code is None and reason is not None:
                    code = 1000  # "normal closure" status code
                if code is None:
                    close_data = b""
                else:
                    close_data = struct.pack(">H", code)
                if reason is not None:
                    close_data += utf8(reason)
                try:
                    self._write_frame(True, 0x8, close_data)
                except StreamClosedError:
                    self._abort()
            self.server_terminated = True
        if self.client_terminated:
            if self._waiting is not None:
                self.stream.io_loop.remove_timeout(self._waiting)
                self._waiting = None
            self.stream.close()
        elif self._waiting is None:
            # Give the client a few seconds to complete a clean shutdown,
            # otherwise just close the connection.
            self._waiting = self.stream.io_loop.add_timeout(
                self.stream.io_loop.time() + 5, self._abort
            )

public function terminate()
    {
        if (!$this->application || false === $this->application->isStarted()) {
            return;
        }

        ob_implicit_flush(true);
        flush();

        // $response may not be set
        if ($this->response instanceof Response) {
            $this->application->getEventDispatcher()->dispatch(
                KernelEvents::TERMINATE,
                new PostResponseEvent($this, $this->getRequest(), $this->response)
            );
        }
    }

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


Question:
Process file dispersion.

@param string $finalTarget

@return string
@throws \Xloit\Bridge\Zend\Filter\Exception\NoSuchDirectoryException

protected function fileDispersion($finalTarget)
    {
        if (strpos($finalTarget, DIRECTORY_SEPARATOR . 'original_image' . DIRECTORY_SEPARATOR) !== false) {
            return $finalTarget;
        }
        if ($this->isFileDispersionEnabled()) {
            $file           = pathinfo($finalTarget, PATHINFO_BASENAME);
            $dispersionPath = $this->getDispersionPath($file);
            $directory      = pathinfo($finalTarget, PATHINFO_DIRNAME) . $dispersionPath;
            $finalTarget    = $directory . $file;

            $this->setTargetDirectory($directory);
            $this->createFolders();
        }

        return $finalTarget;
    }

private void zipDirectory(String zipFile, String dirToZip) {
    File directory = new File(dirToZip);
    try (ZipOutputStream stream = new ZipOutputStream(new FileOutputStream(zipFile))) {
      addDirectoryToZip(directory, directory, stream);
    } catch (Exception e) {
      throw new PlatformManagerException("Failed to zip module", e);
    }
  }

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


Question: //export closeCallback

func closeCallback(conn C.virConnectPtr, reason int, goCallbackId int) {
	ctx := getCallbackId(goCallbackId)
	switch cctx := ctx.(type) {
	case *closeContext:
		cctx.cb(VirConnection{ptr: conn}, reason, cctx.f)
	default:
		panic("Inappropriate callback type called")
	}
}

public function block($seconds, $callback = null)
    {
        $starting = $this->currentTime();

        while (! $this->acquire()) {
            usleep(250 * 1000);

            if ($this->currentTime() - $seconds >= $starting) {
                throw new LockTimeoutException;
            }
        }

        if (is_callable($callback)) {
            try {
                return $callback();
            } finally {
                $this->release();
            }
        }

        return true;
    }

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


Question: // contextWithRepositoryScope returns a context with tokenScopesKey{} and the repository scope value.

func contextWithRepositoryScope(ctx context.Context, refspec reference.Spec, push bool) (context.Context, error) {
	s, err := repositoryScope(refspec, push)
	if err != nil {
		return nil, err
	}
	return context.WithValue(ctx, tokenScopesKey{}, []string{s}), nil
}

public function read(&$result)
    {
        $relations = [];
        $conditions = [];

        foreach ($result as $i => $entity) {
            foreach ($this->definition->localKeys() as $local => $refer) {
                $conditions[$refer][] = $this->accessor->getPropertyValue($entity, $local);
            }

            $relations[$this->buildLocalKey($entity, $this->definition->localKeys())][] = &$result[$i];
        }

        $collection = $this->fetch($this->definition->mediator(), $conditions, false);

// --- MEDIATOR START

        $mediator = [];
        $conditions = [];
        foreach ($collection as $entity) {
            foreach ($this->definition->foreignKeys() as $local => $refer) {
                $conditions[$refer][] = $this->accessor->getPropertyValue($entity, $local);
            }

            $in = $this->buildForeignKey($entity, $this->definition->localKeys());
            $out = $this->buildLocalKey($entity, $this->definition->foreignKeys());
            $mediator[$out][] = $in;
        }

        $collection = $this->fetch($this->definition->entity(), $conditions, true);

// --- MEDIATOR END

        foreach ($collection as $relEntity) {
            $key = $this->buildForeignKey($relEntity, $this->definition->foreignKeys());

            if (!isset($mediator[$key])) {
                continue;
            }
            foreach ($mediator[$key] as $mkey) {
                if (!isset($relations[$mkey])) {
                    continue;
                }

                foreach ($relations[$mkey] as &$entity) {
                    $this->accessor->addPropertyValue($entity, $this->definition->container(), $relEntity);
                    unset($entity);
                }
            }
        }

        return $result;
    }

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


Question:
Trim all occurences of the supplied leading character from the given String.

@param str the string to check
@param leadingCharacter the leading character to be trimmed
@return the trimmed String

public static String trimLeadingCharacter(String str, final char leadingCharacter)
   {
      return trimLeadingCharacter(str, new CharacterFilter()
      {
         @Override
         public boolean isCharacterLegal(char character)
         {
            return character == leadingCharacter;
         }
      });
   }

public function render($type = 'html')
    {
        $row = $this->getTable()->getRow()->getActualRow();

        $value = '';

        if (is_array($row) || $row instanceof \ArrayAccess) {
            $value = (isset($row[$this->getHeader()->getName()])) ? $row[$this->getHeader()->getName()] : '';
        } elseif (is_object($row)) {
            $headerName = $this->getHeader()->getName();
            $methodName = 'get' . ucfirst($headerName);
            if (method_exists($row, $methodName)) {
                $value = $row->$methodName();
            } else {
                $value = (property_exists($row, $headerName)) ? $row->$headerName : '';
            }
        }

        foreach ($this->decorators as $decorator) {
            if ($decorator->validConditions()) {
                $value = $decorator->render($value);
            }
        }

        if ($type == 'html') {
            $ret = sprintf("<td %s>%s</td>", $this->getAttributes(), $value);
            $this->clearVar();
            return $ret;

        } else {
            return $value;
        }
    }

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


Question:
// Relaxed produces a regexp that matches any URL matched by Strict, plus any
// URL with no scheme.

func Relaxed() *regexp.Regexp {
	re := regexp.MustCompile(relaxedExp())
	re.Longest()
	return re
}

protected function get_registered_options() {
		$rest_options = array();

		foreach ( get_registered_settings() as $name => $args ) {
			if ( empty( $args['show_in_rest'] ) ) {
				continue;
			}

			$rest_args = array();
			if ( is_array( $args['show_in_rest'] ) ) {
				$rest_args = $args['show_in_rest'];
			}

			$defaults = array(
				'name'   => ! empty( $rest_args['name'] ) ? $rest_args['name'] : $name,
				'schema' => array(),
			);
			$rest_args = array_merge( $defaults, $rest_args );

			$default_schema = array(
				'type'        => empty( $args['type'] ) ? null : $args['type'],
				'description' => empty( $args['description'] ) ? '' : $args['description'],
				'default'     => isset( $args['default'] ) ? $args['default'] : null,
			);

			$rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
			$rest_args['option_name'] = $name;

			// Skip over settings that don't have a defined type in the schema.
			if ( empty( $rest_args['schema']['type'] ) ) {
				continue;
			}

			// Whitelist the supported types for settings, as we don't want invalid types
			// to be updated with arbitrary values that we can't do decent sanitizing for.
			if ( ! in_array( $rest_args['schema']['type'], array( 'number', 'string', 'boolean' ), true ) ) {
				continue;
			}

			$rest_options[ $rest_args['name'] ] = $rest_args;
		}

		return $rest_options;
	}

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


Question:
Wait until a Block backed by a StatefulController has initialized

    Args:
        context (Context): The context to use to make the child block
        mri (str): The mri of the child block
        timeout (float): The maximum time to wait

def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT):

    context.when_matches(
        [mri, "state", "value"], StatefulStates.READY,
        bad_values=[StatefulStates.FAULT, StatefulStates.DISABLED],
        timeout=timeout)

async def verify_worker_impls(chain):

    valid_worker_impls = get_valid_worker_impls()
    for obj in chain.get_all_links_in_chain():
        worker_impl = obj.worker_impl
        log.info("Verifying {} {} as a {} task...".format(obj.name, obj.task_id, worker_impl))
        # Run tests synchronously for now.  We can parallelize if efficiency
        # is more important than a single simple logfile.
        await valid_worker_impls[worker_impl](chain, obj)

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


Question:
Tells if the path is an absolute path.
@param string $path The file system path to test
@return bool True if the path is an absolute path, false if not

private static function isAbsolute($path)
    {
        $path = trim($path);

        if ($path === '') {
            return false;
        }

        $length = strcspn($path, '/\\');

        return $length === 0 || $path[$length - 1] === ':';
    }

public static function getFilesArray($root)
	{
		$alias=array();
		$directories=array();
		$last_letter=$root[strlen($root)-1];
		$root= ($last_letter=='\\' || $last_letter=='/')? $root : $root.DIRECTORY_SEPARATOR;

		$directories[]=$root;

		while (sizeof($directories)) {
			$dir=array_pop($directories);
			if ($handle=opendir($dir)) {
				while (FALSE!==($file=readdir($handle))) {
					if ($file=='.' || $file=='..') {
						continue;
						}
					$file=$dir.$file;
					if (is_dir($file)) {
						$directory_path=$file.DIRECTORY_SEPARATOR;
						array_push($directories, $directory_path);
						}
					elseif (is_file($file)) {
						$key=basename($file);
						$alias[substr($key, 1, strpos($key, '.')-1)]=$file;
						}
					}
				closedir($handle);
				}
			}

		return $alias;
	}

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


Question:
// readFrom reads an arrayContainer from stream.
// PRE-REQUISITE: you must size the arrayContainer correctly (allocate b.content)
// *before* you call readFrom. We can't guess the size in the stream
// by this point.

func (ac *arrayContainer) readFrom(stream io.Reader) (int, error) {
	buf := uint16SliceAsByteSlice(ac.content)
	return io.ReadFull(stream, buf)
}

public static <C> SlicePredicate getPredicate(ColumnSlice<C> columns, Serializer<C> colSer) {
        // Get all the columns
        if (columns == null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange(ByteBuffer.wrap(new byte[0]), ByteBuffer.wrap(new byte[0]), false,
                    Integer.MAX_VALUE));
            return predicate;
        }
        // Get a specific list of columns
        if (columns.getColumns() != null) {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setColumn_namesIsSet(true);
            predicate.column_names = colSer.toBytesList(columns.getColumns());
            return predicate;
        }
        else {
            SlicePredicate predicate = new SlicePredicate();
            predicate.setSlice_range(new SliceRange((columns.getStartColumn() == null) ? ByteBuffer.wrap(new byte[0])
                    : ByteBuffer.wrap(colSer.toBytes(columns.getStartColumn())),
                    (columns.getEndColumn() == null) ? ByteBuffer.wrap(new byte[0]) : ByteBuffer.wrap(colSer
                            .toBytes(columns.getEndColumn())), columns.getReversed(), columns.getLimit()));
            return predicate;
        }
    }

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


Question:
Set the application's locale based on the user preference.
@return void

public static function setAppLocale()
    {
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        elseif (
            ($user = BackendAuth::getUser()) &&
            ($locale = static::get('locale'))
        ) {
            Session::put('locale', $locale);
            App::setLocale($locale);
        }
    }

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question:
Assign a response entity body

@param null|string|callable|Body $body
@throws \InvalidArgumentException
@return Response Returns the current object instance

public function setBody(Body $body)
    {
        $this->body = $body;
        $this->setAllHeaders($body->getHeaders());
        $this->setStatus($body->getStatusCode());

        return $this;
    }

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

	var roleScopes []role.RoleDescriptor

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

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

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

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


Question:
Returns the extensions allowed for compressed documents.

@param type $default
@return string

public function getCompressedExtensions( $default = null ) {

		$prop = $this->properties[ self::PROP_EXTENSION_COMPRESSED ];

		if( isset( $prop ) && strlen( $prop ) > 0 ) {

			return preg_split( "/,/", $prop );
		}

		return $default;
	}

public function getParameter( $parameter )
    {

        self::isParameterAllowed( $parameter );

        $value = $this->query(new Raw("SHOW {$parameter}"))->fetch( Result::FETCH_SINGLE );

        return ( $value === 'true' or $value === 'false' )
            ? \Bond\boolval( $value )
            : $value;

    }

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


Question:
getHubWindowsIndexedByStartTimeAndDeliveryType()

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2012-10-27

@return array

public function getHubWindowsIndexedByStartTimeAndDeliveryType()
    {
        $windows = array();

        foreach ($this->getHubWindows() as $window)
        {
            $start_time    = $window->getStartTime()->format(\DateTime::ATOM);
            $delivery_type = $window->getDeliveryType();

            $windows[$start_time][$delivery_type] = $window;
        }

        return $windows;
    }

def post_file(api_method, file, parameters = {})
      parameters.merge!({"token" => @token})

      body = {}
      body.merge!({:method => api_method})
      body.merge!({:params => parameters})

      # Brightcove requires that the JSON-RPC call absolutely
      # be the first part of a multi-part POST like create_video.
      if RUBY_VERSION >= '1.9'
        payload = {}
      else
        payload = OrderedHash.new
      end

      payload[:json] = body.to_json
      payload[:file] = File.new(file, 'rb')

      execution_payload = {
        :method => :post,
        :url => @write_api_url,
        :payload => payload,
        :content_type => :json,
        :accept => :json,
        :multipart => true
      }

      execution_payload[:timeout] = @timeout if @timeout
      execution_payload[:open_timeout] = @open_timeout if @open_timeout

      response = RestClient::Request.execute(execution_payload)

      JSON.parse(response)
    end

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


Question:
Resets the KeyFactory to its initial state.

@return {@code this} for chaining

public KeyFactory reset() {
    setProjectId(pi);
    setNamespace(ns);
    kind = null;
    ancestors.clear();
    return this;
  }

public void clear(final String propertyName) {
        Preconditions.checkNotNull(propertyName);
        if (properties.containsKey(propertyName)) {
            properties.put(propertyName, null);
        } else if (references.containsKey(propertyName)) {
            references.put(propertyName, null);
        }
    }

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


Question: Decorator to add sets of required mutually exclusive args to subcommands.

def argset(name, *args, **kwargs):

    def _arg(f):
        if not hasattr(f, '_subcommand_argsets'):
            f._subcommand_argsets = {}
        f._subcommand_argsets.setdefault(name, []).append((args, kwargs))
        return f
    return _arg

func (service *Service) CreateCollection(label string) (*Collection, error) {
  properties := make(map[string]dbus.Variant)
  properties["org.freedesktop.Secret.Collection.Label"] = dbus.MakeVariant(label)

  var path   dbus.ObjectPath
  var prompt dbus.ObjectPath

  err := service.dbus.Call("org.freedesktop.Secret.Service.CreateCollection", 0, properties, "").Store(&path, &prompt)
  if err != nil {
    return &Collection{}, err
  }

  if isPrompt(prompt) {
    prompt := NewPrompt(service.conn, prompt)

    result, err := prompt.Prompt()
    if err != nil {
      return &Collection{}, err
    }

    path = result.Value().(dbus.ObjectPath)
  }

  return NewCollection(service.conn, path), nil
}

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


Question:
Get the first crumb formated as HTML.

@return string

public function firstFormated(): string
    {
        if ($this->isEmpty()) {
            return '';
        }

        $crumb = reset($this->breadcrumbs);

        return $this->renderCrumb($crumb['name'], $crumb['href'], false, 1);
    }

public static function toCake(PsrResponse $response)
    {
        $body = static::getBody($response);
        $data = [
            'status' => $response->getStatusCode(),
            'body' => $body['body'],
        ];
        $cake = new CakeResponse($data);
        if ($body['file']) {
            $cake->file($body['file']);
        }
        $cookies = static::parseCookies($response->getHeader('Set-Cookie'));
        foreach ($cookies as $cookie) {
            $cake->cookie($cookie);
        }
        $headers = static::collapseHeaders($response);
        $cake->header($headers);

        if (!empty($headers['Content-Type'])) {
            $cake->type($headers['Content-Type']);
        }

        return $cake;
    }

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


Question:
long-gracing ::= gracing-grace / gracing-vol / gracing-style / gracing-len
/ gracing-finger / gracing-phrase / gracing-exec / gracing-other

Rule LongGracing() {
		return FirstOf(GracingGrace(), GracingStyle(), GracingLen(),
				GracingFinger(), GracingPhrase(), GracingExec(),
				//!fermata! before !f!
				GracingVol(), GracingOther())
			.label(LongGracing);
	}

func opToString(op syntax.Op) string {
	switch op {
	case syntax.OpNoMatch:
		return "OpNoMatch"
	case syntax.OpEmptyMatch:
		return "OpEmptyMatch"
	case syntax.OpLiteral:
		return "OpLiteral"
	case syntax.OpCharClass:
		return "OpCharClass"
	case syntax.OpAnyCharNotNL:
		return "OpAnyCharNotNL"
	case syntax.OpAnyChar:
		return "OpAnyChar"
	case syntax.OpBeginLine:
		return "OpBeginLine"
	case syntax.OpEndLine:
		return "OpEndLine"
	case syntax.OpBeginText:
		return "OpBeginText"
	case syntax.OpEndText:
		return "OpEndText"
	case syntax.OpWordBoundary:
		return "OpWordBoundary"
	case syntax.OpNoWordBoundary:
		return "OpNoWordBoundary"
	case syntax.OpCapture:
		return "OpCapture"
	case syntax.OpStar:
		return "OpStar"
	case syntax.OpPlus:
		return "OpPlus"
	case syntax.OpQuest:
		return "OpQuest"
	case syntax.OpRepeat:
		return "OpRepeat"
	case syntax.OpConcat:
		return "OpConcat"
	case syntax.OpAlternate:
		return "OpAlternate"
	}

	panic(fmt.Sprintf("invalid op: %d", op))
}

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


Question:
Set 'Seller' value

@param \AgentSIB\Diadoc\Api\Proto\Invoicing\DiadocOrganizationInfo $value

public function setSeller(\AgentSIB\Diadoc\Api\Proto\Invoicing\DiadocOrganizationInfo $value)
    {
        $this->Seller = $value;
    }

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case BpsimPackage.ELEMENT_PARAMETERS__TIME_PARAMETERS:
				return timeParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__CONTROL_PARAMETERS:
				return controlParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__RESOURCE_PARAMETERS:
				return resourceParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PRIORITY_PARAMETERS:
				return priorityParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__COST_PARAMETERS:
				return costParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__PROPERTY_PARAMETERS:
				return propertyParameters != null;
			case BpsimPackage.ELEMENT_PARAMETERS__VENDOR_EXTENSION:
				return vendorExtension != null && !vendorExtension.isEmpty();
			case BpsimPackage.ELEMENT_PARAMETERS__ELEMENT_REF:
				return ELEMENT_REF_EDEFAULT == null ? elementRef != null : !ELEMENT_REF_EDEFAULT.equals(elementRef);
			case BpsimPackage.ELEMENT_PARAMETERS__ID:
				return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
		}
		return super.eIsSet(featureID);
	}

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


Question:
/*
Set the value of the RedeliverdCount field in the message header.

Javadoc description supplied by JsMessage interface.

public final void setRedeliveredCount(int value) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "setRedeliveredCount", Integer.valueOf(value));
        getHdr2().setIntField(JsHdr2Access.REDELIVEREDCOUNT, value);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "setRedeliveredCount");
    }

private void receiveMessage(ClientSocket client, DataInputStream buffer, byte from, StateConnection expected)
            throws IOException
    {
        if (ServerImpl.checkValidity(client, from, expected))
        {
            final byte dest = buffer.readByte();
            final byte type = buffer.readByte();
            final int size = buffer.readInt();
            if (size > 0)
            {
                final byte[] clientData = new byte[size];
                if (buffer.read(clientData) != -1) // CHECKSTYLE IGNORE LINE: TrailingComment|NestedIfDepth
                {
                    final DataInputStream clientBuffer = new DataInputStream(new ByteArrayInputStream(clientData));
                    decodeMessage(type, from, dest, clientBuffer);
                }
            }
            final int headerSize = 4;
            bandwidth += headerSize + size;
        }
    }

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


Question:
Associates the given {@link JFXTooltip} tooltip to the given node.
The tooltip will be shown according to the given {@link Pos} pos

@param node
@param tooltip

public static void install(Node node, JFXTooltip tooltip, Pos pos) {
        tooltip.setPos(pos);
        BEHAVIOR.install(node, tooltip);
    }

private static Element emitterToElement(Document document,
			ConfigurableEmitter emitter) {
		Element root = document.createElement("emitter");
		root.setAttribute("name", emitter.name);
		root.setAttribute("imageName", emitter.imageName == null ? ""
				: emitter.imageName);
		root
				.setAttribute("useOriented", emitter.useOriented ? "true"
						: "false");
		root
				.setAttribute("useAdditive", emitter.useAdditive ? "true"
						: "false");

		if (emitter.usePoints == Particle.INHERIT_POINTS) {
			root.setAttribute("renderType", "inherit");
		}
		if (emitter.usePoints == Particle.USE_POINTS) {
			root.setAttribute("renderType", "points");
		}
		if (emitter.usePoints == Particle.USE_QUADS) {
			root.setAttribute("renderType", "quads");
		}

		root.appendChild(createRangeElement(document, "spawnInterval",
				emitter.spawnInterval));
		root.appendChild(createRangeElement(document, "spawnCount",
				emitter.spawnCount));
		root.appendChild(createRangeElement(document, "initialLife",
				emitter.initialLife));
		root.appendChild(createRangeElement(document, "initialSize",
				emitter.initialSize));
		root.appendChild(createRangeElement(document, "xOffset",
				emitter.xOffset));
		root.appendChild(createRangeElement(document, "yOffset",
				emitter.yOffset));
		root.appendChild(createRangeElement(document, "initialDistance",
				emitter.initialDistance));
		root.appendChild(createRangeElement(document, "speed", emitter.speed));
		root
				.appendChild(createRangeElement(document, "length",
						emitter.length));
		root.appendChild(createRangeElement(document, "emitCount",
				emitter.emitCount));

		root
				.appendChild(createValueElement(document, "spread",
						emitter.spread));
		root.appendChild(createValueElement(document, "angularOffset",
				emitter.angularOffset));
		root.appendChild(createValueElement(document, "growthFactor",
				emitter.growthFactor));
		root.appendChild(createValueElement(document, "gravityFactor",
				emitter.gravityFactor));
		root.appendChild(createValueElement(document, "windFactor",
				emitter.windFactor));
		root.appendChild(createValueElement(document, "startAlpha",
				emitter.startAlpha));
		root.appendChild(createValueElement(document, "endAlpha",
				emitter.endAlpha));
		root.appendChild(createValueElement(document, "alpha", emitter.alpha));
		root.appendChild(createValueElement(document, "size", emitter.size));
		root.appendChild(createValueElement(document, "velocity",
				emitter.velocity));
		root
				.appendChild(createValueElement(document, "scaleY",
						emitter.scaleY));

		Element color = document.createElement("color");
		ArrayList list = emitter.colors;
		for (int i = 0; i < list.size(); i++) {
			ColorRecord record = (ColorRecord) list.get(i);
			Element step = document.createElement("step");
			step.setAttribute("offset", "" + record.pos);
			step.setAttribute("r", "" + record.col.r);
			step.setAttribute("g", "" + record.col.g);
			step.setAttribute("b", "" + record.col.b);

			color.appendChild(step);
		}

		root.appendChild(color);

		return root;
	}

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


Question: Finds an "if" expression as a statement

def find_if_expression_as_statement(node):
    """"""
    return (
        isinstance(node, ast.Expr)
        and isinstance(node.value, ast.IfExp)
    )

public function getMatches(VerbalExpression $verbalExpression, $test)
    {
        $matches = array();

        preg_match($verbalExpression, $test, $matches);

        return $matches;
    }

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


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

public EClass getIfcConnectionCurveGeometry() {
		if (ifcConnectionCurveGeometryEClass == null) {
			ifcConnectionCurveGeometryEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(101);
		}
		return ifcConnectionCurveGeometryEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question: // Connect returns the runhcs shim information

func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {
	log.G(ctx).Debugf("Connect: %s", r.ID)

	var taskpid uint32
	p, _ := s.getProcess(r.ID, "")
	if p != nil {
		taskpid = p.stat().pid
	}

	return &taskAPI.ConnectResponse{
		ShimPid: uint32(os.Getpid()),
		TaskPid: taskpid,
		Version: runhcsShimVersion,
	}, nil
}

func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err error) {
	if prefix == "" {
		prefix = os.Args[0]
	}
	var conn serverConn
	if network == "" {
		conn, err = unixSyslog()
	} else {
		var c net.Conn
		c, err = net.Dial(network, raddr)
		conn = netConn{c}
	}
	return &Writer{priority, prefix, conn}, err
}

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


Question:
// Try parsing the date based on the layouts defined in RFC 5322, section 3.3.
// Inspired by https://github.com/golang/go/blob/master/src/net/mail/message.go

func parseMessageDateTime(maybeDate string) (time.Time, error) {
	for _, layout := range envelopeDateTimeLayouts {
		parsed, err := time.Parse(layout, maybeDate)
		if err == nil {
			return parsed, nil
		}
	}
	return time.Time{}, fmt.Errorf("date %s could not be parsed", maybeDate)
}

func NewSingleEmail(from *Email, subject string, to *Email, plainTextContent string, htmlContent string) *SGMailV3 {
	plainText := NewContent("text/plain", plainTextContent)
	html := NewContent("text/html", htmlContent)
	return NewV3MailInit(from, subject, to, plainText, html)
}

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


Question:
@param $publicationDate

@throws VideoItemException

@return $this

public function setPublicationDate($publicationDate)
    {
        self::writeFullTag(
            $publicationDate,
            'publication_date',
            true,
            'video:publication_date',
            $this->validator,
            'validatePublicationDate',
            $this->exception,
            'Provided publication date value is not a valid.'
        );

        return $this;
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
Append nodes after this node.

        If nodes contains ``str``, it will be converted to Text node.

def after(self, *nodes: Union[AbstractNode, str]) -> None:

        if self.parentNode:
            node = _to_node_list(nodes)
            _next_node = self.nextSibling
            if _next_node is None:
                self.parentNode.appendChild(node)
            else:
                self.parentNode.insertBefore(node, _next_node)

public function add(string $word): self {
        // 构建临时树
        $tmp_tree = &$this->tmp_tree;
        foreach ($this->split($word) as $char) {
            // 加入索引
            $code = $this->index($char);

            // 插树
            $tmp_tree = &$this->putNode($code, $tmp_tree);

            // 抛弃无用词条
            if ($tmp_tree == $this->tmp_tree) {
                break;
            }
        }

        // 修剪trie树，抛弃无用词条
        $tmp_tree && $tmp_tree != $this->tmp_tree && $tmp_tree = [];

        return $this;
    }

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


Question: // SetAccountId sets the AccountId field's value.

func (s *UpdateAccountSettingsInput) SetAccountId(v string) *UpdateAccountSettingsInput {
	s.AccountId = &v
	return s
}

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

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

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


Question: // GetObjectType returns the ObjectType field if it's non-nil, zero value otherwise.

func (t *TextMatch) GetObjectType() string {
	if t == nil || t.ObjectType == nil {
		return ""
	}
	return *t.ObjectType
}

function (obj) {
            return vQ.isArray(obj) || !vQ.isFunction(obj) &&
                ( obj.length === 0 || typeof obj.length === 'number' && obj.length > 0 && ( obj.length - 1 ) in obj );
        }

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


Question:
Checks if any parsing method should be appended to the
Tags content.

@param Tag &$Tag a Tag instance.

@return string the tags content.

public static function parse(Tag &$Tag)
    {
        if (!empty($Tag->content) && $Tag->hasOption('translate') && is_callable(Config::get('translator'))) {
            $Tag->content = call_user_func_array(
                Config::get('translator'),
                array(
                    $Tag->content,
                    Config::get('textdomain')
                )
            );
        }

        if ($Tag->hasOption('bbContent')) {
            self::bb($Tag->content);
        }

        if ($Tag->hasOption('markdown')) {
            $Tag->addOption('cleanContent');
            self::markdown($Tag->content);
        }

        if ($Tag->hasOption('compress')) {
            self::compress($Tag);
        }

        return $Tag->content;
    }

public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, S style, PS paragraphStyle) {
        return addPar(new Paragraph<>(argumentOrDefault(paragraphStyle), segmentOps, segment, style));
    }

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


Question:
// getBuildModule returns the build info of Caddy
// from debug.BuildInfo (requires Go modules). If
// no version information is available, a non-nil
// value will still be returned, but with an
// unknown version.

func getBuildModule() *debug.Module {
	bi, ok := debug.ReadBuildInfo()
	if ok {
		// The recommended way to build Caddy involves
		// creating a separate main module, which
		// preserves caddy a read-only dependency
		// TODO: track related Go issue: https://github.com/golang/go/issues/29228
		for _, mod := range bi.Deps {
			if mod.Path == "github.com/mholt/caddy" {
				return mod
			}
		}
	}
	return &debug.Module{Version: "unknown"}
}

def versions_available(self):

        if self.version:
            spec = "%s==%s" % (self.project_name, self.version)
        else:
            spec = self.project_name

        if self.all_versions and self.version in self.all_versions:
            print_pkg_versions(self.project_name, [self.version])
        elif not self.version and self.all_versions:
            print_pkg_versions(self.project_name, self.all_versions)
        else:
            if self.version:
                self.logger.error("No pacakge found for version %s" \
                        % self.version)
            else:
                self.logger.error("No pacakge found for %s" % self.project_name)
            return 1
        return 0

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


Question:
// Branch wraps the state model branch method,
// returning the locally defined Generation interface.

func (g *modelShim) Branch(name string) (Generation, error) {
	m, err := g.Model.Branch(name)
	return m, errors.Trace(err)
}

public function section($name, $class = null)
    {
        /** @var \Foil\Contracts\SectionInterface $section */
        $section = $this->factory->factory($name, $this->mode(), $class);
        $section->start();
        $this->stack->push($section);
        $this->names->push($name);
    }

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


Question:
Get index of array member with specified key

@param array $array
@param string $key
@param mixed $value

@return false|int|string

public function key_search( array $array, $key, $value ) {
		foreach ( $array as $key => $a ) {
			if ( isset( $a[ $key ] ) && $a[ $key ] == $value ) {
				return $key;
			}
		}

		return false;
	}

private static int getIndexOfPair(String value, Map<Integer, String> row_data) {
        for(Integer i : row_data.keySet()) {
            if(row_data.get(i).equals(value)) {
                return i.intValue();
            }
        }
        return -1;
    }

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


Question:
Calculate the total size of the workUnits and set the estimated size for each workUnit
@param workUnitsByTopic
@return the total size of the input workUnits

public double setWorkUnitEstSizes(Map<String, List<WorkUnit>> workUnitsByTopic) {
    double totalEstDataSize = 0;
    for (List<WorkUnit> workUnitsForTopic : workUnitsByTopic.values()) {
      for (WorkUnit workUnit : workUnitsForTopic) {
        setWorkUnitEstSize(workUnit);
        totalEstDataSize += getWorkUnitEstSize(workUnit);
      }
    }
    return totalEstDataSize;
  }

def declare_units(out_units, **units_by_name):
    """"""

    def dec(func):
        # Match the signature of the function to the arguments given to the decorator
        sig = signature(func)
        bound_units = sig.bind_partial(**units_by_name)

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # Match all passed in value to their proper arguments so we can check units
            bound_args = sig.bind(*args, **kwargs)
            for name, val in bound_args.arguments.items():
                _check_units(val, bound_units.arguments.get(name, None))

            out = func(*args, **kwargs)

            # In the generic case, we use the default units that should have been propagated by the computation.
            if '[' in out_units:
                _check_units(out, out_units)

            # Otherwise, we specify explicitly the units.
            else:
                out.attrs['units'] = out_units
            return out

        return wrapper

    return dec

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


Question:
Get List view data

@param int $start
@param int $rowPerPage
@param string $keyword
@param string $sortField
@param string $sortOrder ASC/DESC
@return array List of beans
@throws \RedBeanPHP\RedException\SQL

protected function getListViewData($start = null, $rowPerPage = null, $keyword = null, $sortField = null, $sortOrder = null) {
        $list = [];

        if ($this->listViewDataClosure != null) {
            $c = $this->listViewDataClosure;
            $list = $c($start, $rowPerPage, $keyword, $sortField, $sortOrder);

        } elseif ($keyword != null && trim($keyword) != "" && $this->searchClosure != null) {         // For Custom Searching
            $c = $this->searchClosure;
            $list = $c($start, $rowPerPage, $keyword, $sortField, $sortOrder);

        } else {
            $this->beforeGetListViewData(function ($tableName, $findClause, $limit, $bindingData) use (&$list) {

                // For RedBean Case
                $list = R::find($tableName, $findClause . $limit, $bindingData);

            }, function ($sql, $limit, $bindingData) use (&$list) {

                // For SQL Case
                $list = R::getAll($sql . $limit, $bindingData);

                try {
                    $list = R::convertToBeans($this->tableName, $list);
                } catch (\Exception $ex) {

                }

            }, $start, $rowPerPage, $keyword, $sortField, $sortOrder);
        }

        return $list;
    }

def order_search_results(query, search_results):

    results = search_results

    results_names = []
    old_query = query
    query = query.split(' ')

    first_word = ''
    second_word = ''
    third_word = ''

    if(len(query) < 2):
        first_word = old_query
    else:
        first_word = query[0]
        second_word = query[1]

        if(len(query) > 2):
            third_word = query[2]

    # save results for multiple passes
    results_second = []
    results_third = []

    for result in results:

        result_list = result.split(' ')

        try:
            if(result_list[0].startswith(first_word)):
                results_names.append(result)
            else:
                results_second.append(result)
        except:
            results_second.append(result)

    for result in results_second:

        result_list = result.split(' ')

        try:
            if(result_list[1].startswith(first_word)):
                results_names.append(result)
            else:
                results_third.append(result)
        except:
            results_third.append(result)

    # results are either in results_names (filtered)
    # or unprocessed in results_third (last pass)
    return results_names + results_third

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


Question:
Authenticate with the server.

@param $password

@throws Exception\AuthenticationFailedException

protected function authenticate($password)
    {
        $message = new Message($password, Message::TYPE_AUTH);
        $response = $this->sendMessage($message);

        if ($response->getType() === Message::TYPE_AUTH_FAILURE) {
            throw new AuthenticationFailedException('Could not authenticate to the server.');
        }
    }

public function execute(Input $input, Output $output)
    {
        $connector = $input->getArgument('connector') ?: $this->app->config->get('queue.connector', 'sync');

        $queue = $input->getOption('queue') ?: $this->app->config->get("queue.{$connector}", 'default');
        $delay = $input->getOption('delay');
        $sleep = $input->getOption('sleep');
        $tries = $input->getOption('tries');

        $this->listenForEvents();

        if ($input->getOption('once')) {
            $this->worker->runNextJob($connector, $queue, $delay, $sleep, $tries);
        } else {
            $memory  = $input->getOption('memory');
            $timeout = $input->getOption('timeout');
            $this->worker->daemon($connector, $queue, $delay, $sleep, $tries, $memory, $timeout);
        }
    }

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


Question:
Sets a list of acceptable HTTP method for this route to match.

@param array $acceptableMethods

public function setAcceptableMethods(array $acceptableMethods)
    {
        $this->acceptableMethods = $acceptableMethods;

        $this->addConstraint(function (Request $request) use ($acceptableMethods) {
            return in_array($request->getMethod(), $acceptableMethods);
        });
    }

public function any( $uri, $action = null )
	{
		$verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];

		return $this->addRoute( $verbs, $uri, $action );
	}

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


Question:
// CopyObjectPart creates a part in a multipart upload by copying
// existing object or a part of it.

func (l *ossObjects) CopyObjectPart(ctx context.Context, srcBucket, srcObject, destBucket, destObject, uploadID string,
	partID int, startOffset, length int64, srcInfo minio.ObjectInfo, srcOpts, dstOpts minio.ObjectOptions) (p minio.PartInfo, err error) {

	bkt, err := l.Client.Bucket(destBucket)
	if err != nil {
		logger.LogIf(ctx, err)
		return p, ossToObjectError(err, destBucket)
	}

	// Build OSS metadata
	opts, err := appendS3MetaToOSSOptions(ctx, nil, srcInfo.UserDefined)
	if err != nil {
		return p, ossToObjectError(err, srcBucket, srcObject)
	}

	completePart, err := bkt.UploadPartCopy(oss.InitiateMultipartUploadResult{
		Key:      destObject,
		UploadID: uploadID,
	}, srcBucket, srcObject, startOffset, length, partID, opts...)

	if err != nil {
		logger.LogIf(ctx, err)
		return p, ossToObjectError(err, srcBucket, srcObject)
	}

	p.PartNumber = completePart.PartNumber
	p.ETag = minio.ToS3ETag(completePart.ETag)
	return p, nil
}

public function setFile($file, $sourceFile = null) {
        if (!$file instanceof File) {
            $file = new File($file);
        }
        $this->file = $file;
        $this->sourceFile = empty($sourceFile) ? $file : $sourceFile;
        return $this;
    }

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


Question: //set the unit with hour, which interval is 1

func (j *Job) Hour() (job *Job) {
	if j.interval != 1 {
		panic("")
	}
	job = j.Hours()
	return
}

func (h *Timing) ContentLoadTime(contentLoadTime int64) *Timing {
	h.contentLoadTime = contentLoadTime
	h.contentLoadTimeSet = true
	return h
}

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


Question:
Delete the RTree Index extension for the table and geometry column. Drops
the triggers, RTree table, and deletes the extension.

@param tableName
table name
@param geometryColumnName
geometry column name

public void delete(String tableName, String geometryColumnName) {

		if (has(tableName, geometryColumnName)) {
			drop(tableName, geometryColumnName);

			try {
				extensionsDao.deleteByExtension(EXTENSION_NAME, tableName,
						geometryColumnName);
			} catch (SQLException e) {
				throw new GeoPackageException(
						"Failed to delete RTree Index extension. GeoPackage: "
								+ geoPackage.getName() + ", Table: "
								+ tableName + ", Geometry Column: "
								+ geometryColumnName, e);
			}
		}

	}

def makeLys(segID, N, CA, C, O, geo):
    ''''''
    ##R-Group
    CA_CB_length=geo.CA_CB_length
    C_CA_CB_angle=geo.C_CA_CB_angle
    N_C_CA_CB_diangle=geo.N_C_CA_CB_diangle

    CB_CG_length=geo.CB_CG_length
    CA_CB_CG_angle=geo.CA_CB_CG_angle
    N_CA_CB_CG_diangle=geo.N_CA_CB_CG_diangle

    CG_CD_length=geo.CG_CD_length
    CB_CG_CD_angle=geo.CB_CG_CD_angle
    CA_CB_CG_CD_diangle=geo.CA_CB_CG_CD_diangle

    CD_CE_length=geo.CD_CE_length
    CG_CD_CE_angle=geo.CG_CD_CE_angle
    CB_CG_CD_CE_diangle=geo.CB_CG_CD_CE_diangle

    CE_NZ_length=geo.CE_NZ_length
    CD_CE_NZ_angle=geo.CD_CE_NZ_angle
    CG_CD_CE_NZ_diangle=geo.CG_CD_CE_NZ_diangle

    carbon_b= calculateCoordinates(N, C, CA, CA_CB_length, C_CA_CB_angle, N_C_CA_CB_diangle)
    CB= Atom("CB", carbon_b, 0.0 , 1.0, " "," CB", 0,"C")
    carbon_g= calculateCoordinates(N, CA, CB, CB_CG_length, CA_CB_CG_angle, N_CA_CB_CG_diangle)
    CG= Atom("CG", carbon_g, 0.0, 1.0, " ", " CG", 0, "C")
    carbon_d= calculateCoordinates(CA, CB, CG, CG_CD_length, CB_CG_CD_angle, CA_CB_CG_CD_diangle)
    CD= Atom("CD", carbon_d, 0.0, 1.0, " ", " CD", 0, "C")
    carbon_e= calculateCoordinates(CB, CG, CD, CD_CE_length, CG_CD_CE_angle, CB_CG_CD_CE_diangle)
    CE= Atom("CE", carbon_e, 0.0, 1.0, " ", " CE", 0, "C")
    nitrogen_z= calculateCoordinates(CG, CD, CE, CE_NZ_length, CD_CE_NZ_angle, CG_CD_CE_NZ_diangle)
    NZ= Atom("NZ", nitrogen_z, 0.0, 1.0, " ", " NZ", 0, "N")

    ##Create Residue Data Structure
    res= Residue((' ', segID, ' '), "LYS", '    ')
    res.add(N)
    res.add(CA)
    res.add(C)
    res.add(O)
    res.add(CB)
    res.add(CG)
    res.add(CD)
    res.add(CE)
    res.add(NZ)
    return res

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


Question: // Get finds the Source by id among all contained Stores

func (multi *SourcesStore) Get(ctx context.Context, id int) (chronograf.Source, error) {
	var err error
	for _, store := range multi.Stores {
		var s chronograf.Source
		s, err = store.Get(ctx, id)
		if err == nil {
			return s, nil
		}
	}
	return chronograf.Source{}, err
}

func (l *State) RawGet(index int) {
	t := l.indexToValue(index).(*table)
	l.stack[l.top-1] = t.at(l.stack[l.top-1])
}

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


Question:
Loads all the configurations from a specific environment.

@param string $environment Environment name.

@return ConfigObject
@throws \Webiny\Component\Config\ConfigException

private function loadConfigurations($environment)
    {
        $configs = new ConfigObject([]);
        $configFolder = $this->applicationAbsolutePath . 'App/Config/' . $environment;
        $h = scandir($configFolder);

        foreach ($h as $configFile) {
            if (strpos($configFile, 'yaml') === false) {
                continue;
            }

            $configs->mergeWith($this->config()->yaml($configFolder . DIRECTORY_SEPARATOR . $configFile));
        }

        return $configs;
    }

public function withEnv(string $name, string $value): self
    {
        $builder = clone $this;
        $builder->env[$name] = $value;

        return $builder;
    }

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


Question: A form containing a single input field with an appended Button

function FormWithSingleInputAndButton({
  formProps,
  inputProps,
  buttonProps,
}: Props): React.Node {
  const button = React.createElement(Button, buttonProps);
  return (
    <Form {...formProps}>
      <Form.InputGroup inputProps={inputProps} append={button} />
    </Form>
  );
}

def on_btn_delete_fit(self, event):

        self.delete_fit(self.current_fit, specimen=self.s)

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


Question:
// EqJoin is an efficient join that looks up elements in the right table by primary key.
//
// Optional arguments: "index" (string - name of the index to use in right table instead of the primary key)

func (t Term) EqJoin(left, right interface{}, optArgs ...EqJoinOpts) Term {
	opts := map[string]interface{}{}
	if len(optArgs) >= 1 {
		opts = optArgs[0].toMap()
	}
	return constructMethodTerm(t, "EqJoin", p.Term_EQ_JOIN, []interface{}{funcWrap(left), right}, opts)
}

public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }

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


Question:
// BtcDecode decodes r using the bitcoin protocol encoding into the receiver.
// This is part of the Message interface implementation.

func (msg *MsgCFCheckpt) BtcDecode(r io.Reader, pver uint32, _ MessageEncoding) error {
	// Read filter type
	err := readElement(r, &msg.FilterType)
	if err != nil {
		return err
	}

	// Read stop hash
	err = readElement(r, &msg.StopHash)
	if err != nil {
		return err
	}

	// Read number of filter headers
	count, err := ReadVarInt(r, pver)
	if err != nil {
		return err
	}

	// Refuse to decode an insane number of cfheaders.
	if count > maxCFHeadersLen {
		return ErrInsaneCFHeaderCount
	}

	// Create a contiguous slice of hashes to deserialize into in order to
	// reduce the number of allocations.
	msg.FilterHeaders = make([]*chainhash.Hash, count)
	for i := uint64(0); i < count; i++ {
		var cfh chainhash.Hash
		err := readElement(r, &cfh)
		if err != nil {
			return err
		}
		msg.FilterHeaders[i] = &cfh
	}

	return nil
}

private function decryptPrivate($data)
    {
        if (!openssl_private_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
            throw new Exception('Failure decrypting Data (openssl private) - ' . openssl_error_string());
        }
        return $decrypted;
    }

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


Question:
/*
内部公共方法, 发送消息

@param  string  $req

private static function parseRequest($req)
    {
        $rsp = HttpClient::sendRequest($req);

        if ($rsp === false) {
            return array(
                'code'      => Response::COSAPI_NETWORK_ERROR,
                'message'   => 'network error',
            );
        }

        $info = HttpClient::info();
        $ret = json_decode($rsp, true);

        if ($ret === NULL) {
            return array(
                'code'      => Response::COSAPI_NETWORK_ERROR,
                'message'   => $rsp,
                'data'      => array()
            );
        }

        return $ret;
    }

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

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

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


Question:
Recursively finds all files with the .php extension in the provided
$path adds them to $this->files.
@param  string $path Path in which to look for .php files.
@return void

private function getPhpFilesFromPath(string $path)
    {
        $directoryIterator = new RecursiveDirectoryIterator($path);
        foreach (new RecursiveIteratorIterator($directoryIterator) as $file) {
            if (! in_array($file->getExtension(), $this->fileExtensions)) {
                continue;
            }

            if ($this->fileShouldBeIgnored($file)) {
                continue;
            }

            $this->files->push(new File(['displayPath' => $file->getPathName(), 'fullPath' => $file->getRealPath()]));
        }
    }

public static function load($pClassName)
    {
        if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
            // Either already loaded, or not a PHPExcel class request
            return false;
        }

        $pClassFilePath = PHPEXCEL_ROOT .
            str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
            '.php';

        if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
            // Can't load
            return false;
        }

        require($pClassFilePath);
    }

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


Question:
Compile an express helper into PHP code.

@param ExpressCompiler $compiler
@param integer $flags Direct ouput of helper? Not needed for child nodes of composite helpers.
@return string Returns the variable field accessor of this helper ($this->helper).

public function compile(ExpressCompiler $compiler, $flags = 0)
	{
		try
		{
			$helper = $this->getHelper($compiler);
			$field = $compiler->nextField('h');

			$compiler->write("\t\t" . 'if(' . $field . ' === NULL) {' . "\n");

			$compiler->write("\t\ttry {\n");

			$compiler->write("\t\t" . $field . ' = $this->renderer->getHelper(');
			$compiler->write(var_export($this->namespace, true) . ', ' . var_export($this->name, true));
			$compiler->write(");\n");
			$compiler->write("\t\t" . $field . "->bindContext(\$this->context);\n");

			$bound = [];

			// Setup helper arguments:
			foreach($this->attributes as $attr)
			{
				$name = preg_replace_callback("'-([a-z0-9])'", function(array $m) {
					return strtoupper($m[1]);
				}, $attr->getName());

				if(false !== strpos($name, ':'))
				{
					continue;
				}

				$dynamic = $attr->isExpressionCallback() || $attr->isDynamic();
				$pass = $helper->isPassthroughAttribute($name);

				$bound[$name] = true;

				if($pass)
				{
					// Dealing with passthrough attributes.

					if($dynamic)
					{
						// Dynamic value passthrough attribute, use ArrayAccess to set compiled closure.

						$compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true));
						$compiler->write("] = function() {\n\t\t\ttry {\n\t\t\treturn ");

						$exp = '';

						foreach($attr as $i => $sub)
						{
							if($i != 0)
							{
								$compiler->write(' . ');
							}

							$compiler->write($sub->compile($compiler, self::FLAG_RAW));

							if($sub instanceof ExpressionNode)
							{
								$exp .= $sub->getExpression();
							}
							elseif($sub instanceof TextNode)
							{
								$exp .= $sub->getText();
							}
						}

						$compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n");
						$compiler->write("\t\t\t\tthrow \$ex;\n");
						$compiler->write("\t\t\t} catch(\Exception \$ex) {\n");
						$compiler->write("\t\t\t\tthrow new ExpressViewException(");
						$compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true));
						$compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n");
						$compiler->write("\t\t\t}\n\t\t};\n");
					}
					else
					{
						// Static passthrough attribute.

						$sub = $compiler->createCompiler();
						$attr->compile($sub);

						$compiler->write("\t\t" . $field . "[" . var_export($attr->getName(), true));
						$compiler->write("] = " . var_export($sub->getOutputBuffer(), true) . ";\n");
					}
				}
				else
				{
					if($dynamic)
					{
						// Dynamic and expression attributes are assembled into a string and returned:

						$compiler->write("\t\t" . $field . '->setAttr(' . var_export($name, true));
						$compiler->write(", function(\$inspect = false) {\n\t\t\ttry {\n\t\t\treturn ");

						$childNodes = iterator_to_array($attr->getIterator());
						$inspectable = false;
						$exp = '';

						if(count($childNodes) == 1)
						{
							if($childNodes[0] instanceof ExpressionNode)
							{
								$chain = $childNodes[0]->getExpression()->getNode();

								if($chain instanceof AccessorChain)
								{
									$inspectable = true;
								}
							}
						}

						if($inspectable)
						{
							$compiler->write('$inspect ? ');
							$compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp', 'inspectValue'));
							$compiler->write(' : ');
							$compiler->write($chain->compile($compiler->getExpressionContextFactory(), '$this->exp'));

							$exp .= $childNodes[0]->getExpression();
						}
						else
						{
							foreach($childNodes as $i => $sub)
							{
								if($i != 0)
								{
									$compiler->write(' . ');
								}

								$compiler->write($sub->compile($compiler, self::FLAG_RAW));

								if($sub instanceof ExpressionNode)
								{
									$exp .= $sub->getExpression();
								}
								elseif($sub instanceof TextNode)
								{
									$exp .= $sub->getText();
								}
							}
						}

						$compiler->write(";\n\t\t\t} catch(\ExpressViewException \$ex) {\n");
						$compiler->write("\t\t\t\tthrow \$ex;\n");
						$compiler->write("\t\t\t} catch(\Exception \$ex) {\n");
						$compiler->write("\t\t\t\tthrow new ExpressViewException(");
						$compiler->write(var_export(sprintf('Unable to evaluate attribute "%s" in view helper "%s" using expression "%s"', $name, $this->namespace . ':' . $this->name, $exp), true));
						$compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n");
						$compiler->write("\t\t\t}\n\t\t});\n");
					}
					else
					{
						// Static attributes are set as property values:

						$sub = $compiler->createCompiler();
						$attr->compile($sub);

						$compiler->write("\t\t" . $field . '->' . $name . ' = ');
						$compiler->write(var_export($sub->getOutputBuffer(), true) . ";\n");
					}
				}
			}

			$compiler->write("\t\t" . $field . "->bindAttr([");

			foreach(array_keys($bound) as $i => $key)
			{
				if($i != 0)
				{
					$compiler->write(', ');
				}

				$compiler->write(var_export($key, true) . ' => true');
			}

			$compiler->write("]);\n");

			if(!empty($this->childNodes))
			{
				if($helper instanceof CompositeViewHelperInterface)
				{
					$helpers = [];

					foreach($this->childNodes as $node)
					{
						if(!$node instanceof HelperNode)
						{
							continue;
						}

						$helpers[] = $node->compile($compiler, self::FLAG_NO_OUTPUT);
					}

					$compiler->write("\t\t" . $field . '->setNestedNodes([' . "\n");
					$compiler->write("\t\t" . implode(', ', $helpers) . "\n");
					$compiler->write("\t\t]);\n");
				}
				else
				{
					$compiler->write("\t\t" . $field . '->setNestedNodes([function(OutputBuffer $out) {' . "\n");

					foreach($this->childNodes as $node)
					{
						$node->compile($compiler);
					}

					$compiler->write("\n\t\t}]);\n");
				}
			}

			$compiler->write("\t\t} catch(ExpressViewException \$ex) {\n");
			$compiler->write("\t\t\tthrow \$ex;\n");
			$compiler->write("\t\t} catch(\\Exception \$ex) {\n");
			$compiler->write("\t\t\tthrow new ExpressViewException(");
			$compiler->write(var_export('Unable to instantiate view helper "' . $this->namespace . ':' . $this->name . '"', true));
			$compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n");
			$compiler->write("\t\t}\n");

			$compiler->write("\t\t}\n");

			if(!($flags & self::FLAG_NO_OUTPUT))
			{
				$compiler->write("\t\ttry {\n");
				$compiler->write("\t\t" . $field . '->__invoke($out);' . "\n");
				$compiler->write("\t\t} catch(ExpressViewException \$ex) {\n");
				$compiler->write("\t\t\tthrow \$ex;\n");
				$compiler->write("\t\t} catch(\\Exception \$ex) {\n");
				$compiler->write("\t\t\tthrow new ExpressViewException(");
				$compiler->write(var_export('Unable to invoke view helper "' . $this->namespace . ':' . $this->name . '"', true));
				$compiler->write(", \$this->getResource(), {$this->line}, \$ex);\n");
				$compiler->write("\t\t}\n");
			}

			return $field;
		}
		catch(ExpressViewException $e)
		{
			throw $e;
		}
		catch(\Exception $e)
		{
			throw new ExpressViewException(sprintf('Unable to compile view helper "%s" in namespace "%s"', $this->name, $this->namespace), $compiler->getResource(), $this->line, $e);
		}
	}

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Create a {@link URI} with scheme and host.

@param scheme
the scheme
@param host
the host
@return the {@link URI}
@throws IllegalArgumentException
If the given string not parsable

public static URI createUri(final String scheme, final String host) {
        final boolean isIpV6 = host.indexOf(':') >= 0 && host.charAt(0) != '[';
        if (isIpV6) {
            return URI.create(scheme + SCHEME_SEPERATOR + "[" + host + "]");
        }
        return URI.create(scheme + SCHEME_SEPERATOR + host);
    }

public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
            protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
            protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
            protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
            protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
            protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
            protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
            protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns a determined button to be able to configure it

@param string $buttonName

@return AjaxViewButton

public function getButton($buttonName)
    {
        if (isset($this->buttons[$buttonName])) {
            return $this->buttons[$buttonName];
        }
        else {
            throw new AjaxModalsException("Button $buttonName does not exists.");
        }
    }

function btnOnClick(e, opts, callback, target, k) {
        var that = void 0;
        if (e.srcElement) e.target = e.srcElement;

        target = U.findParentNode(e.target, function (target) {
          if (target.getAttribute("data-modal-header-btn")) {
            return true;
          }
        });

        if (target) {
          k = target.getAttribute("data-modal-header-btn");

          that = {
            self: this,
            key: k,
            value: opts.header.btns[k],
            dialogId: opts.id,
            btnTarget: target
          };

          if (opts.header.btns[k].onClick) {
            opts.header.btns[k].onClick.call(that, k);
          }
        }

        that = null;
        opts = null;
        callback = null;
        target = null;
        k = null;
      }

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


Question: // ValidateCluster runs our validation methods on the K8s Cluster.

func (r *RollingUpdateInstanceGroup) ValidateCluster(rollingUpdateData *RollingUpdateCluster, cluster *api.Cluster, instanceGroupList *api.InstanceGroupList) error {
	if _, err := validation.ValidateCluster(cluster, instanceGroupList, rollingUpdateData.K8sClient); err != nil {
		return fmt.Errorf("cluster %q did not pass validation: %v", cluster.Name, err)
	}

	return nil

}

public static JAASSystem getJAASSystem(final String _name)
        throws CacheReloadException
    {
        final Cache<String, JAASSystem> cache = InfinispanCache.get()
                        .<String, JAASSystem>getCache(JAASSystem.NAMECACHE);
        if (!cache.containsKey(_name)) {
            JAASSystem.getJAASSystemFromDB(JAASSystem.SQL_NAME, _name);
        }
        return cache.get(_name);
    }

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


Question: 7.1.4. The WebSocket Connection is Closed.

def connection_lost(self, exc: Optional[Exception]) -> None:

        logger.debug("%s - event = connection_lost(%s)", self.side, exc)
        self.state = State.CLOSED
        logger.debug("%s - state = CLOSED", self.side)
        if not hasattr(self, "close_code"):
            self.close_code = 1006
        if not hasattr(self, "close_reason"):
            self.close_reason = ""
        logger.debug(
            "%s x code = %d, reason = %s",
            self.side,
            self.close_code,
            self.close_reason or "[no reason]",
        )
        self.abort_keepalive_pings()
        # If self.connection_lost_waiter isn't pending, that's a bug, because:
        # - it's set only here in connection_lost() which is called only once;
        # - it must never be canceled.
        self.connection_lost_waiter.set_result(None)
        super().connection_lost(exc)

public function onSwooleWSClose($serv, $fd)
    {
        unset($this->fdRequest[$fd]);
        $this->portManager->eventClose($fd);
    }

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


Question: // Set saves the value string to the session pointed to by the session id key.

func (d *DiskStorer) Set(key, value string) error {
	if !validKey(key) {
		return errNoSession{}
	}

	filePath := path.Join(d.folderPath, key)

	d.mut.Lock()
	defer d.mut.Unlock()

	return ioutil.WriteFile(filePath, []byte(value), 0600)
}

private Entity<? extends Serializable> onAfterSave(
			Entity<? extends Serializable> entity) {
		Class<?> cls = entity.getClass();
		if (Treeable.class.isAssignableFrom(cls)) {
			Treeable self = (Treeable) entity;
			if (notNull(self.getParent())) {
				Treeable parent = (Treeable) getCurrentSession().get(cls,
						self.getParent());
				self.setPath(parent.getPath() + entity.getId().toString() + "/");
				getCurrentSession().update(self);
			}
		}
		return entity;
	}

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