Question: Preparing SQL scripts for database initialization.

private static String prepareScripts(String initScriptPath, String itemTableSuffix, String valueTableSuffix,
      String refTableSuffix, boolean isolatedDB) throws IOException
   {
      String scripts = IOUtil.getStreamContentAsString(PrivilegedFileHelper.getResourceAsStream(initScriptPath));

      if (isolatedDB)
      {
         scripts =
            scripts.replace("MITEM", itemTableSuffix).replace("MVALUE", valueTableSuffix)
               .replace("MREF", refTableSuffix);
      }

      return scripts;
   }

def setConnStringForWindows():

    global _dbConnectString
    from peek_platform.file_config.PeekFileConfigABC import PeekFileConfigABC
    from peek_platform.file_config.PeekFileConfigSqlAlchemyMixin import \
        PeekFileConfigSqlAlchemyMixin
    from peek_platform import PeekPlatformConfig

    class _WorkerTaskConfigMixin(PeekFileConfigABC,
                           PeekFileConfigSqlAlchemyMixin):
        pass

    PeekPlatformConfig.componentName = peekWorkerName

    _dbConnectString = _WorkerTaskConfigMixin().dbConnectString

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


Question:
// GetSchemaByID returns the Auro schema string identified by the id.
// id (int) – the globally unique identifier of the schema.

func (c *Client) GetSchemaByID(subjectID int) (string, error) {
	// # Get the schema for a particular subject id
	// GET /schemas/ids/{int: id}
	path := fmt.Sprintf(schemaPath, subjectID)
	resp, err := c.do(http.MethodGet, path, "", nil)
	if err != nil {
		return "", err
	}

	var res schemaOnlyJSON
	if err = c.readJSON(resp, &res); err != nil {
		return "", err
	}

	return res.Schema, nil
}

def identifier
      @identifier ||= begin
        uri = @representor_hash.href || self.object_id
        protocol = @representor_hash.protocol || (uri == self.object_id ? UNKNOWN_PROTOCOL : DEFAULT_PROTOCOL)
        PROTOCOL_TEMPLATE % [protocol, uri]
      end
    end

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


Question:
Sets the list of the filepaths for this widget to the inputed paths.

        :param      filepaths | [<str>, ..]

def setFilepaths(self, filepaths):

        self.setFilepath(os.path.pathsep.join(filepaths))

def cmd_all(args):
    """"""
    for penlist in penStore.data:
        puts(penlist)
        with indent(4, '  -'):
            for penfile in penStore.data[penlist]:
                puts(penfile)

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


Question: // Wipe resets the KeyValue by dropping and recreating the database tables.

func (kv *keyValue) Wipe() error {
	if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil {
		return err
	}
	if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil {
		return err
	}
	return kv.finalize()
}

public function update_timecheckstate($time) {
        global $DB;
        if ($this->attempt->timecheckstate !== $time) {
            $this->attempt->timecheckstate = $time;
            $DB->set_field('quiz_attempts', 'timecheckstate', $time, array('id' => $this->attempt->id));
        }
    }

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


Question:
Get the bandpass' pivot wavelength.

        Unlike calc_pivot_wavelength(), this function will use a cached
        value if available.

def pivot_wavelength(self):

        wl = self.registry._pivot_wavelengths.get((self.telescope, self.band))
        if wl is not None:
            return wl

        wl = self.calc_pivot_wavelength()
        self.registry.register_pivot_wavelength(self.telescope, self.band, wl)
        return wl

public static String stringFor(int n)
    {
        switch (n)
        {
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT_TILING";
            case CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT: return "CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT";
        }
        return "INVALID cudnnConvolutionBwdFilterAlgo: "+n;
    }

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


Question:
Create pymol session for each reasonable design representative.  This
    method was copied from an old version of this script, and does not
    currently work.

def report_pymol_sessions(designs, directory):

    print "Reporting pymol sessions..."

    if os.path.exists(directory): shutil.rmtree(directory)
    os.mkdir(directory)

    with open('pymol_modes.txt') as file:
        import yaml
        base_config = yaml.load_cell(file)['Present design in pymol']

    for design in designs:
        decoy = design.representative
        config = base_config + ' save ' + os.path.join(
                directory, design.get_fancy_path('.pse')) + ';'

        score_vs_distance.open_in_pymol(design, decoy, config, gui=False)

def injectable_repr(inj_name):

    i = orca.get_injectable(inj_name)
    return jsonify(type=str(type(i)), repr=repr(i))

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


Question: Extract database references for a TERM.

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

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

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

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

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

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

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

    return db_refs, ont_type, relevant_ambiguities

public function getTfIdf(DocumentAbstract $document, $token, $mode = 1)
    {
        return $this->getTermFrequency($document, $token, $mode) * $this->getIdf($token);
    }

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


Question:
Find all columns.

@param <E>
the element type
@param entityClass
the entity class
@param columns
the columns
@param keys
the keys
@return the list

private <E> List<E> findAllColumns(Class<E> entityClass, byte[][] columns, Object... keys)
    {
        Object connection = getConnection();
        // connection.co
        List results = new ArrayList();
        try
        {
            for (Object key : keys)
            {
                Object result = fetch(entityClass, key, connection, columns);
                if (result != null)
                {
                    results.add(result);
                }
            }
        }
        catch (InstantiationException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        catch (IllegalAccessException e)
        {
            logger.error("Error during find by key:", e);
            throw new PersistenceException(e);
        }
        return results;
    }

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: Formats coverage data as LCOV report.

function formatReport() { // eslint-disable-line no-unused-vars
  const lineCoverage = new LineCoverage(2, 2, [
    new LineData(6, 2, 'PF4Rz2r7RTliO9u6bZ7h6g'),
    new LineData(7, 2, 'yGMB6FhEEAd8OyASe3Ni1w')
  ]);

  const record = new Record('/home/cedx/lcov.js/fixture.js', {
    functions: new FunctionCoverage(1, 1),
    lines: lineCoverage
  });

  const report = new Report('Example', [record]);
  console.log(report.toString());
}

func Convert_kops_UserData_To_v1alpha2_UserData(in *kops.UserData, out *UserData, s conversion.Scope) error {
	return autoConvert_kops_UserData_To_v1alpha2_UserData(in, out, s)
}

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


Question:
Check if the current language is a valid language.

@param string $lang Language
@return mixed.

public function validLang($lang)
    {
        if (in_array($lang, $this->validLanguages)) {
            return $lang;
        }
        if ($this->defaultLanguage) {
            return $this->defaultLanguage;
        }
        return false;
    }

public function setMessages($locale, $messages)
    {
        $this->loadMessagesFromFile($locale);
        $this->addResource('array', $messages, $locale);
        $this->messages[$locale] = array_merge(
            isset($this->messages[$locale]) ? $this->messages[$locale] : [],
            $messages
        );

        return $this;
    }

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


Question:
revokes a lease. All keys attached to the lease will expire and be deleted.

@param int  $id ID is the lease ID to revoke. When the ID is revoked,
all associated keys will be deleted.
@return array
@throws \GuzzleHttp\Exception\BadResponseException

public function revoke($id)
    {
        $params = [
            'ID' => $id,
        ];

        $body = $this->request(self::URI_REVOKE, $params);

        return $body;
    }

public function parse(array $data, ParsingDispatcher $parsingDispatcher)
    {
        $contentType = null;
        if (array_key_exists('ContentType', $data) && is_array($data['ContentType'])) {
            if (!array_key_exists('_href', $data['ContentType'])) {
                throw new Exceptions\Parser("Missing '_href' attribute for ContentType element in UserCreate.");
            }

            $contentType = $this->contentTypeService->loadContentType(
                $this->requestParser->parseHref($data['ContentType']['_href'], 'contentTypeId')
            );
        }

        if (!array_key_exists('mainLanguageCode', $data)) {
            throw new Exceptions\Parser("Missing 'mainLanguageCode' element for UserCreate.");
        }

        if (!array_key_exists('login', $data)) {
            throw new Exceptions\Parser("Missing 'login' element for UserCreate.");
        }

        if (!array_key_exists('email', $data)) {
            throw new Exceptions\Parser("Missing 'email' element for UserCreate.");
        }

        if (!array_key_exists('password', $data)) {
            throw new Exceptions\Parser("Missing 'password' element for UserCreate.");
        }

        $userCreateStruct = $this->userService->newUserCreateStruct(
            $data['login'],
            $data['email'],
            $data['password'],
            $data['mainLanguageCode'],
            $contentType
        );

        if (array_key_exists('Section', $data) && is_array($data['Section'])) {
            if (!array_key_exists('_href', $data['Section'])) {
                throw new Exceptions\Parser("Missing '_href' attribute for Section element in UserCreate.");
            }

            $userCreateStruct->sectionId = $this->requestParser->parseHref($data['Section']['_href'], 'sectionId');
        }

        if (array_key_exists('remoteId', $data)) {
            $userCreateStruct->remoteId = $data['remoteId'];
        }

        if (array_key_exists('enabled', $data)) {
            $userCreateStruct->enabled = $this->parserTools->parseBooleanValue($data['enabled']);
        }

        if (!array_key_exists('fields', $data) || !is_array($data['fields']) || !is_array($data['fields']['field'])) {
            throw new Exceptions\Parser("Missing or invalid 'fields' element for UserCreate.");
        }

        foreach ($data['fields']['field'] as $fieldData) {
            if (!array_key_exists('fieldDefinitionIdentifier', $fieldData)) {
                throw new Exceptions\Parser("Missing 'fieldDefinitionIdentifier' element in field data for UserCreate.");
            }

            $fieldDefinition = $userCreateStruct->contentType->getFieldDefinition($fieldData['fieldDefinitionIdentifier']);
            if (!$fieldDefinition) {
                throw new Exceptions\Parser(
                    "'{$fieldData['fieldDefinitionIdentifier']}' is invalid field definition identifier for '{$userCreateStruct->contentType->identifier}' content type in UserCreate."
                );
            }

            if (!array_key_exists('fieldValue', $fieldData)) {
                throw new Exceptions\Parser("Missing 'fieldValue' element for '{$fieldData['fieldDefinitionIdentifier']}' identifier in UserCreate.");
            }

            $fieldValue = $this->fieldTypeParser->parseValue($fieldDefinition->fieldTypeIdentifier, $fieldData['fieldValue']);

            $languageCode = null;
            if (array_key_exists('languageCode', $fieldData)) {
                $languageCode = $fieldData['languageCode'];
            }

            $userCreateStruct->setField($fieldData['fieldDefinitionIdentifier'], $fieldValue, $languageCode);
        }

        return $userCreateStruct;
    }

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


Question:
Create a string from bytes using the given encoding

@param bytes The bytes to create a string from
@param encoding The encoding of the string
@return The created string

public static String getString(byte[] bytes, String encoding) {
        try {
            return new String(bytes, encoding);
        } catch(UnsupportedEncodingException e) {
            throw new IllegalArgumentException(encoding + " is not a known encoding name.", e);
        }
    }

def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True):
        """"""
        try:
            with self:
                _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response)
                self._conn.writeCharacteristic(handle, value, withResponse=with_response)
                if timeout:
                    _LOGGER.debug("Waiting for notifications for %s", timeout)
                    self._conn.waitForNotifications(timeout)
        except btle.BTLEException as ex:
            _LOGGER.debug("Got exception from bluepy while making a request: %s", ex)
            raise

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


function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
                        previousCompileContext) {
      if (!($compileNodes instanceof jqLite)) {
        // jquery always rewraps, whereas we need to preserve the original selector so that we can
        // modify it.
        $compileNodes = jqLite($compileNodes);
      }
      // We can not compile top level text elements since text nodes can be merged and we will
      // not be able to attach scope data to them, so we will wrap them in
      forEach($compileNodes, function(node, index) {
        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
          $compileNodes[index] = jqLite(node).wrap('').parent()[0];
        }
      });
      var compositeLinkFn =
              compileNodes($compileNodes, transcludeFn, $compileNodes,
                           maxPriority, ignoreDirective, previousCompileContext);
      compile.$$addScopeClass($compileNodes);
      var namespace = null;
      return function publicLinkFn(scope, cloneConnectFn, options) {
        assertArg(scope, 'scope');

        options = options || {};
        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
          transcludeControllers = options.transcludeControllers,
          futureParentElement = options.futureParentElement;

        // When `parentBoundTranscludeFn` is passed, it is a
        // `controllersBoundTransclude` function (it was previously passed
        // as `transclude` to directive.link) so we must unwrap it to get
        // its `boundTranscludeFn`
        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
        }

        if (!namespace) {
          namespace = detectNamespaceForChildElements(futureParentElement);
        }
        var $linkNode;
        if (namespace !== 'html') {
          // When using a directive with replace:true and templateUrl the $compileNodes
          // (or a child element inside of them)
          // might change, so we need to recreate the namespace adapted compileNodes
          // for call to the link function.
          // Note: This will already clone the nodes...
          $linkNode = jqLite(
            wrapTemplate(namespace, jqLite('
').append($compileNodes).html())
          );
        } else if (cloneConnectFn) {
          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
          // and sometimes changes the structure of the DOM.
          $linkNode = JQLitePrototype.clone.call($compileNodes);
        } else {
          $linkNode = $compileNodes;
        }

        if (transcludeControllers) {
          for (var controllerName in transcludeControllers) {
            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
          }
        }

        compile.$$addScopeInfo($linkNode, scope);

        if (cloneConnectFn) cloneConnectFn($linkNode, scope);
        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
        return $linkNode;
      };
    }

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

		if ($this->multiPage)
		{
			$strPreview .= '
 Articletitle1

 Articletitle2

 Articletitle3
';
		}
		else
		{
			$strPreview .= '
 Articletitle
';
		}

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

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


Question: // Round performs quantization by rounding. Rounds a to the nearest multiple of b.

func (as ArraySpec) Round(val Input) Input {
	return as.proc(func(i Input) Input {
		return i.Round(val)
	})
}

public function setDisplayRoundingFactor( $decimal, $power, $label = '' )
	{
		$this->displayRoundings[ $decimal ] = array(
			'divisor' => $decimal >= 0 ? 1 : pow( 10, $power ),
			'power' => $power,
			'label' => $label,
		);
	}

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


Question:
Short description of method getSecondOperation

@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@return core_kernel_rules_Term

public function getSecondOperation()
    {
        $returnValue = null;

        if(empty($this->secondOperation)){
        	$property = new core_kernel_classes_Property(RulesRdf::PROPERTY_OPERATION_SECOND_OP);
        	$resource = $this->getUniquePropertyValue($property);
        	$this->secondOperation = new core_kernel_rules_Term($resource->getUri());
        }
        $returnValue = $this->secondOperation;

        return $returnValue;
    }

def username_end_time(self, **kwargs):

        config = ET.Element("config")
        username = ET.SubElement(config, "username", xmlns="urn:brocade.com:mgmt:brocade-aaa")
        name_key = ET.SubElement(username, "name")
        name_key.text = kwargs.pop('name')
        end_time = ET.SubElement(username, "end-time")
        end_time.text = kwargs.pop('end_time')

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

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


Question:
@param \Rancoud\Database\Configurator|array $configuration
@param string                               $key
@param string                               $method

@throws \Exception

public static function useNewDatabaseEncryptionDriver($configuration, string $key, string $method = null): void
    {
        static::throwExceptionIfHasStarted();

        $driver = new DatabaseEncryption();
        $driver->setNewDatabase($configuration);
        static::setKeyAndMethod($driver, $key, $method);

        static::$driver = $driver;
    }

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLENAME_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getOperation(), OPERATION_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyField(), HASHKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyValue(), HASHKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyType(), HASHKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyField(), RANGEKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyValue(), RANGEKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyType(), RANGEKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getPayloadField(), PAYLOADFIELD_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: // AndCardinality returns the cardinality of the intersection between two bitmaps, bitmaps are not modified

func (rb *Bitmap) AndCardinality(x2 *Bitmap) uint64 {
	pos1 := 0
	pos2 := 0
	answer := uint64(0)
	length1 := rb.highlowcontainer.size()
	length2 := x2.highlowcontainer.size()

main:
	for {
		if pos1 < length1 && pos2 < length2 {
			s1 := rb.highlowcontainer.getKeyAtIndex(pos1)
			s2 := x2.highlowcontainer.getKeyAtIndex(pos2)
			for {
				if s1 == s2 {
					c1 := rb.highlowcontainer.getContainerAtIndex(pos1)
					c2 := x2.highlowcontainer.getContainerAtIndex(pos2)
					answer += uint64(c1.andCardinality(c2))
					pos1++
					pos2++
					if (pos1 == length1) || (pos2 == length2) {
						break main
					}
					s1 = rb.highlowcontainer.getKeyAtIndex(pos1)
					s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
				} else if s1 < s2 {
					pos1 = rb.highlowcontainer.advanceUntil(s2, pos1)
					if pos1 == length1 {
						break main
					}
					s1 = rb.highlowcontainer.getKeyAtIndex(pos1)
				} else { //s1 > s2
					pos2 = x2.highlowcontainer.advanceUntil(s1, pos2)
					if pos2 == length2 {
						break main
					}
					s2 = x2.highlowcontainer.getKeyAtIndex(pos2)
				}
			}
		} else {
			break
		}
	}
	return answer
}

private static void contextWord(String[] words, int index, int distance, String word, Map<String, List<ContextWord>> map){
        String _word = null;
        if(index > -1 && index < words.length){
            _word = words[index];
        }
        if(_word != null && Utils.isChineseCharAndLengthAtLeastTwo(_word)){
            addToMap(map, word, _word, distance);
        }
    }

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


Question:
Returns the value for a key as a String.

@param _key key for the searched value
@return string of the value if exist; otherwise null

public String getString(final String _key)
    {
        String ret = null;
        if (this.attributes.containsKey(_key)) {
            ret = this.attributes.get(_key).getValue();
        }
        return ret;
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question: A replacement for inspect.getargspec

def getargspec(f):
    """"""
    spec = getfullargspec(f)
    return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults)

def _get_spec(tree_base, spec, template, saltenv='base'):
    '''

    '''
    spec_tgt = os.path.basename(spec)
    dest = os.path.join(tree_base, 'SPECS', spec_tgt)
    return __salt__['cp.get_url'](
        spec,
        dest,
        saltenv=saltenv)

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


Question: Add the element *val* to the list.

def add(self, val):
        """"""
        _maxes, _lists = self._maxes, self._lists

        if _maxes:
            pos = bisect_right(_maxes, val)

            if pos == len(_maxes):
                pos -= 1
                _maxes[pos] = val
                _lists[pos].append(val)
            else:
                insort(_lists[pos], val)

            self._expand(pos)
        else:
            _maxes.append(val)
            _lists.append([val])

        self._len += 1

def value_change(self, vcdId, value):
        ''''''
        self.idcode2series[vcdId].append((self.now, value))

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


Question:
Get options for configuring widget

@param string|null $key
@param mixed|null $default

@return mixed|null

public function getOptions($key = null, $default = null)
    {
        if ($key !== null) {
            return isset($this->_options[$key]) ? $this->_options[$key] : $default;
        } else {
            return $this->_options;
        }
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question: // prepareUpdate builds an updated release for an update operation.

func (s *ReleaseServer) prepareUpdate(req *services.UpdateReleaseRequest) (*release.Release, *release.Release, error) {
	if req.Chart == nil {
		return nil, nil, errMissingChart
	}

	// finds the deployed release with the given name
	currentRelease, err := s.env.Releases.Deployed(req.Name)
	if err != nil {
		return nil, nil, err
	}

	// determine if values will be reused
	if err := s.reuseValues(req, currentRelease); err != nil {
		return nil, nil, err
	}

	// finds the non-deleted release with the given name
	lastRelease, err := s.env.Releases.Last(req.Name)
	if err != nil {
		return nil, nil, err
	}

	// Increment revision count. This is passed to templates, and also stored on
	// the release object.
	revision := lastRelease.Version + 1

	ts := timeconv.Now()
	options := chartutil.ReleaseOptions{
		Name:      req.Name,
		Time:      ts,
		Namespace: currentRelease.Namespace,
		IsUpgrade: true,
		Revision:  int(revision),
	}

	caps, err := capabilities(s.clientset.Discovery())
	if err != nil {
		return nil, nil, err
	}
	valuesToRender, err := chartutil.ToRenderValuesCaps(req.Chart, req.Values, options, caps)
	if err != nil {
		return nil, nil, err
	}

	hooks, manifestDoc, notesTxt, err := s.renderResources(req.Chart, valuesToRender, req.SubNotes, caps.APIVersions)
	if err != nil {
		return nil, nil, err
	}

	// Store an updated release.
	updatedRelease := &release.Release{
		Name:      req.Name,
		Namespace: currentRelease.Namespace,
		Chart:     req.Chart,
		Config:    req.Values,
		Info: &release.Info{
			FirstDeployed: currentRelease.Info.FirstDeployed,
			LastDeployed:  ts,
			Status:        &release.Status{Code: release.Status_PENDING_UPGRADE},
			Description:   "Preparing upgrade", // This should be overwritten later.
		},
		Version:  revision,
		Manifest: manifestDoc.String(),
		Hooks:    hooks,
	}

	if len(notesTxt) > 0 {
		updatedRelease.Info.Status.Notes = notesTxt
	}
	err = validateManifest(s.env.KubeClient, currentRelease.Namespace, manifestDoc.Bytes())
	return currentRelease, updatedRelease, err
}

public function publishNodeAction(NodeInterface $node, Workspace $selectedWorkspace)
    {
        $this->publishingService->publishNode($node);
        $this->addFlashMessage($this->translator->translateById('workspaces.selectedChangeHasBeenPublished', [], null, null, 'Modules', 'Neos.Neos'));
        $this->redirect('show', null, null, ['workspace' => $selectedWorkspace]);
    }

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


Question: // Validate the message values.

func (m *Message) validate() error {
	// Message should no be empty
	if m.Message == "" {
		return ErrMessageEmpty
	}

	// Validate message length
	if utf8.RuneCountInString(m.Message) > MessageMaxLength {
		return ErrMessageTooLong
	}

	// Validate Title field length
	if utf8.RuneCountInString(m.Title) > MessageTitleMaxLength {
		return ErrMessageTitleTooLong
	}

	// Validate URL field
	if utf8.RuneCountInString(m.URL) > MessageURLMaxLength {
		return ErrMessageURLTooLong
	}

	// Validate URL title field
	if utf8.RuneCountInString(m.URLTitle) > MessageURLTitleMaxLength {
		return ErrMessageURLTitleTooLong
	}

	// URLTitle should not be set with an empty URL
	if m.URL == "" && m.URLTitle != "" {
		return ErrEmptyURL
	}

	// Validate priorities
	if m.Priority > PriorityEmergency || m.Priority < PriorityLowest {
		return ErrInvalidPriority
	}

	// Validate emergency priority
	if m.Priority == PriorityEmergency {
		if m.Retry == 0 || m.Expire == 0 {
			return ErrMissingEmergencyParameter
		}
	}

	// Test device name
	if m.DeviceName != "" {
		if deviceNameRegexp.MatchString(m.DeviceName) == false {
			return ErrInvalidDeviceName
		}
	}

	return nil
}

public String getMessage(String id, String defaultMsg) {
    return getMessage(id, lang, defaultMsg);
  }

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


Question:
[POST] [/event/index]
Post endpoint for submitting new events
@return array

public function actionIndexPost()
	{
		$event = new Events;
		$attributes = Yii::app()->request->getParam('Event', array());
		if (strpos($attributes['uri'], '/dashboard/') !== false)
			return true;

		$event->attributes = $attributes;

		// Set failure?
		if (isset($attributes['content_id']))
			$event->content_id = $attributes['content_id'];

		// Try to figure out the correct content_id if one isn't provided
		if ($event->content_id == NULL)
		{
			$content = Content::model()->findByAttributes(array('slug' => $event->uri));
			if ($content !== NULL)
				$event->content_id = $content->id;
		}

		if ($id = Cii::get($attributes, 'content_id', false))
		{
			$content = Content::model()->findByPk($id);
			if ($content != NULL)
				$event->uri = $content->slug;
		}
		else
			$event->content_id = null;

		if ($event->save())
			return $event->getApiAttributes();

		return $this->returnError(400, NULL, $event->getErrors());
	}

public void marshall(DescribeEventAggregatesRequest describeEventAggregatesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeEventAggregatesRequest.getFilter(), FILTER_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getAggregateField(), AGGREGATEFIELD_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getNextToken(), NEXTTOKEN_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: // CleanupTempMounts all temp mounts and remove the directories

func CleanupTempMounts(flags int) (warnings []error, err error) {
	mounts, err := Self()
	if err != nil {
		return nil, err
	}
	var toUnmount []string
	for _, m := range mounts {
		if strings.HasPrefix(m.Mountpoint, tempMountLocation) {
			toUnmount = append(toUnmount, m.Mountpoint)
		}
	}
	sort.Sort(sort.Reverse(sort.StringSlice(toUnmount)))
	for _, path := range toUnmount {
		if err := UnmountAll(path, flags); err != nil {
			warnings = append(warnings, err)
			continue
		}
		if err := os.Remove(path); err != nil {
			warnings = append(warnings, err)
		}
	}
	return warnings, nil
}

func ForceUnmount(target string, flag int) (err error) {
	// Simple retry logic for unmount
	for i := 0; i < 10; i++ {
		if err = syscall.Unmount(target, flag); err == nil {
			return err
		}
		time.Sleep(100 * time.Millisecond)
	}
	return
}

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


Question: // GetMTU determines the MTU of a network interface device.

func GetMTU(name string) (uint32, error) {
	fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_DGRAM, 0)
	if err != nil {
		return 0, err
	}

	defer syscall.Close(fd)

	var ifreq struct {
		name [16]byte
		mtu  int32
		_    [20]byte
	}

	copy(ifreq.name[:], name)
	_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.SIOCGIFMTU, uintptr(unsafe.Pointer(&ifreq)))
	if errno != 0 {
		return 0, errno
	}

	return uint32(ifreq.mtu), nil
}

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

        return $this;
    }

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


Question: / \copydoc Erebot::Interfaces::Config::Main::load()

public function load($configData, $source)
    {
        $logger = \Plop\Plop::getInstance();
        $possibleSources = array(
            self::LOAD_FROM_FILE,
            self::LOAD_FROM_STRING,
        );
        if (!in_array($source, $possibleSources, true)) {
            throw new \Erebot\InvalidValueException('Invalid $source');
        }

        if ($source == self::LOAD_FROM_FILE) {
            if (is_string($configData) && $configData != "") {
                if (!strncasecmp(PHP_OS, "Win", 3)) {
                    if (!in_array($configData[0], array("/", "\\")) &&
                        strlen($configData) > 1 && $configData[1] != ":") {
                        $configData = getcwd() . DIRECTORY_SEPARATOR .
                                        $configData;
                    }
                } elseif ($configData[0] != DIRECTORY_SEPARATOR) {
                    $configData = getcwd() . DIRECTORY_SEPARATOR . $configData;
                }
                $file = \Erebot\URI::fromAbsPath($configData, false);
            } elseif (is_object($configData) &&
                $configData instanceof \Erebot\URIInterface) {
                $file = $configData;
            } else {
                throw new \Erebot\InvalidValueException(
                    "Invalid configuration file"
                );
            }
        } elseif (!is_string($configData)) {
            throw new \Erebot\InvalidValueException(
                "Invalid configuration file"
            );
        } else {
            $file = null;
        }

        $mainSchema = dirname(dirname(__DIR__)) .
                        DIRECTORY_SEPARATOR . 'data' .
                        DIRECTORY_SEPARATOR . 'config.rng';
        $mainSchema = file_get_contents($mainSchema);
        $ue         = libxml_use_internal_errors(true);
        $domxml     = new \Erebot\DOM();
        if ($source == self::LOAD_FROM_FILE) {
            $domxml->load((string) $file);
        } else {
            $domxml->loadXML($configData);
        }

        $domxml->xinclude(LIBXML_NOBASEFIX);
        $this->stripXGlobWrappers($domxml);

        $ok         = $domxml->relaxNGValidateSource($mainSchema);
        $errors     = $domxml->getErrors();
        libxml_use_internal_errors($ue);

        if (!$ok || count($errors)) {
            // Some unpredicted error occurred,
            // show some (hopefully) useful information.
            $logger->error(print_r($errors, true));
            throw new \Erebot\InvalidValueException(
                'Errors were found while validating the configuration file'
            );
        }

        $xml = simplexml_import_dom($domxml);
        parent::__construct($this, $xml);

        if (!isset($xml['version'])) {
            $this->version = null;
        } else {
            $this->version  = (string) $xml['version'];
        }

        if (!isset($xml['timezone'])) {
            throw new \Erebot\InvalidValueException('No timezone defined');
        }
        $this->timezone = (string) $xml['timezone'];

        // Set timezone information.
        // This is needed to configure the logging subsystem.
        if (function_exists('date_default_timezone_set')) {
            if (!date_default_timezone_set($this->timezone)) {
                throw \Erebot\InvalidValueException(
                    sprintf(
                        'Invalid timezone: "%s"',
                        $this->timezone
                    )
                );
            }
        }

        $daemonize      = isset($xml['daemon'])
                        ? $this->parseBool((string) $xml['daemon'])
                        : false;
        $userIdentity   = isset($xml['uid']) ? ((string) $xml['uid']) : null;
        $groupIdentity  = isset($xml['gid']) ? ((string) $xml['gid']) : null;
        $pidfile        = isset($xml['pidfile'])
                        ? ((string) $xml['pidfile'])
                        : null;

        if ($daemonize === null) {
            throw new \Erebot\InvalidValueException('Invalid "daemon" value');
        }

        if (!isset($xml['commands-prefix'])) {
            $this->commandsPrefix = '!';
        } else {
            $this->commandsPrefix = (string) $xml['commands-prefix'];
            if (strcspn($this->commandsPrefix, " \r\n\t") !=
                strlen($this->commandsPrefix)) {
                throw new \Erebot\InvalidValueException(
                    'Invalid command prefix'
                );
            }
        }

        $logger->debug(
            $this->coreTranslator->gettext(
                'Loaded configuration data'
            )
        );

        $this->networks = array();
        foreach ($xml->networks->network as $netCfg) {
            /// @TODO use dependency injection instead.
            $newConfig  = new \Erebot\Config\Network($this, $netCfg);
            $this->networks[$newConfig->getName()] = $newConfig;
            unset($newConfig);
        }

        if ($source == self::LOAD_FROM_FILE) {
            $this->configFile   = $configData;
        } else {
            $this->configFile   = null;
        }

        // Default values.
        $this->daemonize        = $daemonize;
        $this->userIdentity     = $userIdentity;
        $this->groupIdentity    = $groupIdentity;
        $this->pidfile          = $pidfile;
    }

public function init()
    {
        $this->initAutoloader($this->swiftBasePath);

        $this->transport = Swift_SmtpTransport::newInstance($this->host, $this->port, $this->security);
        $this->transport->setUsername($this->username)->setPassword($this->password);

        parent::init();
    }

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


Question: TODO: suggest the old value & the current version

def complete_set(self, cmd_param_text, full_cmd, *rest):

        complete_value = partial(complete_values, ["updated-value"])
        complete_version = partial(complete_values, [str(i) for i in range(1, 11)])
        completers = [self._complete_path, complete_value, complete_version]
        return complete(completers, cmd_param_text, full_cmd, *rest)

def create_marking_iobject(self,
                               uid=None,
                               timestamp=timezone.now(),
                               metadata_dict=None,
                               id_namespace_uri=DINGOS_DEFAULT_ID_NAMESPACE_URI,
                               iobject_family_name=DINGOS_IOBJECT_FAMILY_NAME,
                               iobject_family_revison_name=DINGOS_REVISION_NAME,
                               iobject_type_name=DINGOS_DEFAULT_IMPORT_MARKING_TYPE_NAME,
                               iobject_type_namespace_uri=DINGOS_NAMESPACE_URI,
                               iobject_type_revision_name=DINGOS_REVISION_NAME,
                               ):

        if not uid:
            uid = uuid.uuid1()

        iobject, created = self.create_iobject(iobject_family_name=iobject_family_name,
                                                      iobject_family_revision_name=iobject_family_revison_name,
                                                      iobject_type_name=iobject_type_name,
                                                      iobject_type_namespace_uri=iobject_type_namespace_uri,
                                                      iobject_type_revision_name=iobject_type_revision_name,
                                                      iobject_data=metadata_dict,
                                                      uid=uid,
                                                      identifier_ns_uri=id_namespace_uri,
                                                      timestamp=timestamp,
                                                      )

        return iobject

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


Question: Yields bad words and suggested alternate spellings.

def check(self, text):

        for word, pos in self.tokenizer(text):
            correct = self.dictionary.check(word)
            if correct:
                continue
            yield word, self.dictionary.suggest(word) if self.suggest else []
        return

protected boolean checkTerm(AppendRequest request, CompletableFuture<AppendResponse> future) {
    RaftLogWriter writer = raft.getLogWriter();
    if (request.term() < raft.getTerm()) {
      log.debug("Rejected {}: request term is less than the current term ({})", request, raft.getTerm());
      return failAppend(writer.getLastIndex(), future);
    }
    return true;
  }

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


Question:
Save the tree into the given XML stream writer.
@param stream the stream writer
@throws XMLStreamException if an error occurs

public void save(XMLStreamWriter stream) throws XMLStreamException {
        stream.writeStartDocument("UTF-8", "1.0");

        saveInternal(stream);

        stream.writeEndDocument();
    }

def update(self):
        """"""
        response = self.jss.session.post(self.url, data=self.auth)
        response_xml = ElementTree.fromstring(response.text.encode("utf_8"))

        # Remove previous data, if any, and then add in response's XML.
        self.clear()
        for child in response_xml.getchildren():
            self.append(child)

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


Question: // evalGC is used to garbage collect old evaluations

func (c *CoreScheduler) evalGC(eval *structs.Evaluation) error {
	// Iterate over the evaluations
	ws := memdb.NewWatchSet()
	iter, err := c.snap.Evals(ws)
	if err != nil {
		return err
	}

	var oldThreshold uint64
	if eval.JobID == structs.CoreJobForceGC {
		// The GC was forced, so set the threshold to its maximum so everything
		// will GC.
		oldThreshold = math.MaxUint64
		c.logger.Debug("forced eval GC")
	} else {
		// Compute the old threshold limit for GC using the FSM
		// time table.  This is a rough mapping of a time to the
		// Raft index it belongs to.
		tt := c.srv.fsm.TimeTable()
		cutoff := time.Now().UTC().Add(-1 * c.srv.config.EvalGCThreshold)
		oldThreshold = tt.NearestIndex(cutoff)
		c.logger.Debug("eval GC scanning before cutoff index",
			"index", oldThreshold, "eval_gc_threshold", c.srv.config.EvalGCThreshold)
	}

	// Collect the allocations and evaluations to GC
	var gcAlloc, gcEval []string
	for raw := iter.Next(); raw != nil; raw = iter.Next() {
		eval := raw.(*structs.Evaluation)

		// The Evaluation GC should not handle batch jobs since those need to be
		// garbage collected in one shot
		gc, allocs, err := c.gcEval(eval, oldThreshold, false)
		if err != nil {
			return err
		}

		if gc {
			gcEval = append(gcEval, eval.ID)
		}
		gcAlloc = append(gcAlloc, allocs...)
	}

	// Fast-path the nothing case
	if len(gcEval) == 0 && len(gcAlloc) == 0 {
		return nil
	}
	c.logger.Debug("eval GC found eligibile objects",
		"evals", len(gcEval), "allocs", len(gcAlloc))

	return c.evalReap(gcEval, gcAlloc)
}

def get_consumed(self, key):

        if key not in self._consumed:
            self._consumed[key] = {
                'read': DecayingCapacityStore(),
                'write': DecayingCapacityStore(),
            }
        return self._consumed[key]

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


Question: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *ImageStreamList) DeepCopyInto(out *ImageStreamList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]ImageStream, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	return
}

def to_gufunc_string(self):

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

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContinueOn.

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

def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False):
        """"""
        if len(tokens) == 1:
            decorators, funcdef = "", tokens[0]
        elif len(tokens) == 2:
            decorators, funcdef = tokens
        else:
            raise CoconutInternalException("invalid function definition tokens", tokens)

        # extract information about the function
        raw_lines = funcdef.splitlines(True)
        def_stmt = raw_lines.pop(0)
        func_name, func_args, func_params = None, None, None
        with self.complain_on_err():
            func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt)

        undotted_name = None  # the function __name__ if func_name is a dotted name
        if func_name is not None:
            if "." in func_name:
                undotted_name = func_name.rsplit(".", 1)[-1]
                def_stmt = def_stmt.replace(func_name, undotted_name)

        # handle async functions
        if is_async:
            if not self.target:
                raise self.make_err(
                    CoconutTargetError,
                    "async function definition requires a specific target",
                    original, loc,
                    target="sys",
                )
            elif self.target_info >= (3, 5):
                def_stmt = "async " + def_stmt
            else:
                decorators += "@_coconut.asyncio.coroutine\n"

            # only Python 3.3+ supports returning values inside generators
            if self.target_info < (3, 3):
                func_code = self.transform_returns(raw_lines, is_async=True)
            else:
                func_code = "".join(raw_lines)

        # handle normal functions
        else:
            # tre does not work with decorators, though tco does
            attempt_tre = func_name is not None and not decorators
            if attempt_tre:
                use_mock = func_args and func_args != func_params[1:-1]
                func_store = tre_store_var + "_" + str(self.tre_store_count)
                self.tre_store_count += 1
                tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock)
            else:
                use_mock = func_store = tre_return_grammar = None

            func_code, tco, tre = self.transform_returns(
                raw_lines,
                tre_return_grammar,
                use_mock,
            )

            if tre:
                comment, rest = split_leading_comment(func_code)
                indent, base, dedent = split_leading_trailing_indent(rest, 1)
                base, base_dedent = split_trailing_indent(base)
                docstring, base = self.split_docstring(base)
                func_code = (
                    comment + indent
                    + (docstring + "\n" if docstring is not None else "")
                    + (
                        "def " + tre_mock_var + func_params + ": return " + func_args + "\n"
                        if use_mock else ""
                    ) + "while True:\n"
                        + openindent + base + base_dedent
                        + ("\n" if "\n" not in base_dedent else "") + "return None"
                        + ("\n" if "\n" not in dedent else "") + closeindent + dedent
                    + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n"
                )
            if tco:
                decorators += "@_coconut_tco\n"  # binds most tightly

        out = decorators + def_stmt + func_code
        if undotted_name is not None:
            out += func_name + " = " + undotted_name + "\n"
        return out

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


Question: Check if the given file is a .concat file. Call done() with result.

function filterFile(file, done) {
      // Ensure it matches the extension.
      const correctExtention = path.extname(file) === opts.extname

      // Make sure it has defined files.
      const hasFiles = files[file].files
      done(null, correctExtention && hasFiles)
    }

public static CsvWriter getWriter(String filePath, Charset charset, boolean isAppend) {
		return new CsvWriter(filePath, charset, isAppend);
	}

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


Question: Initializes the Memcache Module

private function initializeMemCached()
    {
        $this->memcached = new \Memcached();

        // support multiple hosts using semicolon to separate hosts
        $hosts = explode(';', $this->host);

        // different ports for each hosts the same way
        $ports = explode(';', $this->port);

        if (count($ports) < 1) {
            $ports = array_fill(0, count($hosts), self::DEFAULT_PORT);
        } elseif (count($ports) === 1) {
            // if we have just one port, use it for all hosts
            $usedPort = $ports[0];
            $ports    = array_fill(0, count($hosts), $usedPort);
        }

        foreach ($hosts as $i => $host) {
            if (!isset($ports[$i])) {
                /*
                 * if we have a difference between the count of hosts and
                 * the count of ports, use the default port to fill the gap
                 */
                $ports[$i] = self::DEFAULT_PORT;
            }

            $this->memcached->addServer($host, $ports[$i]);
        }
    }

public function set_data($data) {
        if (!isset($data['sharing'])) {
            // Set the default value here. mforms doesn't handle defaults very nicely.
            $data['sharing'] = cache_administration_helper::get_definition_sharing_options(cache_definition::SHARING_DEFAULT);
        }
        parent::set_data($data);
    }

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


Question:
add select element
@access public
@param $field string
@param $label string
@return \Gcs\Framework\Core\Orm\Validation\Element\Select
@since 3.0
@package Gcs\Framework\Core\Orm\Validation

public function select($field, $label) {
        $select = new Select($this->_entity, $field, $label);
        array_push($this->_elements, $select);

        return $select;
    }

def apply_configuration(yml)
      if yml.include?("packages")
        yml["packages"].each do |k, v|
          valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
          @package_info[k] = valid_data
        end
      end

      if yml.include?("platforms")
        yml["platforms"].each do |k, v|
          valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
          @platform_info[k] = valid_data
        end
      end

      if yml.include?("compile")
        valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
        valid_data.each { |k, v| @compile_info[k] = v }
      end

      if yml.include?("unittest")
        valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
        valid_data.each { |k, v| @unittest_info[k] = v }
      end

      self
    end

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


Question:
[indexAction description]

@param  \Fredy\Model\Entity\Request $request

@return array    TwigContext

function indexAction($request)
    {

        $response = new FrontendResponse('journal/journalList.twig', $request);

        $journalRepository = new Repository(new Journal(),$this->database);

        $journals = $journalRepository->findAll();

        $journals = array_reverse($journals);

        $response->setTwigVariables(
            [
                'journals' => $journals
            ]
        );

        return $response;

        // $insertJournal = new \Model\Entity\Journal(NULL,'title','content');
        // $journalRepository->update($insertJournal);

        // $journal = $journalRepository->findById(1);
        // $journalRepository->remove($journal);

        // $filter = new Filter($this->database);
        // $filter->addCondition(new Condition('content','<>','content'));
        // $journals = $journalRepository->findByFilter($filter);

    }

public function execute()
    {
        $datafield  = $this->getRequest()->getParam('name');

        if (! empty($datafield)) {
            $response = $this->dataHelper->createDatafield(
                (int) $this->getRequest()->getParam('website_id'),
                $datafield,
                $this->getRequest()->getParam('type'),
                $this->getRequest()->getParam('visibility'),
                $this->getRequest()->getParam('default')
            );

            if (isset($response->message)) {
                $this->messageManager->addErrorMessage($response->message);
            } else {
                $this->messageManager->addSuccessMessage(__('Data field successfully created.'));
            }
        }
    }

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


Question:
Find something

@param Callable $rule

@return array

public function find($rule){

            $r = [];

            foreach($this->data as $k=>$v){
                if($rule($this->{$k})){
                    $r[] = $this->{$k};
                }
            }

            return $r;

        }

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: Serialize object to an encoded base64 string.

public String serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			oos.writeObject(object);
			return new String(Base64.encodeBase64(bos.toByteArray()));
		} catch (IOException e) {
			LOGGER.error("Can't serialize data on Base 64", e);
			throw new IllegalArgumentException(e);
		} catch (Exception e) {
			LOGGER.error("Can't serialize data on Base 64", e);
			throw new IllegalArgumentException(e);
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (Exception e) {
				LOGGER.error("Can't close ObjetInputStream used for serialize data on Base 64", e);
			}
		}
	}

def stringify_times(obj)
      case obj
      when Hash
        Hash[obj.map { |k,v| [k, stringify_times(v)] }]
      when Array
        obj.map { |v| stringify_times(v) }
      else
        iso_format_time(obj)
      end
    end

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


Question: region ---------------------- SETTERS -------------------------------

public function setDecorators($name, array $decorators) {
        foreach ($decorators as $decorator) {
            $this->addDecorator($name, $decorator);
        }
    }

def characterSet(self, charset: str) -> None:
        """"""
        charset_node = self._find_charset_node() or Meta(parent=self.head)
        charset_node.setAttribute('charset', charset)

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


Question:
Negates this instance and returns it.

        :return     self

def negated(self):

        op = QueryCompound.Op.And if self.__op == QueryCompound.Op.Or else QueryCompound.Op.Or
        return QueryCompound(*self.__queries, op=op)

def has_children?(check = nil)
      post = obtain_record(check)
      post.blank? ? false : post.has_children?
    end

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


Question: // newTelegrafWriter returns a logging-wrapped writer.

func newTelegrafWriter(w io.Writer) io.Writer {
	return &telegrafLog{
		writer: wlog.NewWriter(w),
	}
}

public void serialize(final DataOutput output) throws TTIOException {
        try {
            output.writeLong(dataKey);
            output.writeBoolean(eof);
            output.writeInt(val.length);
            output.write(val);
        } catch (final IOException exc) {
            throw new TTIOException(exc);
        }
    }

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


Question:
Load the initial values for parameters and Wilson coefficients from
        one or several files.

        `streams` should be a tuple of file-like objects strings.

def load_initial(self, streams):
        """"""
        d = {}
        for stream in streams:
            s = io.load(stream)
            if 'BLOCK' not in s:
                raise ValueError("No BLOCK found")
            d.update(s['BLOCK'])
        d = {'BLOCK': d}
        C = io.wc_lha2dict(d)
        sm = io.sm_lha2dict(d)
        C.update(sm)
        C = definitions.symmetrize(C)
        self.C_in = C

def create(genome, config):

        genome_config = config.genome_config
        required = required_for_output(genome_config.input_keys, genome_config.output_keys, genome.connections)

        # Gather inputs and expressed connections.
        node_inputs = {}
        for cg in itervalues(genome.connections):
            if not cg.enabled:
                continue

            i, o = cg.key
            if o not in required and i not in required:
                continue

            if o not in node_inputs:
                node_inputs[o] = [(i, cg.weight)]
            else:
                node_inputs[o].append((i, cg.weight))

        neurons = {}
        for node_key in required:
            ng = genome.nodes[node_key]
            inputs = node_inputs.get(node_key, [])
            neurons[node_key] = IZNeuron(ng.bias, ng.a, ng.b, ng.c, ng.d, inputs)

        genome_config = config.genome_config
        return IZNN(neurons, genome_config.input_keys, genome_config.output_keys)

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


Question: // Delete removes the given SSH key, by Name

func (ssh SSHKeyPair) Delete(ctx context.Context, client *Client) error {
	if ssh.Name == "" {
		return fmt.Errorf("an SSH Key Pair may only be deleted using Name")
	}

	return client.BooleanRequestWithContext(ctx, &DeleteSSHKeyPair{
		Name: ssh.Name,
	})
}

func (s *ModifyReplicationGroupShardConfigurationInput) SetNodeGroupsToRemove(v []*string) *ModifyReplicationGroupShardConfigurationInput {
	s.NodeGroupsToRemove = v
	return s
}

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


Question:
/*
@Override
public Type getType()
{
return getDelegate().getType();
}

@Override
  public void invoke(InboxAmp inbox, StubAmp actor)
  {
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();

    try {
      thread.setContextClassLoader(_loader);

      getDelegate().invoke(inbox, actor);
    } finally {
      thread.setContextClassLoader(oldLoader);
    }
  }

<L, E extends Input.Impl> void dispatch(
      Class<L> listenerType, E event, Interaction<L, E> interaction, Interaction<L, E> onCancel) {
    dispatch(event.captureState.layer, listenerType, event, interaction, onCancel);
  }

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


Question:
Format the field attributes.

@return string

protected function formatAttributes()
    {
        $html = [];

        foreach ($this->attributes as $name => $value) {
            $html[] = $name.'="'.e($value).'"';
        }

        return implode(' ', $html);
    }

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

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


Question:
Remove all the custom fields from the entity

@param  int $id
@return \Phalcon\MVC\Models

public function cleanCustomFields(int $id): bool
    {
        $reflector = new \ReflectionClass($this);
        $classNameWithNameSpace = $reflector->getNamespaceName() . '\\' . $reflector->getShortName() . 'CustomFields';
        $customModel = new $classNameWithNameSpace();

        //return $customModel->find(['conditions' => $this->getSource() . '_id = ?0', 'bind' => [$id]])->delete();
        //we need to run the query since we dont have primary key
        $result = $this->getReadConnection()->prepare("DELETE FROM {$customModel->getSource()} WHERE " . $this->getSource() . '_id = ?');
        return $result->execute([$id]);
    }

private function clearEntities()
    {
        $this->nodeEntities = array();
        $this->relationEntities = array();

        $this->nodeEntitiesToRemove = array();
        $this->relationEntitiesToRemove = array();

        $this->startNodeRelations = array();
        $this->endNodeRelations = array();
    }

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


Question: Given a node in a partition layout, return an array of all of its ancestor nodes, highest first, but excluding the root.

function getAncestors(node) {
  var path = [];
  var current = node;
  while (current.parent) {
    path.unshift(current);
    current = current.parent;
  }
  return path;
}

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question: // SetRequestParameters sets the RequestParameters field's value.

func (s *Integration) SetRequestParameters(v map[string]*string) *Integration {
	s.RequestParameters = v
	return s
}

def add_query_params(self, query_params):
        '''
        '''
        query_params = as_multi_dict(query_params)
        for k in query_params:
            self.query_params.pop(k, None)
            for v in query_params.getlist(k):
                self.query_params[k] = v
        self.apply_param_schema()
        return self

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


Question: //VerifyCouchConfig method provides function to verify the connection information

func (couchInstance *CouchInstance) VerifyCouchConfig() (*ConnectionInfo, *DBReturn, error) {

	logger.Debugf("Entering VerifyCouchConfig()")
	defer logger.Debugf("Exiting VerifyCouchConfig()")

	connectURL, err := url.Parse(couchInstance.conf.URL)
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, nil, errors.Wrapf(err, "error parsing couch instance URL: %s", couchInstance.conf.URL)
	}
	connectURL.Path = "/"

	//get the number of retries for startup
	maxRetriesOnStartup := couchInstance.conf.MaxRetriesOnStartup

	resp, couchDBReturn, err := couchInstance.handleRequest(context.Background(), http.MethodGet, "", "VerifyCouchConfig", connectURL, nil,
		couchInstance.conf.Username, couchInstance.conf.Password, maxRetriesOnStartup, true, nil)

	if err != nil {
		return nil, couchDBReturn, errors.WithMessage(err, "unable to connect to CouchDB, check the hostname and port")
	}
	defer closeResponseBody(resp)

	dbResponse := &ConnectionInfo{}
	decodeErr := json.NewDecoder(resp.Body).Decode(&dbResponse)
	if decodeErr != nil {
		return nil, nil, errors.Wrap(decodeErr, "error decoding response body")
	}

	// trace the database info response
	logger.Debugw("VerifyConnection() dbResponseJSON: %s", dbResponse)

	//check to see if the system databases exist
	//Verifying the existence of the system database accomplishes two steps
	//1.  Ensures the system databases are created
	//2.  Verifies the username password provided in the CouchDB config are valid for system admin
	err = CreateSystemDatabasesIfNotExist(couchInstance)
	if err != nil {
		logger.Errorf("Unable to connect to CouchDB, error: %s. Check the admin username and password.", err)
		return nil, nil, errors.WithMessage(err, "unable to connect to CouchDB. Check the admin username and password")
	}

	return dbResponse, couchDBReturn, nil
}

func (c *Certificate) SetVersion(version X509_Version) error {
	cvers := C.long(version)
	if C.X_X509_set_version(c.x, cvers) != 1 {
		return errors.New("failed to set certificate version")
	}
	return nil
}

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


Question:
Export the page data for the mustache template.

@param renderer_base $output renderer to be used to render the page elements.
@return stdClass

public function export_for_template(renderer_base $output) {

        $data = (object) [
            'pluginbaseurl' => (new moodle_url('/admin/tool/policy'))->out(false),
        ];

        $data->policies = array_values($this->policies);
        if (!empty($this->returnurl)) {
            $data->returnurl = $this->returnurl;
        }

        array_walk($data->policies, function($item, $key) {
            $item->policytypestr = get_string('policydoctype'.$item->type, 'tool_policy');
            $item->policyaudiencestr = get_string('policydocaudience'.$item->audience, 'tool_policy');
        });

        return $data;
    }

public function findView()
    {
        if (view()->exists($this->view)) {
            return $this->view;
        }

        $default = $this->hint.
                   '::'.
                   $this->intermediatePath.
                   '.Panels.default';

        if (view()->exists($default)) {
            return $default;
        }

        // Not finding the Flame Panel creates an Exception since the remaining logic
        // cannot be processed (attributes finding, twinkles rending, etc).
        throw FlameException::PanelNotFound(Route::getCurrentRoute()->getActionName());
    }

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


Question: Decode a Base58 encoded string

def b58decode(v):
    ''''''

    if not isinstance(v, str):
        v = v.decode('ascii')

    origlen = len(v)
    v = v.lstrip(alphabet[0])
    newlen = len(v)

    acc = b58decode_int(v)

    result = []
    while acc > 0:
        acc, mod = divmod(acc, 256)
        result.append(mod)

    return (b'\0' * (origlen - newlen) + bseq(reversed(result)))

public function calculateHash()
    {
        $str =  $this->data['ECM_TRANS_ID'] .
                $this->data['ECM_TRANS_DATE'] .
                $this->request->getPurse() .
                $this->data['ECM_PAYER_ID'] .
                $this->data['ECM_ITEM_COST'] .
                $this->data['ECM_QTY'] .
                $this->request->getSecret();

        return md5($str);
    }

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


Question:
Tries to extract a `datetime` object from the given string, including
        time information.

        Raises `DateTimeFormatterException` if the extraction fails.

def extract_datetime(cls, datetime_str):

        if not datetime_str:
            raise DateTimeFormatterException('datetime_str must a valid string')

        try:
            return cls._extract_timestamp(datetime_str, cls.DATETIME_FORMAT)
        except (TypeError, ValueError):
            raise DateTimeFormatterException('Invalid datetime string {}.'.format(datetime_str))

protected static function _getDateString($value)
    {
        $formatted = '';
        if (isset($value['year'], $value['month'], $value['day']) &&
            (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
        ) {
            $formatted .= sprintf('%d-%02d-%02d ', $value['year'], $value['month'], $value['day']);
        }

        if (isset($value['hour'])) {
            if (isset($value['meridian']) && (int)$value['hour'] === 12) {
                $value['hour'] = 0;
            }
            if (isset($value['meridian'])) {
                $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
            }
            $value += ['minute' => 0, 'second' => 0];
            if (is_numeric($value['hour']) && is_numeric($value['minute']) && is_numeric($value['second'])) {
                $formatted .= sprintf('%02d:%02d:%02d', $value['hour'], $value['minute'], $value['second']);
            }
        }

        return trim($formatted);
    }

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


Question:
Save the X500Principal object to a stream.

@serialData this {@code X500Principal} is serialized
by writing out its DER-encoded form
(the value of {@code getEncoded} is serialized).

private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        s.writeObject(thisX500Name.getEncodedInternal());
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_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: Removes a postfix function from a variable. See 'postfix'.

def do_rmpostfix(self, arg):
        """"""
        altered = False
        if arg in self.curargs["functions"]:
            del self.curargs["functions"][arg]
            altered = True
        elif arg == "*":
            for varname in list(self.curargs["functions"].keys()):
                del self.curargs["functions"][varname]
            altered = True
        if altered:
            self.do_postfix("list")

def get_docs(self, arg=None):
        '''

        '''
        if arg:
            if '*' in arg:
                target_mod = arg
                _use_fnmatch = True
            else:
                target_mod = arg + '.' if not arg.endswith('.') else arg
                _use_fnmatch = False
            if _use_fnmatch:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in fnmatch.filter(self.functions, target_mod)]
            else:
                docs = [(fun, self.functions[fun].__doc__)
                        for fun in sorted(self.functions)
                        if fun == arg or fun.startswith(target_mod)]
        else:
            docs = [(fun, self.functions[fun].__doc__)
                    for fun in sorted(self.functions)]
        docs = dict(docs)
        return salt.utils.doc.strip_rst(docs)

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


Question:
Add an image to each record
@param array
@param string
@return string

public function addIcon($row, $label, \DataContainer $dc=null, $imageAttribute='', $blnReturnImage=false, $blnProtected=false)
  {
    // Add the breadcrumb link
    $label = 'addToUrl('cat='.$row['id']) . '">' . $label . '[' . \ContaoDMS\DmsUtils::getCuttedAllowedFileTypes(implode(',', $this->getCategoryForId($row['id'], true, false)->getAllowedFileTypes())) . ']';

    $time = time();
    $image = 'category';

    $published = ($row['published'] && ($row['start'] == '' || $row['start'] < $time) && ($row['stop'] == '' || $row['stop'] > $time));
    if (!$published)
    {
      $image .= '_1';
    }

    // Return the image only
    if ($blnReturnImage)
    {
      return $this->generateImage($image . '.png', '', $imageAttribute);
    }

    $genReadPerm = $row['general_read_permission'];
    $genReadPermImg = ''
            . $this->generateImage('system/modules/DocumentManagementSystem/assets/general_read_permission_' . $genReadPerm . '.png', $genReadPerm, 'title="' . $GLOBALS['TL_LANG']['tl_dms_categories']['general_read_permission_option'][$genReadPerm][0] . '"')
            . '';
    $genManagePerm = $row['general_manage_permission'];
    $genManagePermImg = ''
            . $this->generateImage('system/modules/DocumentManagementSystem/assets/general_manage_permission_' . $genManagePerm . '.png', $genManagePerm, 'title="' . $GLOBALS['TL_LANG']['tl_dms_categories']['general_manage_permission_option'][$genManagePerm][0] . '"')
            . '';

    $pubDocPerDef = $row['publish_documents_per_default'];
    $pubDocPerDefImg = "";
    if ($pubDocPerDef != \Category::PUBLISH_DOCUMENTS_PER_DEFAULT_DISABLE)
    {
      $pubDocPerDefImg = ''
              . $this->generateImage('system/modules/DocumentManagementSystem/assets/publish_documents_per_default_' . $pubDocPerDef . '.png', $pubDocPerDef, 'title="' . $GLOBALS['TL_LANG']['tl_dms_categories']['publish_documents_per_default_option'][$pubDocPerDef][0] . '"')
              . '';
    }

    $inhFileTypes = $row['file_types_inherit'];
    $inhFileTypesImg = "";
    if ($inhFileTypes)
    {
      $inhFileTypesImg = ''
               . $this->generateImage('system/modules/DocumentManagementSystem/assets/file_types_inherit_ACTIVE.png', "", 'title="' . $GLOBALS['TL_LANG']['tl_dms_categories']['file_types_inherit_option']['ACTIVE'][0] . '"')
               . '';
    }

    return 'addToUrl('cat='.$row['id']) . '#do=feRedirect">' . $this->generateImage('system/modules/DocumentManagementSystem/assets/' . $image . '.png', '', $imageAttribute . ' data-icon="' . 'system/modules/DocumentManagementSystem/assets/' . ($published ? $image : rtrim($image, '_1')) . '.png' . '" data-icon-disabled="' . 'system/modules/DocumentManagementSystem/assets/' . rtrim($image, '_1') . '_1.png' . '"') . '' . $label . $genReadPermImg . $genManagePermImg . $pubDocPerDefImg . $inhFileTypesImg;
  }

public function Details() {
      if ($this->_PropertiesDefined === FALSE)
         trigger_error(ErrorMessage('You must configure the pager with $Pager->Configure() before retrieving the pager details.', 'MorePager', 'Details'), E_USER_ERROR);

      $Details = FALSE;
      if ($this->TotalRecords > 0) {
         if ($this->_Totalled === TRUE) {
            $Details = self::FormatUrl(T('%s$1 to %s$2 of %s$3'), $this->Offset + 1, $this->_LastOffset, $this->TotalRecords);
         } else {
            $Details = self::FormatUrl(T('%s$1 to %s$2'), $this->Offset, $this->_LastOffset);
         }
      }
      return $Details;
   }

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


Question:
Checks if a potential solution is a real one
(not included in a previous solution)
and add this solution to the solution list
in case of success.

@param  traversed  new potential solution

private void solution(BitSet traversed) throws CDKException {
        boolean included = false;
        BitSet projG1 = projectG1(traversed);
        BitSet projG2 = projectG2(traversed);

        // the solution must follows the search constrains
        // (must contain the mandatory elements in G1 an G2)
        if (isContainedIn(getSourceBitSet(), projG1) && isContainedIn(getTargetBitSet(), projG2)) {
            // the solution should not be included in a previous solution
            // at the CDKRGraph level. So we check against all previous solution
            // On the other hand if a previous solution is included in the
            // new one, the previous solution is removed.
            for (Iterator<BitSet> i = getSolutionList().listIterator(); i.hasNext() && !included;) {
                BitSet sol = i.next();
                checkTimeOut();
                if (!sol.equals(traversed)) {
                    // if we asked to save all 'mappings' then keep this mapping
                    if (isFindAllMap() && (projG1.equals(projectG1(sol)) || projG2.equals(projectG2(sol)))) {
                        // do nothing
                    } // if the new solution is included mark maxIterator as included
                    else if (isContainedIn(projG1, projectG1(sol)) || isContainedIn(projG2, projectG2(sol))) {
                        included = true;
                    } // if the previous solution is contained in the new one, remove the previous solution
                    else if (isContainedIn(projectG1(sol), projG1) || isContainedIn(projectG2(sol), projG2)) {
                        i.remove();
                    }
                } else {
                    // solution already exists
                    included = true;
                }
            }

            if (included == false) {
                // if maxIterator is really a new solution add maxIterator to the
                // list of current solution
                getSolutionList().add(traversed);
            }

            if (!isFindAllStructure()) {
                // if we need only one solution
                // stop the search process
                // (e.g. substructure search)
                setStop(true);
            }
        }
    }

function walk (router, transform) {
  assert.equal(typeof router, 'function', 'wayfarer.walk: router should be an function')
  assert.equal(typeof transform, 'function', 'wayfarer.walk: transform should be a function')

  var trie = router._trie
  assert.equal(typeof trie, 'object', 'wayfarer.walk: trie should be an object')

  // (str, obj) -> null
  ;(function walk (route, trie) {
    if (trie.cb) {
      trie.cb = transform(route, trie.cb)
    }

    if (trie.nodes) {
      var nodes = trie.nodes
      Object.keys(nodes).forEach(function (key) {
        var node = nodes[key]
        var newRoute = (key === '$$')
          ? route + '/:' + trie.name
          : route + '/' + key
        walk(newRoute, node)
      })
    }
  })('', trie.trie)
}

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


Question: // LeaveGroup method

func (client *Client) LeaveGroup(groupID string) *LeaveGroupCall {
	return &LeaveGroupCall{
		c:       client,
		groupID: groupID,
	}
}

private boolean isRemoved(HeaderType<?> headerType)
	{
		for (HeaderType<?> type : mRemovedHeaderTypes)
		{
			if (type.equals(headerType))
			{
				return true;
			}
		}
		return false;
	}

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


Question:
Returns standard (dynamic) object URL

@param int   $iLang   language id [optional]
@param array $aParams additional params to use [optional]

@return string

public function getStdLink($iLang = null, $aParams = [])
    {
        if ($iLang === null) {
            $iLang = \OxidEsales\Eshop\Core\Registry::getLang()->getBaseLanguage();
        }

        return \OxidEsales\Eshop\Core\Registry::getUtilsUrl()->processUrl($this->getBaseStdLink($iLang), true, $aParams, $iLang);
    }

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

        return;
    }

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


Question:
Prepends each line in a block of text w/ line numbers, optionally
highlighting a specific line.

function withLineNumbers(text, offset, offendingLine) {
    if (typeof offendingLine !== 'number') {
      offendingLine = NaN;
    }

    var lines = text;
    if (typeof lines === 'string') {
      lines = lines.split('\n');
    }

    return lines.map(function(line, i) {
      line = (i + offset) + ': ' + line;
      if (i === (offendingLine - 1)) {
        line = '\x1B[31m' + line + '\x1B[39m';
      } else {
        line = '\x1B[90m' + line + '\x1B[39m';
      }
      return line;
    }).join('\n');
  }

def return_buffer_contents(self, frame, force_unescaped=False):
        """"""
        if not force_unescaped:
            if frame.eval_ctx.volatile:
                self.writeline('if context.eval_ctx.autoescape:')
                self.indent()
                self.writeline('return Markup(concat(%s))' % frame.buffer)
                self.outdent()
                self.writeline('else:')
                self.indent()
                self.writeline('return concat(%s)' % frame.buffer)
                self.outdent()
                return
            elif frame.eval_ctx.autoescape:
                self.writeline('return Markup(concat(%s))' % frame.buffer)
                return
        self.writeline('return concat(%s)' % frame.buffer)

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


Question:
@inheritdoc

@throws \Payum\Core\Reply\HttpRedirect

public function execute($request)
    {
        /** @var Request $request */
        RequestNotSupportedException::assertSupports($this, $request);

        $model = ArrayObject::ensureArrayObject($request->getModel());

        if ($model['vads_trans_id']) {
            return;
        }

        $model['vads_trans_id'] = $this->api->getTransactionId();
        // Current UTC date time
        $model['vads_trans_date'] = (new \DateTime('now', new \DateTimeZone('UTC')))->format('YmdHis');

        $data = $model->getArrayCopy();

        $this->logRequestData($data);

        $url = $this->api->createRequestUrl($data);

        throw new HttpRedirect($url);
    }

public function handle()
    {
        $git_url = $this->argument('$git_url');
        $warning = 'This will overrite you Auth view files. Do you wish to continue? [y|N]';
        if ($this->confirm($warning)) {
            $this->info('Getting auth theme from github');
            $process = new Process('git clone '. $git_url . ' tmp_auth && rm -rf tmp_auth/.git && rm -f tmp_auth/readme.md && cp -rf tmp_auth/* resources/views/ && rm -rf tmp_auth');
            $process->run();

            // executes after the command finishes
            if (!$process->isSuccessful()) {
                throw new ProcessFailedException($process);
            }

            echo $process->getOutput();
            $this->info('Successfully added auth theme');
        } else {
            $this->info('Alright, we wount touch anything!');
        }
    }

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


Question:
getIndexedParameter()

@throws ParseException

@return AST\AnonymousVariable

private function parseAnonVariable()
    {
        $this->tokenizer->expect(TokenType::ANON_VARIABLE);

        return new AST\AnonymousVariable($this->varIndex);
    }

function (params, tokens, is_ingroup) {
	var i = 0, url = '', value;

	for (; i < tokens.length; ++i) {
		switch (tokens[i].type) {
			case "OptionalGroup" :
				if (params[tokens[i].index]) {
					url += params[tokens[i].index];
				}
				break;
			case "Segment" :
				value = params[tokens[i].key];
				if (value) {
					url += value;
				} else if (is_ingroup) {
					return '';
				}
				break;
			case "Explicit" :
				url += tokens[i].value;
				break;
			default:
				console.log("Unhandled token", tokens[i]);
		}
	}

	return url;
}

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