Question:
Validates the proper entity type on EntityMetadata.

@param   EntityMetadata  $metadata
@return  bool
@throws  MetadataException

public function validateMetadataType(EntityMetadata $metadata)
    {
        if (true === $metadata->isChildEntity()) {
            $parentType = $metadata->getParentEntityType();
            if (0 !== strpos($metadata->type, $parentType)) {
                throw MetadataException::invalidMetadata($metadata->type, sprintf('Child class types must be prefixed by the parent class. Expected "%s" prefix.', $parentType));
            }
        }
        if (false === $this->isEntityTypeValid($metadata->type)) {
            throw MetadataException::invalidMetadata($metadata->type, sprintf('The entity type is invalid based on the configured name format "%s"', $this->config->getEntityFormat()));
        }
        return true;
    }

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

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

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

        $class = new ReflectionClass($model);

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

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

        return $ret;
    }

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


Question: Get all of the spans in the queue

def queued_spans(self):

        spans = []
        while True:
            try:
                s = self.queue.get(False)
            except queue.Empty:
                break
            else:
                spans.append(s)
        return spans

def populate_event_que(self, que_obj):

        for ip in self.obj_dict:
            drvr_obj = self.obj_dict.get(ip).get('drvr_obj')
            drvr_obj.populate_event_que(que_obj)

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


Question: Add an empty line after a node. Mutates the node.

function addEmptyLineAfter(
  node /*: postcss$node*/,
  newline /*: '\n' | '\r\n'*/
) /*: postcss$node*/ {
  const after = _.last(node.raws.after.split(";"));

  if (!/\r?\n/.test(after)) {
    node.raws.after = node.raws.after + _.repeat(newline, 2);
  } else {
    node.raws.after = node.raws.after.replace(/(\r?\n)/, `${newline}$1`);
  }

  return node;
}

func FodderEnsureCleanNewline(fodder *Fodder) {
	if !FodderHasCleanEndline(*fodder) {
		FodderAppend(fodder, MakeFodderElement(FodderLineEnd, 0, 0, []string{}))
	}
}

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


Question:
Get bean in lazy mode (if bean is null then initialize it).

@param pBeanName - bean name
@return Object - requested bean
@throws Exception - an exception

@Override
  public final Object lazyGet(
    final String pBeanName) throws Exception {
    if (this.isReconfiguring) {
      throw new ExceptionWithCode(ExceptionWithCode.SYSTEM_RECONFIGURING,
        "system_reconfiguring");
    }
    if (this.isReinitializing) {
      // locking:
      synchronized (this) {
        if (this.isReinitializing) {
          init(); //complex initializing inner factories delegate
          this.isReinitializing = false;
        }
      }
    }
    setLastRequestTime(new Date().getTime());
    Object bean = this.beansMap.get(pBeanName);
    // see in beige-common:
    // org.beigesoft.test.DoubleCkeckLockingWrApTest
    if (bean == null) {
      // locking:
      synchronized (this) {
        // make sure again whether it's null after locking:
        bean = this.beansMap.get(pBeanName);
        if (bean == null) {
          if (getHandlerEntityRequestName().equals(pBeanName)) {
            bean = this.factoryBldServices.lazyGetHandlerEntityRequest();
          } else if (getHndlEntityFileReportReqName().equals(pBeanName)) {
            bean = this.factoryBldServices.lazyGetHndlEntityFileReportReq();
          } else if (getSrvOrmName().equals(pBeanName)) {
            bean = lazyGetSrvOrm();
          } else if (getSessionTrackerName().equals(pBeanName)) {
            bean = lazyGetSessionTracker();
          } else if (getImportFullDatabaseCopyName().equals(pBeanName)) {
            bean = lazyGetImportFullDatabaseCopy();
          } else if (getDatabaseWriterName().equals(pBeanName)) {
            bean = lazyGetDbWriterFullCopy();
          } else if (getMailSenderName().equals(pBeanName)) {
            bean = lazyGetMailSender();
          } else if (getHndlI18nRequestName().equals(pBeanName)) {
            bean = lazyGetHndlI18nRequest();
          } else if (getUtilXmlName().equals(pBeanName)) {
            bean = lazyGetUtilXml();
          } else if (getSecureLoggerName().equals(pBeanName)) {
            bean = lazyGetSecureLogger();
          } else if (getLoggerName().equals(pBeanName)) {
            bean = lazyGetLogger();
          } else if (getMngSoftwareName().equals(pBeanName)) {
            bean = lazyGetMngSoftware();
          } else if (getSrvI18nName().equals(pBeanName)) {
            bean = lazyGetSrvI18n();
          } else if (getUtlJspName().equals(pBeanName)) {
            bean = lazyGetUtlJsp();
          } else if (getSrvDatabaseName().equals(pBeanName)) {
            bean = lazyGetSrvDatabase();
          } else if (getHlpEntitiesPageName().equals(pBeanName)) {
            bean = lazyGetHlpEntitiesPage();
          } else if (getSrvNumberToStringName().equals(pBeanName)) {
            bean = lazyGetSrvNumberToString();
          } else if (getSrvDateName().equals(pBeanName)) {
            bean = lazyGetSrvDate();
          } else if (getSrvPageName().equals(pBeanName)) {
            bean = lazyGetSrvPage();
          } else if (getFillEntityFromReqName().equals(pBeanName)) {
            bean = lazyGetFillEntityFromReq();
          } else if (getMngUvdSettingsName().equals(pBeanName)) {
            bean = lazyGetMngUvdSettings();
          } else if (getUtlPropertiesName().equals(pBeanName)) {
            bean = lazyGetUtlProperties();
          } else if (getUtlReflectionName().equals(pBeanName)) {
            bean = lazyGetUtlReflection();
          } else if (getMngSettingsGetDbCopyName().equals(pBeanName)) {
            bean = lazyGetMngSettingsGetDbCopy();
          } else if (getHldFieldsCnvTfsNamesName().equals(pBeanName)) {
            bean = lazyGetHldFieldsCnvTfsNames();
          } else if (getFctConvertersToFromStringName().equals(pBeanName)) {
            bean = lazyGetFctConvertersToFromString();
          } else if (getFctFillersObjectFieldsName().equals(pBeanName)) {
            bean = lazyGetFctFillersObjectFields();
          } else if (getHolderRapiSettersName().equals(pBeanName)) {
            bean = lazyGetHolderRapiSetters();
          } else if (getHolderRapiGettersName().equals(pBeanName)) {
            bean = lazyGetHolderRapiGetters();
          } else if (getHolderRapiFieldsName().equals(pBeanName)) {
            bean = lazyGetHolderRapiFields();
          } else if (getHlpInsertUpdateName().equals(pBeanName)) {
            bean = lazyGetHlpInsertUpdate();
          } else if (getFillerEntitiesFromRsName().equals(pBeanName)) {
            bean = lazyGetFillerEntitiesFromRs();
          } else if (getFctBnCnvBnFromRsName().equals(pBeanName)) {
            bean = lazyGetFctBnCnvBnFromRs();
          } else if (getFctBnCnvIbnToColumnValuesName().equals(pBeanName)) {
            bean = lazyGetFctBnCnvIbnToColumnValues();
          } else if (getCsvReaderName().equals(pBeanName)) {
            bean = lazyGetCsvReader();
          } else if (getSrvSqlEscapeName().equals(pBeanName)) {
            bean = lazyGetSrvSqlEscape();
          } else if (getHldCnvToColumnsValuesNamesName().equals(pBeanName)) {
            bean = lazyGetHldCnvToColumnsValuesNames();
          } else if (getPrepareDbAfterFullImportName().equals(pBeanName)) {
            bean = lazyGetPrepareDbAfterFullImport();
          } else if (getHldCnvFromRsNamesName().equals(pBeanName)) {
            bean = lazyGetHldCnvFromRsNames();
          } else if (getFctBcFctSimpleEntitiesName().equals(pBeanName)) {
            bean = this.factoryBldServices.lazyGetFctBcFctSimpleEntities();
          } else if (getFctBcCnvEntityToColumnsValuesName().equals(pBeanName)) {
            bean = lazyGetFctBcCnvEntityToColumnsValues();
          } else {
            bean = lazyGetOtherBean(pBeanName);
            if (bean == null && this.factoryOverBeans != null) {
                bean = this.factoryOverBeans.lazyGet(pBeanName);
            }
          }
        }
      }
    }
    if (bean == null) {
      throw new ExceptionWithCode(ExceptionWithCode.CONFIGURATION_MISTAKE,
        "There is no bean with name " + pBeanName);
    }
    return bean;
  }

def __do_parse(self, pattern_str):

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

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

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

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

        # parser.setTrace(True)

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

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

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

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

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


Question: Set a hash of model attributes on the object, firing `"change"` unless you choose to silence it.

function(attrs, options) {

      // Extract attributes and options.
      options || (options = {});
      if (!attrs) return this;
      if (attrs.attributes) attrs = attrs.attributes;
      var now = this.attributes, escaped = this._escapedAttributes;

      // Run validation.
      if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;

      // Check for changes of `id`.
      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

      // We're about to start triggering change events.
      var alreadyChanging = this._changing;
      this._changing = true;

      // Update attributes.
      for (var attr in attrs) {
        var val = attrs[attr];
        if (!_.isEqual(now[attr], val)) {
          now[attr] = val;
          delete escaped[attr];
          this._changed = true;
          if (!options.silent) this.trigger('change:' + attr, this, val, options);
        }
      }

      // Fire the `"change"` event, if the model has been changed.
      if (!alreadyChanging && !options.silent && this._changed) this.change(options);
      this._changing = false;
      return this;
    }

def update
      @payment_method = PaymentMethod.find params[:payment_method_id]
      data = JSON.parse Base64.strict_decode64 params[:data]
      render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature]
      @order = Order.find data['order_id']

      raise ArgumentError unless @order.payments.completed.empty? &&
        data['currency'] == @order.currency &&
        BigDecimal(data['amount']) == @order.total &&
        data['type'] == 'buy' &&
        (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox'))

      payment = @order.payments.create amount: @order.total, payment_method: @payment_method
      payment.complete!

      render text: "Thank you.\n"
    end

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


Question:
Expect calls to private methods.

@throws Exception If something unexpected goes wrong.
@see PowerMockito#when(Object)

public static <T> OngoingStubbing<T> when(Object instance, String methodName, Object... arguments) throws Exception {
        return Mockito.when(Whitebox.<T>invokeMethod(instance, methodName, arguments));
    }

public function mock(array $settings = array())
    {
        $this->mocked['REQUEST_TIME'] = time();
        $settings = array_merge($this->mocked, $settings);

        $this->parse($settings);
    }

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


Question:
// DBTipBlock gets the dcrutil.Block for the current best block in the stake
// database. It used DBState to get the best block hash, and the node RPC client
// to get the block itself.

func (db *StakeDatabase) DBTipBlock() (*dcrutil.Block, error) {
	_, hash, err := db.DBState()
	if err != nil {
		return nil, err
	}

	return db.getBlock(hash)
}

def find_card_bundles(provider: Provider, deck: Deck) -> Optional[Iterator]:
    ''''''

    if isinstance(provider, RpcNode):
        if deck.id is None:
            raise Exception("deck.id required to listtransactions")

        p2th_account = provider.getaccount(deck.p2th_address)
        batch_data = [('getrawtransaction', [i["txid"], 1]) for
                      i in provider.listtransactions(p2th_account)]
        result = provider.batch(batch_data)

        if result is not None:
            raw_txns = [i['result'] for i in result if result]

        else:
            raise EmptyP2THDirectory({'error': 'No cards found on this deck.'})

    else:
        if deck.p2th_address is None:
            raise Exception("deck.p2th_address required to listtransactions")

        try:
            raw_txns = (provider.getrawtransaction(i, 1) for i in
                        provider.listtransactions(deck.p2th_address))
        except TypeError:
            raise EmptyP2THDirectory({'error': 'No cards found on this deck.'})

    return (card_bundler(provider, deck, i) for i in raw_txns)

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


Question:
Reads a string

<pre>
S b16 b8 string value
</pre>

public String readString()
        throws IOException
    {
        int tag = read();

        switch (tag) {
            case 'N':
                return null;

            case 'I':
                return String.valueOf(parseInt());
            case 'L':
                return String.valueOf(parseLong());
            case 'D':
                return String.valueOf(parseDouble());

            case 'S':
            case 's':
            case 'X':
            case 'x':
                _isLastChunk = tag == 'S' || tag == 'X';
                _chunkLength = (read() << 8) + read();

                _sbuf.setLength(0);
                int ch;

                while ((ch = parseChar()) >= 0)
                    _sbuf.append((char) ch);

                return _sbuf.toString();

            default:
                throw expect("string", tag);
        }
    }

func (l *ConsoleLogger) output(msg *Message) {
	buf := []byte{}
	buf = append(buf, msg.time.Format(l.timeFormat)...)
	if l.prefix != "" {
		buf = append(buf, ' ')
		buf = append(buf, l.prefix...)
	}
	buf = append(buf, ' ')
	buf = append(buf, l.levels[msg.level]...)
	buf = append(buf, ' ')
	buf = append(buf, msg.m...)
	if len(msg.m) > 0 && msg.m[len(msg.m)-1] != '\n' {
		buf = append(buf, '\n')
	}
	l.out.Write(buf)
}

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


Question: Open file in the menu bar was invoked by the user

protected void openFileMenuBar() {
		List<BoofSwingUtil.FileTypes> types = new ArrayList<>();
		if( allowImages )
			types.add(BoofSwingUtil.FileTypes.IMAGES);
		if( allowVideos )
			types.add(BoofSwingUtil.FileTypes.VIDEOS);
		BoofSwingUtil.FileTypes array[] = types.toArray(new BoofSwingUtil.FileTypes[0]);

		File file = BoofSwingUtil.openFileChooser(DemonstrationBase.this,array);
		if (file != null) {
			openFile(file);
		}
	}

public static boolean showDocument(URL url) {
        return showDocumentViaDesktop(url)
            || showDocumentViaExec(url)
            || JavaWebStart.showViaWebStart(url);
    }

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


Question:
Returns all element-collection elements
@return list of element-collection

public List<ElementCollection<EmbeddableAttributes<T>>> getAllElementCollection()
   {
      List<ElementCollection<EmbeddableAttributes<T>>> list = new ArrayList<ElementCollection<EmbeddableAttributes<T>>>();
      List<Node> nodeList = childNode.get("element-collection");
      for(Node node: nodeList)
      {
         ElementCollection<EmbeddableAttributes<T>>  type = new ElementCollectionImpl<EmbeddableAttributes<T>>(this, "element-collection", childNode, node);
         list.add(type);
      }
      return list;
   }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


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

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

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

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

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

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


Question:
Reads the sliders and converts the values to RGB, updating the
internal state for all the individual form fields
@method _getValuesFromSliders
@protected

function() {
            this.logger.log("hsv " + [this._getH(),this._getS(),this._getV()]);
            this.set(this.OPT.RGB, Color.hsv2rgb(this._getH(), this._getS(), this._getV()));
        }

protected FourColors desaturate(FourColors colors) {
        return new FourColors(desaturate(colors.top), desaturate(colors.upperMid), desaturate(colors.lowerMid), desaturate(colors.bottom));
    }

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


Question:
Gets a drop for peer evaluation.

@param Dropzone $dropzone
@param User     $user
@param string   $teamId
@param string   $teamName
@param bool     $withCreation

@return Drop | null

public function getPeerDrop(Dropzone $dropzone, User $user = null, $teamId = null, $teamName = null, $withCreation = true)
    {
        $peerDrop = null;

        /* Gets user|team drop to check if it is finished before allowing peer review */
        $userDrop = $this->getFinishedUserDrop($dropzone, $user, $teamId);

        /* user|team drop is finished */
        if (!empty($userDrop)) {
            /* Gets drops where user|team has an unfinished correction */
            $unfinishedDrops = $this->getUnfinishedPeerDrops($dropzone, $user, $teamId);

            if (count($unfinishedDrops) > 0) {
                /* Returns the first drop with an unfinished correction */
                $peerDrop = $unfinishedDrops[0];
            } else {
                /* Gets drops where user|team has a finished correction */
                $finishedDrops = $this->getFinishedPeerDrops($dropzone, $user, $teamId);
                $nbCorrections = count($finishedDrops);

                /* Fetches a drop for peer correction if user|team has not made the expected number of corrections */
                if ($withCreation && $dropzone->isReviewEnabled() && $nbCorrections < $dropzone->getExpectedCorrectionTotal()) {
                    $peerDrop = $this->getAvailableDropForPeer($dropzone, $user, $teamId, $teamName);
                }
            }
        }

        return $peerDrop;
    }

public static function report(String $subject, String $message, String $destination = NULL, String $time = NULL) : Bool
    {
        return Helper::report($subject, $message, $destination, $time);
    }

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


Question:
Perform logic needed to do IRB completion. Returns Array if completion is handled successfully, <tt>nil</tt>
 if input is not related to HackTree.

   completion_logic("c.he", :enabled_as => :c)    # => ["c.hello"]

def completion_logic(input, options = {})
      o = {}
      options = options.dup

      o[k = :enabled_as] = options.delete(k)

      raise ArgumentError, "Unknown option(s): #{options.inspect}" if not options.empty?
      raise ArgumentError, "options[:enabled_as] must be given" if not o[:enabled_as]

      # Check if this input is related to us.
      if not mat = input.match(/\A#{o[:enabled_as]}\.((?:[^.].*)|)\z/)
        return nil
      end

      lookup = mat[1]

      # Parse lookup string into node name and prefix.
      global_name, prefix = if mat = lookup.match(/\A(?:([^.]*)|(.+)\.(.*?))\z/)
        if mat[1]
          # "something".
          ["", mat[1]]
        else
          # "something.other", "something.other.other.".
          [mat[2], mat[3]]
        end
      else
        # Handle no match just in case.
        ["", ""]
      end

      base = if global_name == ""
        # Base is root.
        nil
      else
        # Find a named base node. If not found, return no candidates right away.
        find_node(global_name) or return []
      end

      # Select sub-nodes.
      candidates = children_of(base).select do |node|
        # Select those matching `prefix`.
        node.name.to_s.index(prefix) == 0
      end.map do |node|
        # Provide 1+ candidates per item.
        case node
        when Node::Group
          # A neat trick to prevent IRB from appending a " " after group name.
          [node.name, "#{node.name}."]
        else
          [node.name]
        end.map(&:to_s)
      end.flatten(1).map do |s|
        # Convert to final names.
        [
          "#{o[:enabled_as]}.",
          ("#{global_name}." if global_name != ""),
          s,
        ].compact.join
      end

      candidates
    end

def apply_environment!(hook_context, env)
      skipped_hooks = "#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}".split(/[:, ]/)
      only_hooks = env.fetch('ONLY') { '' }.split(/[:, ]/)
      hook_type = hook_context.hook_class_name

      if only_hooks.any? || skipped_hooks.include?('all') || skipped_hooks.include?('ALL')
        @hash[hook_type]['ALL']['skip'] = true
      end

      only_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                 map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                 each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = false
      end

      skipped_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                    map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                    each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = true
      end
    end

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


Question: Saves changes of article parameters.

public function save()
    {
        parent::save();

        $oConfig = \OxidEsales\Eshop\Core\Registry::getConfig();
        $soxId = $this->getEditObjectId();
        $aParams = $oConfig->getRequestParameter("editval");

        // default values
        $aParams = $this->addDefaultValues($aParams);

        // null values
        if (isset($aParams['oxarticles__oxvat']) && $aParams['oxarticles__oxvat'] === '') {
            $aParams['oxarticles__oxvat'] = null;
        }

        // varianthandling
        $soxparentId = $oConfig->getRequestParameter("oxparentid");
        if (isset($soxparentId) && $soxparentId && $soxparentId != "-1") {
            $aParams['oxarticles__oxparentid'] = $soxparentId;
        } else {
            unset($aParams['oxarticles__oxparentid']);
        }

        $oArticle = $this->createArticle();
        $oArticle->setLanguage($this->_iEditLang);

        if ($soxId != "-1") {
            $oArticle->loadInLang($this->_iEditLang, $soxId);
        } else {
            $aParams['oxarticles__oxid'] = null;
            $aParams['oxarticles__oxissearch'] = 1;
            $aParams['oxarticles__oxstockflag'] = 1;
            if (empty($aParams['oxarticles__oxstock'])) {
                $aParams['oxarticles__oxstock'] = 0;
            }

            if (!isset($aParams['oxarticles__oxactive'])) {
                $aParams['oxarticles__oxactive'] = 0;
            }
        }

        //article number handling, warns for artnum duplicates
        if (isset($aParams['oxarticles__oxartnum']) && strlen($aParams['oxarticles__oxartnum']) > 0 &&
            $oConfig->getConfigParam('blWarnOnSameArtNums') &&
            $oArticle->oxarticles__oxartnum->value != $aParams['oxarticles__oxartnum']
        ) {
            $sSelect = "select oxid from " . getViewName('oxarticles');
            $sSelect .= " where oxartnum = '" . $aParams['oxarticles__oxartnum'] . "'";
            $sSelect .= " and oxid != '" . $aParams['oxarticles__oxid'] . "'";
            if ($oArticle->assignRecord($sSelect)) {
                $this->_aViewData["errorsavingatricle"] = 1;
            }
        }

        $oArticle->setLanguage(0);
        //triming spaces from article title (M:876)
        if (isset($aParams['oxarticles__oxtitle'])) {
            $aParams['oxarticles__oxtitle'] = trim($aParams['oxarticles__oxtitle']);
        }

        $oArticle->assign($aParams);
        $oArticle->setArticleLongDesc($this->_processLongDesc($aParams['oxarticles__oxlongdesc']));
        $oArticle->setLanguage($this->_iEditLang);
        $oArticle = \OxidEsales\Eshop\Core\Registry::getUtilsFile()->processFiles($oArticle);
        $oArticle->save();

        // set oxid if inserted
        if ($soxId == "-1") {
            $sFastCat = $oConfig->getRequestParameter("art_category");
            if ($sFastCat != "-1") {
                $this->addToCategory($sFastCat, $oArticle->getId());
            }
        }

        $oArticle = $this->saveAdditionalArticleData($oArticle, $aParams);

        $this->setEditObjectId($oArticle->getId());
    }

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

        return self.subreddit.edit_wiki_page(self.page, *args, **kwargs)

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


Question:
/* No longer used ... have to use getSessionCookieConfig and set the values on that
@Override
public void setSessionCookieConfig(SessionCookieConfig arg0) {
TODO Auto-generated method stub

}

@Override
    public JspConfigDescriptor getJspConfigDescriptor() {
        if (withinContextInitOfProgAddListener) {
            throw new UnsupportedOperationException(MessageFormat.format(
                    nls.getString("Unsupported.op.from.servlet.context.listener"),
                    new Object[] {"getJspConfigDescriptor", lastProgAddListenerInitialized, getApplicationName()}));  // PI41941
        }
        JspConfigDescriptorImpl jspConfigDescriptor = new JspConfigDescriptorImpl(this);
        if (jspConfigDescriptor.getJspPropertyGroups().isEmpty() && jspConfigDescriptor.getTaglibs().isEmpty()) {
            return null;
        }
        return jspConfigDescriptor;
    }

public function setOption($name, $value) {
		$this->validateName($name);
		$this->config[$name] = $value;
	}

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


Question:
Inject Span Context to record headers

@param spanContext Span Context
@param headers record headers

static void inject(SpanContext spanContext, Headers headers,
      Tracer tracer) {
    tracer.inject(spanContext, Format.Builtin.TEXT_MAP,
        new HeadersMapInjectAdapter(headers, false));
  }

public function parse(Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $view = $parser->getExpressionParser()->parseExpression();

        $variablesOverride = new Twig_Node_Expression_Array(array(), $token->getLine());
        if ($stream->test(Twig_Token::NAME_TYPE, 'with')) {
            $stream->next();

            $variablesOverride->addElement($this->parser->getExpressionParser()->parseExpression());
        }

        $stream->expect(Twig_Token::BLOCK_END_TYPE);

        $viewTemplateExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateFile',
            new Twig_Node_Expression_Array(array(), $token->getLine()),
            $token->getLine()
        );

        $variablesExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateVars',
            $variablesOverride,
            $token->getLine()
        );

        return new Twig_Node_Include(
            $viewTemplateExpr,
            $variablesExpr,
            $only = false,
            $ignoreMissing = false,
            $token->getLine()
        );
    }

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


Question:
Initialize the weight list.

@param weights Weight list
@param ids IDs
@param relation Data relation
@param first First ID
@param second Second ID
@param distQ Distance query
@return Weight sum
@param <T> Object type

protected static <T> double initialWeights(WritableDoubleDataStore weights, Relation<? extends T> relation, DBIDs ids, T first, T second, DistanceQuery<? super T> distQ) {
    double weightsum = 0.;
    for(DBIDIter it = ids.iter(); it.valid(); it.advance()) {
      // distance will usually already be squared
      T v = relation.get(it);
      double weight = Math.min(distQ.distance(first, v), distQ.distance(second, v));
      weights.putDouble(it, weight);
      weightsum += weight;
    }
    return weightsum;
  }

private String getDatatypeLabel(DatatypeIdValue datatype) {
		if (datatype.getIri() == null) { // TODO should be redundant once the
											// JSON parsing works
			return "Unknown";
		}

		switch (datatype.getIri()) {
		case DatatypeIdValue.DT_COMMONS_MEDIA:
			return "Commons media";
		case DatatypeIdValue.DT_GLOBE_COORDINATES:
			return "Globe coordinates";
		case DatatypeIdValue.DT_ITEM:
			return "Item";
		case DatatypeIdValue.DT_QUANTITY:
			return "Quantity";
		case DatatypeIdValue.DT_STRING:
			return "String";
		case DatatypeIdValue.DT_TIME:
			return "Time";
		case DatatypeIdValue.DT_URL:
			return "URL";
		case DatatypeIdValue.DT_PROPERTY:
			return "Property";
		case DatatypeIdValue.DT_EXTERNAL_ID:
			return "External identifier";
		case DatatypeIdValue.DT_MATH:
			return "Math";
		case DatatypeIdValue.DT_MONOLINGUAL_TEXT:
			return "Monolingual Text";
		default:
			throw new RuntimeException("Unknown datatype " + datatype.getIri());
		}
	}

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


Question: // Read an OpenAPI binary file.

func (g *Gnostic) readOpenAPIBinary(data []byte) (message proto.Message, err error) {
	// try to read an OpenAPI v3 document
	documentV3 := &openapi_v3.Document{}
	err = proto.Unmarshal(data, documentV3)
	if err == nil && strings.HasPrefix(documentV3.Openapi, "3.0") {
		g.sourceFormat = SourceFormatOpenAPI3
		return documentV3, nil
	}
	// if that failed, try to read an OpenAPI v2 document
	documentV2 := &openapi_v2.Document{}
	err = proto.Unmarshal(data, documentV2)
	if err == nil && strings.HasPrefix(documentV2.Swagger, "2.0") {
		g.sourceFormat = SourceFormatOpenAPI2
		return documentV2, nil
	}
	// if that failed, try to read a Discovery Format document
	discoveryDocument := &discovery_v1.Document{}
	err = proto.Unmarshal(data, discoveryDocument)
	if err == nil { // && strings.HasPrefix(documentV2.Swagger, "2.0") {
		g.sourceFormat = SourceFormatDiscovery
		return discoveryDocument, nil
	}
	return nil, err
}

public java.lang.String getStaticFile() {
    java.lang.Object ref = staticFile_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      staticFile_ = s;
      return s;
    }
  }

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


Question:
r"""
        :math:Add formula

def dim_dsigmai(self, pars):

        """
        self._set_parameters(pars)
        result = np.sum(- self.m * self.otc * np.sin(self.ang) / self.denom,
                        axis=1)

        return result

public static StringBuilder appendCalcArgs(StringBuilder sb, CalcArgs args) {
	    final String astr = args.evaluate(CalcArgs.stringEvaluator);
	    if (!astr.startsWith(FUNCTION_OPENING)) {
	        sb.append(FUNCTION_OPENING);
	        sb.append(astr);
	        sb.append(FUNCTION_CLOSING);
	    } else {
	        sb.append(astr);
	    }
	    return sb;
	}

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


Question:
If the {@code nextSubgraphs} queue is empty, expands the graph frontier
of the next available vertex, if one exists, and the subgraphs reachable
from it to the queue.

private void advance() {
        while (nextSubgraphs.isEmpty() && vertexIter.hasNext()) {
            Integer nextVertex = vertexIter.next();
            // Determine the set of vertices that are greater than this vertex
            Set<Integer> extension = new HashSet<Integer>();
            for (Integer v : g.getNeighbors(nextVertex))
                if (v > nextVertex)
                    extension.add(v);
            Set<Integer> subgraph = new HashSet<Integer>();
            subgraph.add(nextVertex);
            extendSubgraph(subgraph, extension, nextVertex);
        }
    }

def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):

    gene_jsd_dict = dict()
    reference_genes = ref_gene_expression_dict.keys()
    assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.'

    for gene in gene_set:
        if gene not in network.nodes:
            continue

        neighbors = find_neighbors(network, gene)

        query_expression_vec = get_neighbor_expression_vector(neighbors, query_gene_expression_dict)
        ref_expression_vec = get_neighbor_expression_vector(neighbors, ref_gene_expression_dict)
        assert len(query_expression_vec) == len(ref_expression_vec), 'Topology of reference network and query network differs. Please check.'

        # A gene which has non-expressed neighbors is ignored.
        if np.sum(query_expression_vec) == 0 and np.sum(ref_expression_vec) == 0:
            continue

        query_p_vec = exp2prob(query_expression_vec)
        ref_p_vec = exp2prob(ref_expression_vec)

        gene_jsd_dict[gene] = jsd(query_p_vec, ref_p_vec)

    return np.mean(list(gene_jsd_dict.values()))

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


Question:
Set the language file to use

@param String $lang
@return void
@throws Exception

public function setLang($lang = 'en-us') {
		$this->lang = $lang;

		try {
			$this->messages = parse_ini_file(__DIR__ . '/Lang/' . $this->lang . '.ini');
		} catch (Exception $e) {
			throw $e;
		}
	}

public function actionDrop()
    {
        $stdout = '';
        foreach ($this->db->schema->getTableSchemas() as $table) {
            if ($table->name === $this->migrationTable) {
                continue;
            }
            $stdout .= static::generateDropTable($table->name);
            if (!empty($table->foreignKeys)) {
                $stdout .= ' // fk: ';

                foreach ($table->foreignKeys as $fk) {
                    foreach ($fk as $k => $v) {
                        if (0 === $k) {
                            continue;
                        }
                        $stdout .= "$k, ";
                    }
                }
                $stdout = rtrim($stdout, ', ');
            }
            $stdout .= "\n";
        }
        $this->stdout($stdout);
    }

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


Question: Executes the current step. Redirects to the next step in line if no errors occur.

public function ExecuteStep()
    {
        if ($this->ProcessStep()) {
            $this->ProcessStepSuccessHook();
            $oBasket = TShopBasket::GetInstance();
            $oBasket->aCompletedOrderStepList[$this->fieldSystemname] = true;
            $oNextStep = $this->GetNextStep();
            $this->JumpToStep($oNextStep);
        }
    }

public function doRun(InputInterface $input, OutputInterface $output)
    {
        $this->setOutput($output);

        $this->resetCodeBuffer();

        $this->setAutoExit(false);
        $this->setCatchExceptions(false);

        $this->readline->readHistory();

        $this->output->writeln($this->getHeader());
        $this->writeVersionInfo();
        $this->writeStartupMessage();

        try {
            $this->beforeRun();
            $this->loop->run($this);
            $this->afterRun();
        } catch (ThrowUpException $e) {
            throw $e->getPrevious();
        } catch (BreakException $e) {
            // The ProcessForker throws a BreakException to finish the main thread.
            return;
        }
    }

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


Question:
listing next siblings (until predicate hit).

@param {Node} node
@param {Function} [pred] - predicate function

function listNext(node, pred) {
  pred = pred || func.fail;

  const nodes = [];
  while (node) {
    if (pred(node)) { break; }
    nodes.push(node);
    node = node.nextSibling;
  }
  return nodes;
}

func setValueAt(root, value interface{}, parts []string) (interface{}, error) {
	h, t := ht(parts)
	return setNodeValueAt(root, value, h, t)
}

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


Question:
Use retry alg from mongodb to gobble up connection failures during replica set master vote
 Defaults to a 10 second wait

def rescue_connection_failure(max_retries = 40)
      success = false
      retries = 0
      while !success
        begin
          yield
          success = true
        rescue mongo_error_type => e
          raise e if (retries += 1) >= max_retries
          sleep 0.25
        end
      end
    end

def exponential_backoff(fn, sleeptime_s_max=30 * 60):
    """"""

    sleeptime_ms = 500
    while True:
        if fn():
            return True
        else:
            print('Sleeping {} ms'.format(sleeptime_ms))
            time.sleep(sleeptime_ms / 1000.0)
            sleeptime_ms *= 2

        if sleeptime_ms / 1000.0 > sleeptime_s_max:
            return False

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


Question: Serve a rueckenwind application

def serv(args):
    """"""
    if not args.no_debug:
        tornado.autoreload.start()

    extra = []

    if sys.stdout.isatty():
        # set terminal title
        sys.stdout.write('\x1b]2;rw: {}\x07'.format(' '.join(sys.argv[2:])))

    if args.cfg:
        extra.append(os.path.abspath(args.cfg))

    listen = (int(args.port), args.address)
    ioloop = tornado.ioloop.IOLoop.instance()
    setup_app(app=args.MODULE, extra_configs=extra,
              ioloop=ioloop, listen=listen)
    ioloop.start()

func (vpcApi *VpcApi) RestartRouter(id string) (bool, error) {
	_, err := vpcApi.entityService.Execute(id, VPC_RESTART_ROUTER_OPERATION, []byte{}, map[string]string{})
	return err == nil, err
}

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


Question:
Build long stream long stream.

@param <N>              the type parameter
@param numberCollection the number collection
@return the long stream

public static <N extends Number> LongStream
    buildLongStream(Collection<N> numberCollection) {
        return numberCollection.stream().mapToLong(Number::longValue);
    }

final public List SetString() throws ParseException {
                     List ans = new ArrayList(); Token tok;
    jj_consume_token(11);
    tok = jj_consume_token(STRING_LITERAL);
      ans.add(ParseUtil.parseStringLiteral(tok.image));
    label_2:
    while (true) {
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case 13:
        ;
        break;
      default:
        jj_la1[15] = jj_gen;
        break label_2;
      }
      jj_consume_token(13);
      tok = jj_consume_token(STRING_LITERAL);
        ans.add(ParseUtil.parseStringLiteral(tok.image));
    }
    jj_consume_token(12);
    {if (true) return ans;}
    throw new Error("Missing return statement in function");
  }

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


Question:
Serialize all informations of this PDU object to its byte representation.

@return The byte representation of this PDU.
@throws InternetSCSIException If any violation of the iSCSI-Standard emerge.
@throws IOException if an I/O error occurs.

public final ByteBuffer serialize () throws InternetSCSIException , IOException {

        basicHeaderSegment.getParser().checkIntegrity();

        final ByteBuffer pdu = ByteBuffer.allocate(calcSize());

        int offset = 0;
        offset += basicHeaderSegment.serialize(pdu, offset);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Serialized Basic Header Segment:\n" + toString());
        }

        offset += serializeAdditionalHeaderSegments(pdu, offset);

        // write header digest
        // TODO: Move CRC calculation in BasicHeaderSegment.serialize?
        if (basicHeaderSegment.getParser().canHaveDigests()) {
            offset += serializeDigest(pdu, headerDigest);
        }

        // serialize data segment
        offset += serializeDataSegment(pdu, offset);

        // write data segment digest
        // TODO: Move CRC calculation in BasicHeaderSegment.serialize?
        if (basicHeaderSegment.getParser().canHaveDigests()) {
            offset += serializeDigest(pdu, dataDigest);
        }

        return (ByteBuffer) pdu.rewind();
    }

def deserialize(dataone_exception_xml):
    """"""
    # logging.debug('dataone_exception_xml="{}"'
    # .format(d1_common.xml.pretty_xml(dataone_exception_xml)))
    try:
        dataone_exception_pyxb = d1_common.xml.deserialize_d1_exception(
            dataone_exception_xml
        )
    except ValueError as e:
        raise ServiceFailure(
            detailCode='0',
            description='Deserialization failed. error="{}" doc="{}"'.format(
                str(e),
                '<empty response>'
                if not dataone_exception_xml
                else dataone_exception_xml,
            ),
            traceInformation=traceback.format_exc(),
        )
    else:
        x = create_exception_by_name(
            dataone_exception_pyxb.name,
            dataone_exception_pyxb.detailCode,
            dataone_exception_pyxb.description,
            _get_trace_information_content(dataone_exception_pyxb),
            dataone_exception_pyxb.identifier,
            dataone_exception_pyxb.nodeId,
        )
        return x

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


Question:
Return amount of limit used, taking time drift into account.

 @return [Integer] amount used

def used
      return 0 if max.zero?

      expiry = redis.pttl(key)
      case expiry
      when -1  # key exists but has no associated expire
        raise Errors::InvalidKeyError, "Redis key #{key} has no expire time set"
      when -2  # key does not exist
        return 0
      end

      (max * expiry / (period * 1000.0)).ceil
    end

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

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

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

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

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

	return results, nil
}

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


Question: // Returns a list of available pools

func (c *ServicedCli) pools() (data []string) {
	pools, err := c.driver.GetResourcePools()
	if err != nil || pools == nil || len(pools) == 0 {
		return
	}

	data = make([]string, len(pools))
	for i, p := range pools {
		data[i] = p.ID
	}

	return
}

private function checkResultCount(array $result, $query)
    {
        if (count($result) === 0) {
            throw new RowNotFoundException('Row not found for query: ' . $query);
        }

        if (count($result) > 1) {
            throw new MultipleRowFoundException('Multiple row found for query: ' . $query);
        }
    }

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


Question:
Chain function which returns a function.

    :param routines: routines to process.

def _process_function_list(self, routines):

    def processing(*args, **kwargs):
        """Execute routines with input args and kwargs and add result in
        chaining.___.

        :param tuple args: routines varargs.
        :param dict kwargs: routines kwargs.
        :return: chaining chaining.
        :rtype: Chaining
        """

        results = [None] * len(routines)
        for index, routine in enumerate(routines):
            if isinstance(routine, Exception):
                result = routine
            else:
                try:
                    result = routine(*args, **kwargs)
                except AttributeError as excp:
                    result = excp
            results[index] = result
        self.___.append(results)

        return self

    return processing

def _DoPredicates(args, context, callback, trace):

    block = args
    value = context.Lookup('@')
    for (predicate, args, func_type), statements in block.clauses:
        if func_type == ENHANCED_FUNC:
            do_clause = predicate(value, context, args)
        else:
            do_clause = predicate(value)

        if do_clause:
            if trace: trace.Push(predicate)
            _Execute(statements, context, callback, trace)
            if trace: trace.Pop()
            break

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


Question: Return all the attributes as a params hash.

def to_params
      attrs = Hash.new
      instance_variables.each do |ivar|
        name = ivar[1..-1]
        attrs[name.to_sym] = instance_variable_get(ivar) if respond_to? "#{name}="
      end
      attrs
    end

def navigate(store_id, category_id, node_id)
      response = api_get("Stores.egg", "Navigation", "#{store_id}/#{category_id}/#{node_id}")
      categories = JSON.parse(response.body)
    end

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


Question:
Takes a URL and a key=>value array to generate a POST PSR-7 request object

@param string $url The URL to make a request to
@param array $params Key=>Value array of data to send
@return \Psr\Http\Message\ResponseInterface

public function post($url, array $params)
    {
        $request = new Request(
            $url,
            'POST',
            'php://temp',
            ['content-type' => 'application/json']
        );

        $request->getBody()->write(json_encode($params));
        return $this->send($request);
    }

public void marshall(GetMethodRequest getMethodRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getMethodRequest.getRestApiId(), RESTAPIID_BINDING);
            protocolMarshaller.marshall(getMethodRequest.getResourceId(), RESOURCEID_BINDING);
            protocolMarshaller.marshall(getMethodRequest.getHttpMethod(), HTTPMETHOD_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Returns the shared link password currently set in the request.

@return  the password for the item's shared link, or null if not set.

public String getPassword(){
        return mBodyMap.containsKey(BoxItem.FIELD_SHARED_LINK) ?
                ((BoxSharedLink) mBodyMap.get(BoxItem.FIELD_SHARED_LINK)).getPassword() :
                null;
    }

func (s *service) AuthorizeToken(ctx context.Context, hostname, path, token string) (*sessions.Session, error) {
	resourceCh, resourceErrCh := make(chan *resources.Resource, 1), make(chan error, 1)
	sessionCh, sessionErrCh := make(chan *sessions.Session, 1), make(chan error, 1)
	go func() {
		session, err := s.sessionRepo.FindByToken(ctx, token)
		if err != nil {
			sessionErrCh <- err
			close(sessionCh)
			return
		}
		sessionCh <- session
		close(sessionErrCh)
	}()
	go func() {
		resource, err := s.resourceRepo.FindByHostname(ctx, hostname)
		if err != nil {
			resourceErrCh <- err
			close(resourceCh)
			return
		}
		resourceCh <- resource
		close(resourceErrCh)
	}()
	// If we can't find a resource, we deny the access
	// Otherwise, the access is denied with an error
	if err := <-resourceErrCh; err != nil {
		if isErrNotFound(err) {
			return nil, withErrDeniedAccess(err)
		}
		return nil, err

	}
	resource := <-resourceCh
	// If the found resource is marked as public, we allow the access without condition
	if resource.Public != nil && *resource.Public {
		return nil, nil
	}
	// If no session is found for the token, we initiate a guest session
	// Otherwise, the access is denied with an error
	if err := <-sessionErrCh; err != nil {
		if isErrNotFound(err) {
			return s.authorizeGuestSession(ctx, path, resource.Name)
		}
		return nil, err
	}
	foundSession := <-sessionCh
	// If a session is found, we try to authorize it
	session, err := s.authorizeSession(ctx, path, resource.Name, foundSession)
	if err != nil {
		// If denied, we at least try to authorize as guest
		if isErrDeniedAccess(err) {
			if _, err := s.authorizeGuestSession(ctx, path, resource.Name); err != nil {
				return nil, err
			}
			return foundSession, nil
		}
		return nil, err
	}
	// If found, we return it
	return session, nil
}

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


Question: // Init the Resource. Requires a *bitset.BitSet.

func (r *AutoVLANCfgResource) Init(rsrcCfg interface{}) error {
	var ok bool
	r.VLANs, ok = rsrcCfg.(*bitset.BitSet)
	if !ok {
		return core.Errorf("Invalid type for vlan resource config")
	}
	err := r.Write()
	if err != nil {
		return err
	}
	defer func() {
		if err != nil {
			r.Clear()
		}
	}()

	oper := &AutoVLANOperResource{FreeVLANs: r.VLANs}
	oper.StateDriver = r.StateDriver
	oper.ID = r.ID
	return oper.Write()
}

def set_bytes_at_rva(self, rva, data):

        offset = self.get_physical_by_rva(rva)
        if not offset:
            raise False

        return self.set_bytes_at_offset(offset, data)

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


Question: function _renderPlotStock()

private function _renderAreaChart($groupCount, $dimensions = '2d') {
		require_once('jpgraph_line.php');

		$this->_renderCartesianPlotArea();

		for($i = 0; $i < $groupCount; ++$i) {
			$this->_renderPlotLine($i,True,False,$dimensions);
		}
	}

def get_plot_panel(self):
        """"""

        plot_type_no = self.chart_type_book.GetSelection()
        return self.chart_type_book.GetPage(plot_type_no)

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


Question:
Function to revert a specific wiki page (Requires login) (UNTESTED).

        Parameters:
            title (str): The title of the wiki page to update.
            version (int): The version to revert to.

def wiki_revert(self, title, version):

        params = {'title': title, 'version': version}
        return self._get('wiki/revert', params, method='PUT')

def _update(self):

        """

        # Step 1 from alg.10.7.
        self._grad.get_grad(self._z_old)
        y_old = self._z_old - self._beta * self._grad.grad

        # Step 2 from alg.10.7.
        self._x_new = self._prox.op(y_old, extra_factor=self._beta)

        # Step 5 from alg.10.7.
        self._z_new = self._x_old + self._lambda * (self._x_new - self._x_old)

        # Restarting step from alg.4-5 in [L2018]
        if self._is_restart(self._z_old, self._x_new, self._x_old):
            self._z_new = self._x_new

        # Update old values for next iteration.
        np.copyto(self._x_old, self._x_new)
        np.copyto(self._z_old, self._z_new)

        # Update parameter values for next iteration.
        self._update_param()

        # Test cost function for convergence.
        if self._cost_func:
            self.converge = self.any_convergence_flag() or \
                            self._cost_func.get_cost(self._x_new)

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


Question: Compute non-linear term, equation 6, page 970.

def _compute_non_linear_term(self, C, pga_only, sites):

        Vref = self.CONSTS['Vref']
        Vcon = self.CONSTS['Vcon']
        c = self.CONSTS['c']
        n = self.CONSTS['n']
        lnS = np.zeros_like(sites.vs30)

        # equation (6a)
        idx = sites.vs30 < Vref
        lnS[idx] = (
            C['sb1'] * np.log(sites.vs30[idx] / Vref) +
            C['sb2'] * np.log(
                (pga_only[idx] + c * (sites.vs30[idx] / Vref) ** n) /
                ((pga_only[idx] + c) * (sites.vs30[idx] / Vref) ** n)
            )
        )

        # equation (6b)
        idx = sites.vs30 >= Vref
        new_sites = sites.vs30[idx]
        new_sites[new_sites > Vcon] = Vcon
        lnS[idx] = C['sb1'] * np.log(new_sites / Vref)

        return lnS

static LongCumulative newNoopLongCumulative(
      String name, String description, String unit, List<LabelKey> labelKeys) {
    return NoopLongCumulative.create(name, description, unit, labelKeys);
  }

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


Question:
Test if the merge field Tag exists in an array
@param string $tagName
@param array $tags
@return mixed (Boolean true|false) or $tag['merge_id']

protected function tagExists($tagName, array $tags)
    {
        foreach ($tags as $tag) {
            if ($tag['tag'] == $tagName) {
                if (array_key_exists('merge_id', $tag)) {
                    return $tag['merge_id'];
                }
                return true;
            }
        }
        return false;
    }

protected function buildInsertQuery(SQLInsert $query, array &$parameters)
    {
        $nl = $this->getSeparator();
        $into = $query->getInto();

        // Column identifiers
        $columns = $query->getColumns();
        $sql = "INSERT INTO {$into}{$nl}(" . implode(', ', $columns) . ")";

        // Values
        $sql .= "{$nl}VALUES";

        // Build all rows
        $rowParts = array();
        foreach ($query->getRows() as $row) {
            // Build all columns in this row
            $assignments = $row->getAssignments();
            // Join SET components together, considering parameters
            $parts = array();
            foreach ($columns as $column) {
                // Check if this column has a value for this row
                if (isset($assignments[$column])) {
                    // Assigment is a single item array, expand with a loop here
                    foreach ($assignments[$column] as $assignmentSQL => $assignmentParameters) {
                        $parts[] = $assignmentSQL;
                        $parameters = array_merge($parameters, $assignmentParameters);
                        break;
                    }
                } else {
                    // This row is missing a value for a column used by another row
                    $parts[] = '?';
                    $parameters[] = null;
                }
            }
            $rowParts[] = '(' . implode(', ', $parts) . ')';
        }
        $sql .= $nl . implode(",$nl", $rowParts);

        return $sql;
    }

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


Question: Fetch data from year, month to current year month data

def fetch_from(self, year: int, month: int):
        """"""
        self.raw_data = []
        self.data = []
        today = datetime.datetime.today()
        for year, month in self._month_year_iter(month, year, today.month, today.year):
            self.raw_data.append(self.fetcher.fetch(year, month, self.sid))
            self.data.extend(self.raw_data[-1]['data'])
        return self.data

public function buildRecordQuery($type, $uid, $pageId): Query
    {
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
        $site = $siteRepository->getSiteByPageId($pageId);

        return $this->newSearchQuery('')
            ->useQueryString('*:*')
            ->useFilter('type:' . $type . ' AND uid:' . $uid, 'type')
            ->useFilter('siteHash:' . $site->getSiteHash(), 'siteHash')
            ->useReturnFields(ReturnFields::fromString('*'))
            ->useSortings(Sortings::fromString('type asc, title asc'))
            ->useQueryType('standard')
            ->getQuery();
    }

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


Question:
Sets which algorithms are allowed for the credentials that are created. Array of constants from the COSEAlgorithm
enumeration (e.g. COSEAlgorithm::ES256)
@param int[] $algorithms
@throws ConfigurationException
@see CoseAlgorithm

public function setAllowedAlgorithms(array $algorithms) : void
    {
        $validList = [];
        foreach ($algorithms as $algorithm) {
            if (!\is_int($algorithm)) {
                throw new ConfigurationException('Algorithms should be integer constants from the COSEAlgorithm enumeratons.');
            }

            if (!\in_array($algorithm, self::SUPPORTED_ALGORITHMS, true)) {
                throw new ConfigurationException(sprintf('Unsupported algorithm "%d".', $algorithm));
            }
            $validList[] = $algorithm;
        }
        $this->algorithms = $validList;
    }

public static EncryptionMode getEncryptionModeCipher(String encryptionMode) {
	if (encryptionMode==null) {
		return null;
	}
	switch (encryptionMode) {
		case "agile": return EncryptionMode.agile;
		case "binaryRC4": return EncryptionMode.binaryRC4;
		case "cryptoAPI": return EncryptionMode.cryptoAPI;
		case "standard": return EncryptionMode.standard;
		default:
			LOG.error("Uknown enncryption mode \""+encryptionMode+"\"");
			break;
		//case "xor": return EncryptionMode.xor; // does not seem to be supported anymore
	}
	return null;
}

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


Question:
取数据的真实区间,返回的时候用 start,end=QA_util_get_real_datelist
    @yutiansut
    2017/8/10

    当start end中间没有交易日 返回None, None
    @yutiansut/ 2017-12-19

def QA_util_get_real_datelist(start, end):

    real_start = QA_util_get_real_date(start, trade_date_sse, 1)
    real_end = QA_util_get_real_date(end, trade_date_sse, -1)
    if trade_date_sse.index(real_start) > trade_date_sse.index(real_end):
        return None, None
    else:
        return (real_start, real_end)

func (c *Client) ListServiceUsageEventsByQuery(query url.Values) ([]ServiceUsageEvent, error) {
	var serviceUsageEvents []ServiceUsageEvent
	requestURL := fmt.Sprintf("/v2/service_usage_events?%s", query.Encode())
	for {
		var serviceUsageEventsResponse ServiceUsageEventsResponse
		r := c.NewRequest("GET", requestURL)
		resp, err := c.DoRequest(r)
		if err != nil {
			return nil, errors.Wrap(err, "error requesting events")
		}
		defer resp.Body.Close()
		if err := json.NewDecoder(resp.Body).Decode(&serviceUsageEventsResponse); err != nil {
			return nil, errors.Wrap(err, "error unmarshaling events")
		}
		for _, e := range serviceUsageEventsResponse.Resources {
			e.Entity.GUID = e.Meta.Guid
			e.Entity.CreatedAt = e.Meta.CreatedAt
			e.Entity.c = c
			serviceUsageEvents = append(serviceUsageEvents, e.Entity)
		}
		requestURL = serviceUsageEventsResponse.NextURL
		if requestURL == "" {
			break
		}
	}
	return serviceUsageEvents, nil
}

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


Question: // comparator returns the comparator function for the attribute

func (a *Attribute) comparator() compareFn {
	if a.Bool != nil {
		return a.boolComparator
	}
	if a.String != nil {
		return a.stringComparator
	}
	if a.Int != nil || a.Float != nil {
		return a.numberComparator
	}

	return nullComparator
}

func (eng *Engine) ObserveAt(t time.Time, name string, value interface{}, tags ...Tag) {
	eng.measure(t, name, value, Histogram, tags...)
}

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


Question: Encode a single token byte-wise into integer ids.

def _byte_encode(self, token):
    """"""
    # Vocab ids for all bytes follow ids for the subwords
    offset = len(self._subwords)
    if token == "_":
      return [len(self._subwords) + ord(" ")]
    return [i + offset for i in list(bytearray(tf.compat.as_bytes(token)))]

@NotNull
    @ObjectiveCName("requestIntegrationTokenCommandWithGid:")
    public Command<String> requestIntegrationToken(int gid) {
        return callback -> modules.getGroupsModule().requestIntegrationToken(gid)
                .then(v -> callback.onResult(v))
                .failure(e -> callback.onError(e));
    }

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


Question:
ASCII files have no headers. Following synphot, this
        routine will assume the first column is wavelength in Angstroms,
        and the second column is throughput (dimensionless).

def _readASCII(self, filename):
        """"""
        self.waveunits = units.Units('angstrom')
        self.throughputunits = 'none'
        wlist, tlist = self._columnsFromASCII(filename)
        self._wavetable = N.array(wlist, dtype=N.float64)
        self._throughputtable = N.array(tlist, dtype=N.float64)

def write_tmp_i3status_config(self, tmpfile):

        # order += ...
        for module in self.py3_config["i3s_modules"]:
            self.write_in_tmpfile('order += "%s"\n' % module, tmpfile)
        self.write_in_tmpfile("\n", tmpfile)
        # config params for general section and each module
        for section_name in ["general"] + self.py3_config["i3s_modules"]:
            section = self.py3_config[section_name]
            self.write_in_tmpfile("%s {\n" % section_name, tmpfile)
            for key, value in section.items():
                # don't include color values except in the general section
                if key.startswith("color"):
                    if (
                        section_name.split(" ")[0] not in I3S_COLOR_MODULES
                        or key not in I3S_ALLOWED_COLORS
                    ):
                        continue
                # Set known fixed format for time and tztime so we can work
                # out the timezone
                if section_name.split()[0] in TIME_MODULES:
                    if key == "format":
                        value = TZTIME_FORMAT
                    if key == "format_time":
                        continue
                if isinstance(value, bool):
                    value = "{}".format(value).lower()
                self.write_in_tmpfile('    %s = "%s"\n' % (key, value), tmpfile)
            self.write_in_tmpfile("}\n\n", tmpfile)
        tmpfile.flush()

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


Question:
sets values from a QuickSettings object, only keeping values that
            are not already defined on the main object

def setdefaults(self, from_qs):

        for k in from_qs.keys():
            from_value = from_qs[k]
            fv_is_qs = isinstance(from_value, QuickSettings)
            self_value = self.get(k, None)
            sv_is_qs = isinstance(self_value, QuickSettings)
            if self_value is None:
                # we don't have a value, so just take the value of the from
                # object
                self[k] = from_value
            elif sv_is_qs and fv_is_qs:
                self_value.setdefaults(from_value)

func (c *ClientsetCAStore) addKey(name string, keysetType kops.KeysetType, item *kops.KeysetItem) error {
	create := false
	client := c.clientset.Keysets(c.namespace)
	keyset, err := client.Get(name, v1.GetOptions{})
	if err != nil {
		if errors.IsNotFound(err) {
			keyset = nil
		} else {
			return fmt.Errorf("error reading keyset %q: %v", name, err)
		}
	}
	if keyset == nil {
		keyset = &kops.Keyset{}
		keyset.Name = name
		keyset.Spec.Type = keysetType
		create = true
	}
	keyset.Spec.Keys = append(keyset.Spec.Keys, *item)
	if create {
		if _, err := client.Create(keyset); err != nil {
			return fmt.Errorf("error creating keyset %q: %v", name, err)
		}
	} else {
		if _, err := client.Update(keyset); err != nil {
			return fmt.Errorf("error updating keyset %q: %v", name, err)
		}
	}
	return nil
}

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


Question: Return the file name for +type+ with +suffix+ (if any) for this clock.

def file_path(type = nil, suffix = '.dat')
      name = self.case.class.benchmark_name.dup
      name << '#' << short_name
      type and name << '-' << type
      name << suffix
      File.expand_path(name, self.case.class.output_dir)
    end

protected function getTempFile($extenstion = null)
    {
        $extenstion = is_null($extenstion) ? '' : '.'.$extenstion;
        return tempnam($this->tmp, 'jitim_'.$extenstion);
    }

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


Question:
Different possibilities for True: ☑✔✓✅👍✔
       Different possibilities for False: ✕✖✗✘✖❌⛔❎👎🛑🔴

def bool_to_unicode(b):
    """"""
    b = bool(b)
    if b is True:  return u"✅"
    if b is False: return u"❎"

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

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


Question:
Add driverChain and get orm config

@return \Doctrine\ORM\Configuration

public function getConfiguration()
    {
        $driverChain = $this->getMetadataDriverImpl();
        // Inject the driverChain into the doctrine config
        $this->configuration->setMetadataDriverImpl($driverChain);
        return $this->configuration;
    }

private function connect($dsn, $username, $password, array $options, $charset)
    {
        $sessionMode = array_key_exists('session_mode', $options) ? $options['session_mode'] : null;

        if (array_key_exists(PDO::ATTR_PERSISTENT, $options) && $options[PDO::ATTR_PERSISTENT]) {
            $this->dbh = @oci_pconnect($username, $password, $dsn, $charset, $sessionMode);
        } else {
            $this->dbh = @oci_connect($username, $password, $dsn, $charset, $sessionMode);
        }

        if (! $this->dbh) {
            $e = oci_error();
            throw new Oci8Exception($e['message']);
        }
    }

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


Question:
Adds a value to a specific option (or set if it's not an array).

@param  string $name  The name of the option.
@param  mixed  $value The value of the option to set.
@return array         The setted value.

public function add($name, $value)
    {
        $config = $this->option($name);
        list($key, $extra) = $this->_splitOptionName($name);

        if ($config['array']) {
            $this->_values[$key][$extra][] = $value;
        } else {
            $this->set($name, $value);
        }
        return $this->_values[$key][$extra];
    }

public function parameterize(TemplateInterface $template)
    {
        $params = [];

        foreach ($template->getRequirements() as $key => $requirement) {
            if (!$this->input->hasOption($key) || !$this->input->getOption($key)) {
                list($prompt, $default) = $requirement;

                if ('description' === $key) {
                    $v = $this->style->ask($prompt.' (enter "e" to open editor)', $default);

                    if ('e' === $v) {
                        $editor = $this->getHelperSet()->get('editor');
                        $v = $editor->fromString('');
                    }
                } else {
                    if ('branch' === $key && $this->input->hasOption('base') && $this->input->getOption('base')) {
                        $default = $this->input->getOption('base');
                    }
                    if (1 < count($choices = explode('|', $default))) {
                        $v = $this->style->choice($prompt.' ', $choices, $choices[0]);
                    } else {
                        $v = $this->style->ask($prompt.' ', $default);
                    }
                }
            } else {
                $v = $this->input->getOption($key);
            }

            $params[$key] = $v;
        }

        $template->bind($params);
    }

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


Question: // LogMode set log mode, `true` for detailed logs, `false` for no log, default, will only print error logs

func (s *DB) LogMode(enable bool) *DB {
	if enable {
		s.logMode = detailedLogMode
	} else {
		s.logMode = noLogMode
	}
	return s
}

private function configureFormatter(OutputFormatter $formatter)
    {
        $style = new OutputFormatterStyle('yellow', null, ['bold']);
        $formatter->setStyle('pathbold', $style);

        $style = new OutputFormatterStyle('green');
        $formatter->setStyle('localname', $style);

        $style = new OutputFormatterStyle(null, null, ['bold']);
        $formatter->setStyle('node', $style);

        $style = new OutputFormatterStyle('blue', null, ['bold']);
        $formatter->setStyle('templatenode', $style);

        $style = new OutputFormatterStyle('blue', null, []);
        $formatter->setStyle('templateproperty', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property', $style);

        $style = new OutputFormatterStyle('magenta', null, ['bold']);
        $formatter->setStyle('node-type', $style);

        $style = new OutputFormatterStyle('magenta', null, []);
        $formatter->setStyle('property-type', $style);

        $style = new OutputFormatterStyle(null, null, []);
        $formatter->setStyle('property-value', $style);

        $style = new OutputFormatterStyle(null, 'red', []);
        $formatter->setStyle('exception', $style);
    }

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


Question:
Register bindings for the Handler Locator.

@return void

protected function registerLocator()
    {
        $this->app->singleton('tactician.locator', function($app) {

            $commandNamespace = $this->config('command_namespace');
            $handlerNamespace = $this->config('handler_namespace');
            $locator           = $this->config('locator');

            return (new $locator($this->app, $commandNamespace, $handlerNamespace));
        });
    }

func (r *Remote) CommandFunc(m MatcherFunc, f CommandFunc) {
	r.service.HandleCommand(m, f)
}

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


Question:
Load the LDAP configuration from a YAML file. See the 'resources/config' folder for an example.

@param string $file The path to the file.
@return $this
@throws ConfigurationException

public function load($file)
    {
        if (!is_readable($file)) {
            throw new ConfigurationException(sprintf("Cannot read configuration file: %s", $file));
        }

        try {
            $config = Yaml::parse(file_get_contents($file));
        } catch (ParseException $e) {
            throw new ConfigurationException('Error in configuration file: %s', $e->getMessage());
        }

        return $this->loadFromArray($config);
    }

protected function getPathToRecipe(string $recipe): string
    {
        $recipePaths = $this->buildRecipePaths($recipe);

        foreach ($recipePaths as $recipePath) {
            if (file_exists($recipePath)) {
                return $recipePath;
            }
        }

        throw new ConfigurationFileNotFoundException(
            sprintf(
                'Could not resolve path for your recipe. Check %s.',
                implode(', ', $recipePaths)
            )
        );
    }

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


Question: TODO task for generating the on-demand stuff to target assets dir TODO dynamic rule for this, so it can be reapplied when directory changes

function UpdateCachedOndemandAssets() {

      var files = glob.sync('**/*.js', {cwd: path.join(ss.root,options.dirs.code)}); //TODO need root *.js as well
      files.forEach(function(rel) {
        ss.http.cached.route('assets/ondemand/'+ (rel.replace('\\','/')), null, path.join(ss.root, options.dirs.code, rel) );
      },this);

      files = glob.sync('**/*.js', {cwd: path.join(ss.root,options.dirs.workers)}); //TODO need root *.js as well
      files.forEach(function(rel) {
        ss.http.cached.route('assets/workers/'+ (rel.replace('\\','/')), null, path.join(ss.root, options.dirs.workers, rel) );
      },this);
    }

def generic_insert_with_folder(folder_name, file_name, template_name, args):

    # First we make sure views are a package instead a file
    if not os.path.isdir(
        os.path.join(
            args['django_application_folder'],
            folder_name
        )
    ):
        os.mkdir(os.path.join(args['django_application_folder'], folder_name))
        codecs.open(
            os.path.join(
                args['django_application_folder'],
                folder_name,
                '__init__.py'
            ),
            'w+'
        )

    view_file = create_or_open(
        os.path.join(
            folder_name,
            '{}.py'.format(file_name)
        ),
        '',
        args
    )
    # Load content from template
    render_template_with_args_in_file(
        view_file,
        os.path.join(
            BASE_TEMPLATES_DIR,
            template_name
        ),
        model_name=args['model_name'],
        model_prefix=args['model_prefix'],
        model_name_lower=args['model_name'].lower(),
        application_name=args['django_application_folder'].split("/")[-1]
    )
    view_file.close()

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


Question:
Render cell content with left and right padding depending on the column width

@param CellInterface $cell
@param int $colWidth
@return string

private function renderCell(CellInterface $cell, int $colWidth) : string
    {
        $content = self::CHAR_CELL_PADDING . $cell->getValue()
                . str_repeat(self::CHAR_CELL_PADDING, ($colWidth - $cell->getWidth() + 1));

        return $content;
    }

private Control createPageControl( Composite parent )
    {
        Composite composite = new Composite( parent, SWT.NONE );
        composite.setLayout( new GridLayout( 1, false ) );
        GridData gridData = new GridData( GridData.HORIZONTAL_ALIGN_FILL
                | GridData.VERTICAL_ALIGN_FILL );

        composite.setLayoutData( gridData );

        Label fieldLabel = new Label( composite, SWT.NONE );
        fieldLabel.setText( "&Query Text:" );

        m_queryTextField = new Text( composite, SWT.BORDER
                | SWT.V_SCROLL | SWT.H_SCROLL );
        GridData data = new GridData( GridData.FILL_HORIZONTAL );
        data.heightHint = 100;
        m_queryTextField.setLayoutData( data );
        m_queryTextField.addModifyListener( new ModifyListener( )
        {
            public void modifyText( ModifyEvent e )
            {
                validateData();
            }
        } );

        setPageComplete( false );
        return composite;
    }

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


Question:
// Launch opens the described or returns an error. The TTY will be protected, and
// SIGQUIT, SIGTERM, and SIGINT will all be trapped.

func (e Editor) Launch(path string) error {
	if len(e.Args) == 0 {
		return fmt.Errorf("no editor defined, can't open %s", path)
	}
	abs, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	args := e.args(abs)
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = os.Stdin
	klog.V(5).Infof("Opening file with editor %v", args)
	if err := (term.TTY{In: os.Stdin, TryDev: true}).Safe(cmd.Run); err != nil {
		if err, ok := err.(*exec.Error); ok {
			if err.Err == exec.ErrNotFound {
				return fmt.Errorf("unable to launch the editor %q", strings.Join(e.Args, " "))
			}
		}
		return fmt.Errorf("there was a problem with the editor %q", strings.Join(e.Args, " "))
	}
	return nil
}

def set_signed_in(self, me):

        self.me = me
        self.sign_in_label.configure(text='Signed in')
        self.sign_in_entry.configure(state=tkinter.NORMAL)
        self.sign_in_entry.delete(0, tkinter.END)
        self.sign_in_entry.insert(tkinter.INSERT, utils.get_display_name(me))
        self.sign_in_entry.configure(state=tkinter.DISABLED)
        self.sign_in_button.configure(text='Log out')
        self.chat.focus()

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


Question:
Sets a specific charset to the response

@param charset The charset to use
@return A response object {@link io.mangoo.routing.Response}

public Response andCharset(String charset) {
        Objects.requireNonNull(charset, Required.CHARSET.toString());
        this.charset = charset;

        return this;
    }

private void setHeaders(HttpMessage message, Map<String, String> headers) {
		message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL);
		message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE);
		message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());

		if (headers != null) {
			for (String headerKey : headers.keySet()) {
				message.setHeader(headerKey, headers.get(headerKey));
			}
		}
	}

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


Question: // SetQualificationTypeId sets the QualificationTypeId field's value.

func (s *DisassociateQualificationFromWorkerInput) SetQualificationTypeId(v string) *DisassociateQualificationFromWorkerInput {
	s.QualificationTypeId = &v
	return s
}

def __register_types(self):

        try:
            for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.types']['plugins']:
                cls = entry_point.load()
                self.types[ResourceType.get(cls.resource_type).resource_type_id] = cls
                logger.debug('Registered resource type {}'.format(cls.__name__))
        except SQLAlchemyError as ex:
            logger.warning('Failed loading type information: {}'.format(ex))

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


Question: " a   b c   d e   f " -> [" a   b", "c   d", "e   f "]

function splitWithSingleSpace(text) {
  const parts = [];

  let lastPart = undefined;
  for (const part of text.split(/( +)/g)) {
    if (part !== " ") {
      if (lastPart === " ") {
        parts.push(part);
      } else {
        parts.push((parts.pop() || "") + part);
      }
    } else if (lastPart === undefined) {
      parts.unshift("");
    }

    lastPart = part;
  }

  if (lastPart === " ") {
    parts.push((parts.pop() || "") + " ");
  }

  if (parts[0] === "") {
    parts.shift();
    parts.unshift(" " + (parts.shift() || ""));
  }

  return parts;
}

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question:
/*!
Sets the time of the stop of the script ot \a $time.
If \a $time is not supplied it gets the current \c microtime( true ).
This is used to calculate total execution time and percentages.

static function setScriptStop( $time = false )
    {
        if ( $time === false )
            $time = microtime( true );
        $debug = eZDebug::instance();
        $debug->ScriptStop = $time;
    }

def print_update(self):

        print("\r\n")
        now = datetime.datetime.now()
        print("Update info: (from: %s)" % now.strftime("%c"))

        current_total_size = self.total_stined_bytes + self.total_new_bytes

        if self.total_errored_items:
            print(" * WARNING: %i omitted files!" % self.total_errored_items)

        print(" * fast backup: %i files" % self.total_fast_backup)

        print(
            " * new content saved: %i files (%s %.1f%%)"
            % (
                self.total_new_file_count,
                human_filesize(self.total_new_bytes),
                to_percent(self.total_new_bytes, current_total_size),
            )
        )

        print(
            " * stint space via hardlinks: %i files (%s %.1f%%)"
            % (
                self.total_file_link_count,
                human_filesize(self.total_stined_bytes),
                to_percent(self.total_stined_bytes, current_total_size),
            )
        )

        duration = default_timer() - self.start_time
        performance = current_total_size / duration / 1024.0 / 1024.0
        print(" * present performance: %.1fMB/s\n" % performance)

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


Question:
// makeDatabaseHandles raises out the number of allowed file handles per process
// for Geth and returns half of the allowance to assign to the database.

func makeDatabaseHandles() int {
	limit, err := fdlimit.Maximum()
	if err != nil {
		Fatalf("Failed to retrieve file descriptor allowance: %v", err)
	}
	raised, err := fdlimit.Raise(uint64(limit))
	if err != nil {
		Fatalf("Failed to raise file descriptor allowance: %v", err)
	}
	return int(raised / 2) // Leave half for networking and other stuff
}

def create(self, item, **kwargs):

        response = self._new_response()
        if self._prototype_handler.check(item, 'create', response):
            self._encrypt(item)
            params = {'Item': item}
            self._call_ddb_method(self.table.put_item,
                                  params, response)
            if response.status == 'success':
                response.data = item
        response.prepare()
        return response

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


Question:
Get the view template name.

@return string

public function getTemplate()
    {
        if (null === $this->template) {
            $this->template = $this->getTemplatePathDefault('layout');
        }

        return $this->template;
    }

public function canRender(ControllerContext $controllerContext)
    {
        $this->setControllerContext($controllerContext);
        try {
            $this->getTemplateSource();
            return true;
        } catch (Exception\InvalidTemplateResourceException $e) {
            return false;
        }
    }

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


Question: Recursively adds directories to a zip file.

private void addDirectoryToZip(File topDirectory, File directory, ZipOutputStream out) throws IOException {
    Path top = Paths.get(topDirectory.getAbsolutePath());

    File[] files = directory.listFiles();
    byte[] buffer = new byte[BUFFER_SIZE];

    for (int i = 0; i < files.length; i++) {
      Path entry = Paths.get(files[i].getAbsolutePath());
      Path relative = top.relativize(entry);
      String entryName = relative.toString();
      if (files[i].isDirectory()) {
        entryName += FILE_SEPARATOR;
      }

      out.putNextEntry(new ZipEntry(entryName.replace("\\", "/")));

      if (!files[i].isDirectory()) {
        try (FileInputStream in = new FileInputStream(files[i])) {
          int bytesRead;
          while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
          }
        }
        out.closeEntry();
      }

      if (files[i].isDirectory()) {
        addDirectoryToZip(topDirectory, files[i], out);
      }
    }
  }

def extract_all_snow_tweets_from_disk_generator(json_folder_path):

    # Get a generator with all file paths in the folder
    json_file_path_generator = (json_folder_path + "/" + name for name in os.listdir(json_folder_path))

    for path in json_file_path_generator:
        for tweet in extract_snow_tweets_from_file_generator(path):
            yield tweet

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


Question: An enrolled user wants to change their password

def changepassword(self, event):
        """"""

        old = event.data['old']
        new = event.data['new']
        uuid = event.user.uuid

        # TODO: Write email to notify user of password change

        user = objectmodels['user'].find_one({'uuid': uuid})
        if std_hash(old, self.salt) == user.passhash:
            user.passhash = std_hash(new, self.salt)
            user.save()

            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': True
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('Successfully changed password for user', uuid)
        else:
            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': False
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('User tried to change password without supplying old one', lvl=warn)

public void setResSNum(Integer newResSNum) {
		Integer oldResSNum = resSNum;
		resSNum = newResSNum;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.RESOURCE_SECTION_NUMBER__RES_SNUM, oldResSNum, resSNum));
	}

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


Question: // GetTTYWidth returns the width of the controlling TTY if it can or 80.

func GetTTYWidth() int {
	var tty *os.File
	var err error
	if tty, err = os.OpenFile("/dev/tty", os.O_RDWR, 0600); err != nil {
		tty = os.Stdout
	} else {
		defer tty.Close()
	}
	if width, _, err := terminal.GetSize(int(tty.Fd())); err != nil {
		return 80
	} else {
		return width
	}
}

def callback_read_char(self):
        #Override base to get automatic newline
        '''
        if self.keyboard_poll():
            line = self.get_line_buffer() + u'\n'
            self.console.write(u"\r\n")
            # however there is another newline added by
            # self.mode.readline_setup(prompt) which is called by callback_handler_install
            # this differs from GNU readline
            self.add_history(self.mode.l_buffer)
            # TADA:
            self.callback(line)

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


Question: // SetTcpRoute sets the TcpRoute field's value.

func (s *RouteSpec) SetTcpRoute(v *TcpRoute) *RouteSpec {
	s.TcpRoute = v
	return s
}

@Override
    public Request<DeleteVpnConnectionRouteRequest> getDryRunRequest() {
        Request<DeleteVpnConnectionRouteRequest> request = new DeleteVpnConnectionRouteRequestMarshaller().marshall(this);
        request.addParameter("DryRun", Boolean.toString(true));
        return request;
    }

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


Question:
/*
Get image sha256 extracted from digest from image manifest.

protected String getSHA256FromManifest(String manifest) {
        if (StringUtils.isBlank(manifest)) {
            return Constants.EMPTY_STRING;
        }

        // sha256 regex, matched group will return string contains digits and chars, String length 64
        String sha256Regex = "sha256:([\\w\\d]{64})";
        Pattern pattern = Pattern.compile(sha256Regex);
        Matcher matcher = pattern.matcher(manifest);

        if(matcher.find()){
            return matcher.group(1);
        } else {
            logger.error("Could not get config -> digest -> sha256 value from manifest");
            logger.error("Manifest content - {}", manifest);
            return Constants.EMPTY_STRING;
        }
    }

private function buildImageId(VersionInfo $versionInfo, Field $field)
    {
        return sprintf(
            '%s-%s-%s',
            $versionInfo->contentInfo->id, $field->id, $versionInfo->versionNo
        );
    }

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


Question:
Determines if a 'real' browser is being used. If the browser is NONE or
HTMLUNIT it is not considered a real browser

@return Boolean: is the browser a 'real' browser

private boolean isRealBrowser() {
        Browser browser = capabilities.getBrowser();
        return browser.getName() != BrowserName.NONE && browser.getName() != BrowserName.HTMLUNIT;
    }

public static function getMeta() {
		$sReturn = '';

		// nofollow, noindex
		if (!self::$_bRobotsIndex || !self::$_bRobotsFollow) {
			$sReturn .= '<meta name="ROBOTS" content="'
				.(self::$_bRobotsIndex  ? 'INDEX'  : 'NOINDEX').', '
				.(self::$_bRobotsFollow ? 'FOLLOW' : 'NOFOLLOW').'">'."\n";
		}

		// css
		foreach (array_merge(self::getConfig()['css'], self::$_lCSS) as $sCSS) {
			$sRel = 'stylesheet';
			if (substr($sCSS, -5) === '.less') {
				$sRel .= '/less';
			}
			$sReturn .= '<link rel="' . $sRel . '" href="' . $sCSS . '" type="text/css" />'."\n";
		}

		// js
		foreach (array_merge(self::getConfig()['js'], self::$_lJS) as $sJS) {
			$sReturn .= '<script src="' . $sJS . '"></script>' . "\n";
		}

		if (self::$_sAddMeta) {
			$sReturn .= self::$_sAddMeta;
		}

		return $sReturn;
	}

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