Question:
Returns accuracy score evaluation result.

      - overall accuracy
      - mean accuracy
      - mean IU
      - fwavacc

def label_accuracy_score(label_trues, label_preds, n_class):

    hist = np.zeros((n_class, n_class))
    for lt, lp in zip(label_trues, label_preds):
        hist += _fast_hist(lt.flatten(), lp.flatten(), n_class)
    acc = np.diag(hist).sum() / hist.sum()
    with np.errstate(divide='ignore', invalid='ignore'):
        acc_cls = np.diag(hist) / hist.sum(axis=1)
    acc_cls = np.nanmean(acc_cls)
    with np.errstate(divide='ignore', invalid='ignore'):
        iu = np.diag(hist) / (
            hist.sum(axis=1) + hist.sum(axis=0) - np.diag(hist)
        )
    mean_iu = np.nanmean(iu)
    freq = hist.sum(axis=1) / hist.sum()
    fwavacc = (freq[freq > 0] * iu[freq > 0]).sum()
    return acc, acc_cls, mean_iu, fwavacc

def chars(self, font, block):

        if font:
            font_files = self._getFont(font)
        else:
            font_files = fc.query()
        code_points = self._getFontChars(font_files)

        if not block:
            blocks = all_blocks
            ranges_column = map(itemgetter(3), blocks)
            overlapped = Ranges(code_points).getOverlappedList(ranges_column)
        else:
            blocks = [block]
            overlapped = [Ranges(code_points).getOverlapped(block[3])]

        if self._display['group']:
            char_count = block_count = 0
            for i, block in enumerate(blocks):
                o_count = len(overlapped[i])
                if o_count:
                    block_count += 1
                    char_count += o_count
                    total = sum(len(r) for r in block[3])
                    percent = 0 if total == 0 else o_count / total
                    print("{0:>6}  {1:47} {2:>4.0%} ({3}/{4})".format(block[0], block[2], percent, o_count, total))
                    if self._display['list']:
                        for point in overlapped[i]:
                            self._charInfo(point, padding=9)
            self._charSummary(char_count, block_count)
        else:
            for point in code_points:
                self._charInfo(point, padding=7)
            self._charSummary(len(code_points))

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


Question:
// Expunge permanently removes all messages that have the \Deleted flag set from
// the currently selected mailbox. If ch is not nil, sends sequence IDs of each
// deleted message to this channel.

func (c *Client) Expunge(ch chan uint32) error {
	if c.State() != imap.SelectedState {
		return ErrNoMailboxSelected
	}

	cmd := new(commands.Expunge)

	var h responses.Handler
	if ch != nil {
		h = &responses.Expunge{SeqNums: ch}
		defer close(ch)
	}

	status, err := c.execute(cmd, h)
	if err != nil {
		return err
	}
	return status.Err()
}

public function basic_publish(
        $msg,
        $exchange = '',
        $routing_key = '',
        $mandatory = false,
        $immediate = false,
        $ticket = null
    ) {
        $pkt = new AMQPWriter();
        $pkt->write($this->pre_publish($exchange, $routing_key, $mandatory, $immediate, $ticket));

        try {
            $this->connection->send_content(
                $this->channel_id,
                60,
                0,
                mb_strlen($msg->body, 'ASCII'),
                $msg->serialize_properties(),
                $msg->body,
                $pkt
            );
        } catch (AMQPConnectionClosedException $e) {
            $this->do_close();
            throw $e;
        }

        if ($this->next_delivery_tag > 0) {
            $this->published_messages[$this->next_delivery_tag] = $msg;
            $this->next_delivery_tag = bcadd($this->next_delivery_tag, '1', 0);
        }
    }

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


Question:
Construct a greater than (``>``) filter.

        :param value: Filter value
        :return: :class:`filters.Field <filters.Field>` object
        :rtype: filters.Field

def gt(self, value):

        self.op = '>'
        self.negate_op = '<='
        self.value = self._value(value)
        return self

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

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

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

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

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


Question: Show the commands for a given environment.

def show_env(environment):

    if not environment:
        print("You need to supply an environment name")
        return

    parser = read_config()

    try:
        commands = parser.get(environment, "cmd").split("\n")

    except KeyError:
        print("Unknown environment type '%s'" % environment)
        return

    print("Environment: %s\n" % environment)

    for cmd in commands:
        print(cmd)

def set_allowed_by(rack_env, allowed_by)
      Env.new(rack_env).tap do |env|
        env.allowed_by = allowed_by
      end.to_rack
    end

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


Question: // Create new progress bar object using int64 as total

func New64(total int64) *ProgressBar {
	pb := &ProgressBar{
		Total:           total,
		RefreshRate:     DEFAULT_REFRESH_RATE,
		ShowPercent:     true,
		ShowCounters:    true,
		ShowBar:         true,
		ShowTimeLeft:    true,
		ShowElapsedTime: false,
		ShowFinalTime:   true,
		Units:           U_NO,
		ManualUpdate:    false,
		finish:          make(chan struct{}),
	}
	return pb.Format(FORMAT)
}

def PCO_protocol_dispatcher(s):
    """"""
    proto_num = orb(s[0]) * 256 + orb(s[1])
    cls = PCO_PROTOCOL_CLASSES.get(proto_num, Raw)
    return cls(s)

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


Question: Pops the last set of keyword arguments provided to the processor.

def pop_context(self):
        """"""
        processor = getattr(self, 'processor', None)
        if processor is not None:
            pop_context = getattr(processor, 'pop_context', None)
            if pop_context is None:
                pop_context = getattr(processor, 'pop', None)
            if pop_context is not None:
                return pop_context()
        if self._pop_next:
            self._pop_next = False

public static Object[] transformArgs(Val<Expression>[] args) {
        Object[] objects = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            objects[i] = args[i].object();
        }
        return objects;
    }

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


Question:
Integer in words
@param int $amount Amount of objects (0 <= amount <= PHP_INT_MAX)
@param int $gender (MALE, FEMALE or NEUTER)
@return string In-words representation of numeral

public function getInWordsInt($amount, $gender = RUtils::MALE)
    {
        $amount = round($amount);
        return $this->sumString($amount, $gender);
    }

func (v Vocabulary) Word(w string) (Word, error) {
  if w == "" {
    return Word{}, Error("word must be non-empty string")
  }

  if v.c.BigHugeLabsApiKey == "" {
    return Word{}, Error("BigHugeLabsApiKey required.")
  }
  if v.c.WordnikApiKey == "" {
    return Word{}, Error("WordnikApiKey required.")
  }

  meanings, err := v.Meanings(w)
  if err != nil {
    return Word{}, err
  }

  synonyms, err := v.Synonyms(w)
  if err != nil {
    return Word{}, err
  }

  antonyms, err := v.Antonyms(w)
  if err != nil {
    return Word{}, err
  }

  pos, err := v.PartOfSpeech(w)
  if err != nil {
    return Word{}, err
  }

  ue, err := v.UsageExample(w)
  if err != nil {
    return Word{}, err
  }

  return Word{
    Word:         w,
    Meanings:     meanings,
    Synonyms:     synonyms,
    Antonyms:     antonyms,
    PartOfSpeech: pos,
    UsageExample: ue,
  }, nil
}

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


Question:
Get all the pending revisions after the current time

        :return: A list of revisions
        :rtype: list

def __get_pending_revisions(self):

        dttime = time.mktime(datetime.datetime.now().timetuple())
        changes = yield self.revisions.find({
            "toa" : {
                "$lt" : dttime,
            },
            "processed": False,
            "inProcess": None
        })
        if len(changes) > 0:
            yield self.set_all_revisions_to_in_process([change.get("id") for change in changes])

        raise Return(changes)

func Convert_apps_ControllerRevision_To_v1_ControllerRevision(in *apps.ControllerRevision, out *v1.ControllerRevision, s conversion.Scope) error {
	return autoConvert_apps_ControllerRevision_To_v1_ControllerRevision(in, out, s)
}

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


Question: // Meta sets the meta data to be included in the aggregation response.

func (a *MovFnAggregation) Meta(metaData map[string]interface{}) *MovFnAggregation {
	a.meta = metaData
	return a
}

def inject_metadata_term_lists(self, term_dict):
        '''

        '''
        check_topic_model_string_format(term_dict)

        if not self.term_doc_matrix.metadata_in_use():
            raise TermDocMatrixHasNoMetadataException("No metadata is present in the term document matrix")

        self.metadata_term_lists = term_dict
        return self

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


Question:
Get the previous step given the current. Will check available steps to confirm.
@param currentStep
@return

private int getPreviousStep(int currentStep) {
        int prevStep = -1;

        // we find the next available step.
        for (int i = currentStep - 1; i >= STEP_LOGIN; i--) {
            if(isStepEnabled(i)) {
                prevStep = i;
                break;
            }
        }

        return prevStep;
    }

func (l *waiterList) PushFront(e *Entry) {
	waiterElementMapper{}.linkerFor(e).SetNext(l.head)
	waiterElementMapper{}.linkerFor(e).SetPrev(nil)

	if l.head != nil {
		waiterElementMapper{}.linkerFor(l.head).SetPrev(e)
	} else {
		l.tail = e
	}

	l.head = e
}

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


Question:
// New creates a new AuthenticatedGossiper instance, initialized with the
// passed configuration parameters.

func New(cfg Config, selfKey *btcec.PublicKey) *AuthenticatedGossiper {
	gossiper := &AuthenticatedGossiper{
		selfKey:                 selfKey,
		cfg:                     &cfg,
		networkMsgs:             make(chan *networkMsg),
		quit:                    make(chan struct{}),
		chanPolicyUpdates:       make(chan *chanPolicyUpdateRequest),
		prematureAnnouncements:  make(map[uint32][]*networkMsg),
		prematureChannelUpdates: make(map[uint64][]*networkMsg),
		channelMtx:              multimutex.NewMutex(),
		recentRejects:           make(map[uint64]struct{}),
		syncMgr: newSyncManager(&SyncManagerCfg{
			ChainHash:            cfg.ChainHash,
			ChanSeries:           cfg.ChanSeries,
			RotateTicker:         cfg.RotateTicker,
			HistoricalSyncTicker: cfg.HistoricalSyncTicker,
			NumActiveSyncers:     cfg.NumActiveSyncers,
		}),
	}

	gossiper.reliableSender = newReliableSender(&reliableSenderCfg{
		NotifyWhenOnline:  cfg.NotifyWhenOnline,
		NotifyWhenOffline: cfg.NotifyWhenOffline,
		MessageStore:      cfg.MessageStore,
		IsMsgStale:        gossiper.isMsgStale,
	})

	return gossiper
}

public function init(PushPipe $pushPipe, PushSettings $pushSettings)
    {
        $this->pushPipe = $pushPipe;
        $this->pushSettings = $pushSettings;

        if ($pushSettings->isPurgeOnStartup()) {
            $this->brokerModel->purgeQueue($pushSettings->getInputQueue());
        }
    }

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


Question:
Main simulation wrapper
    Load the configuration, run the engine and return the analyze.

def intuition(args):
    '''

    '''

    # Use the provided context builder to fill:
    #   - config: General behavior
    #   - strategy: Modules properties
    #   - market: The universe we will trade on
    with setup.Context(args['context']) as context:

        # Backtest or live engine.
        # Registers configuration and setups data client
        simulation = Simulation()

        # Intuition building blocks
        modules = context['config']['modules']

        # Prepare benchmark, timezone, trading calendar
        simulation.configure_environment(
            context['config']['index'][-1],
            context['market'].benchmark,
            context['market'].timezone)

        # Wire togetether modules and initialize them
        simulation.build(args['session'],
                         modules,
                         context['strategy'])

        # Build data generator
        # NOTE How can I use several sources ?
        data = {'universe': context['market'],
                'index': context['config']['index']}
        # Add user settings
        data.update(context['strategy']['data'])
        # Load backtest and / or live module(s)
        if 'backtest' in modules:
            data['backtest'] = utils.intuition_module(modules['backtest'])
        if 'live' in modules:
            data['live'] = utils.intuition_module(modules['live'])

        # Run the simulation and return an intuition.core.analyzes object
        return simulation(datafeed.HybridDataFactory(**data), args['bot'])

public function afterCompile(ClassType $class): void
	{
		$config = $this->config;

		if ($config->debug === true) {
			$initialize = $class->getMethod('initialize');
			$initialize->addBody(
				'$this->getService(?)->addPanel($this->getService(?));',
				['tracy.bar', $this->prefix('panel')]
			);
		}
	}

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


Question:
@param \Riak\Client\Core\Message\Kv\Content $content
@param \Riak\Client\Core\Query\VClock       $vClock

@return \Riak\Client\Core\Query\RiakObject

private function convertToRiakObject(Content $content, VClock $vClock)
    {
        $object = new RiakObject();

        $object->setVClock($vClock);
        $object->setVtag($content->vtag);
        $object->setValue($content->value);
        $object->setContentType($content->contentType);
        $object->setIsDeleted((bool) $content->deleted);
        $object->setLastModified($content->lastModified);

        if ($content->indexes) {
            $object->setIndexes($this->createRiakIndexList($content->indexes));
        }

        if ($content->metas) {
            $object->setUserMeta(new RiakUsermeta($content->metas));
        }

        if ($content->links) {
            $object->setLinks($this->createRiakLinkList($content->links));
        }

        return $object;
    }

def emit_code_from_ir(compound_match_query, compiler_metadata):
    """"""
    # If the compound match query contains only one match query,
    # just call `emit_code_from_single_match_query`
    # If there are multiple match queries, construct the query string for each
    # individual query and combine them as follows.
    #
    # SELECT EXPAND($result)
    # LET
    #    $optional__0 = (
    #        <query_string_0>
    #    ),
    #    $optional__1 = (
    #        <query_string_1>
    #    ),
    #    $optional__2 = (
    #        <query_string_2>
    #    ),
    #
    #    . . .
    #
    #    $result = UNIONALL($optional__0, $optional__1, . . . )

    match_queries = compound_match_query.match_queries
    if len(match_queries) == 1:
        query_string = emit_code_from_single_match_query(match_queries[0])
    elif len(match_queries) > 1:
        query_string = emit_code_from_multiple_match_queries(match_queries)
    else:
        raise AssertionError(u'Received CompoundMatchQuery with an empty list of MatchQueries: '
                             u'{}'.format(match_queries))

    return query_string

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


Question:
Parse the first line of a message.

@param buff
@return boolean (true means parsed entire line)
@throws Exception

public boolean parseLine(WsByteBuffer buff) throws Exception {
        final boolean bTrace = TraceComponent.isAnyTracingEnabled();
        if (bTrace && tc.isDebugEnabled()) {
            Tr.debug(tc, "parseLine called for " + this);
        }

        //PI34161 - Record the start of the request at the time of parsing
        if ((this instanceof HttpRequestMessageImpl) && ((HttpRequestMessageImpl) this).getServiceContext().getHttpConfig().isAccessLoggingEnabled()) {
            this.startTime = System.nanoTime();
        }

        boolean rc = false;
        int startpos = (bTrace && tc.isDebugEnabled()) ? buff.position() : 0;
        TokenCodes tcRC = TokenCodes.TOKEN_RC_MOREDATA;

        // stop parsing the FirstLine when we either hit the end of it (CRLF)
        // or we hit the end of the buffer and need to read more
        while (!rc) {
            if (0 == this.numFirstLineTokensRead) {
                // first token, skip leading CRLFs (up to 16 blank lines)
                tcRC = skipCRLFs(buff);
                if (TokenCodes.TOKEN_RC_DELIM.equals(tcRC)) {
                    try {
                        tcRC = parseTokenExtract(buff, SPACE, false, LOG_FULL);
                        if (!tcRC.equals(TokenCodes.TOKEN_RC_MOREDATA)) {
                            setParsedFirstToken(getParsedToken());
                        }
                    } catch (MalformedMessageException mme) {
                        // no FFDC required

                        // debug print this failing first token to help figure
                        // out why the error happened, usually buffer corruption
                        // Note: if this was discrimination, then it should just
                        // mean it wasn't our data, but we can't tell here which
                        // path it was (i.e. should it have worked)
                        if (bTrace && tc.isDebugEnabled()) {
                            int curpos = buff.position();
                            buff.position(startpos);
                            byte[] data;
                            int offset = 0;
                            if (null != getParsedToken()) {
                                offset = getParsedToken().length;
                                data = new byte[(curpos - startpos) + offset];
                                System.arraycopy(getParsedToken(), 0, data, 0, offset);
                            } else {
                                data = new byte[(curpos - startpos)];
                            }
                            buff.get(data, offset, data.length - offset);
                            Tr.debug(tc, "Initial parse of message failed, (128) of buffer: \n"
                                         + GenericUtils.getHexDump(data, 128));
                        }
                        throw mme;
                    }
                } else if (TokenCodes.TOKEN_RC_MOREDATA.equals(tcRC)) {
                    // ran out of data
                    resetByteCache();
                    break; // out of while
                } else if (TokenCodes.TOKEN_RC_CRLF.equals(tcRC)) {
                    throw new MalformedMessageException("Too many leading CRLFs");
                }
            } else if (1 == this.numFirstLineTokensRead) {
                // second token
                tcRC = parseTokenExtract(buff, SPACE, true, LOG_PARTIAL);
                if (!tcRC.equals(TokenCodes.TOKEN_RC_MOREDATA)) {
                    setParsedSecondToken(getParsedToken());
                    if (tcRC.equals(TokenCodes.TOKEN_RC_CRLF)) {
                        if (bTrace && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Received CRLF after second token");
                        }
                        rc = true;
                    }
                }
            } else if (2 == this.numFirstLineTokensRead) {
                // third token
                tcRC = parseCRLFTokenExtract(buff, LOG_FULL);
                if (!tcRC.equals(TokenCodes.TOKEN_RC_MOREDATA)) {
                    setParsedThirdToken(getParsedToken());
                    rc = true;
                }
            } else {
                // stop coming here
                rc = true;
            }

            // scenarios where we need more data result in the MOREDATA RC above
            if (tcRC.equals(TokenCodes.TOKEN_RC_MOREDATA)) {
                resetByteCache();
                break; // out of while
            }

            // otherwise we finished parsing a single token
            setParsedToken(null);
            this.numFirstLineTokensRead++;
        } // end of while loop

        if (rc) {
            parsingComplete();
            setFirstLineComplete(true);
            // PK15898
            // go back one from the delimiter, unless it was an LF (if first
            // line ends with just an LF and not CRLF then we don't want to
            // change position as the header parsing above would consider it the
            // end of headers)
            decrementBytePositionIgnoringLFs();
        }

        if (bTrace && tc.isDebugEnabled()) {
            Tr.debug(tc, "parseLine returning " + rc + " for " + this);
        }
        return rc;
    }

def push(self, code, msg=None):
        """"""
        if msg is None:
            msg = str(code)
        else:
            msg = '%s %s' % (code, msg)

        if not msg.endswith(self.LINE_TERMINATOR):
            msg += self.LINE_TERMINATOR
        self._channel.write(msg)

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


Question:
// PoolMemberStatus changes the status of a pool member. <state> can be either
// "enable" or "disable". <member> must be in the form of <node>:<port>,
// i.e.: "web-server1:443".

func (b *BigIP) PoolMemberStatus(pool string, member string, state string, owner ...string) error {
	config := &Node{}

	switch state {
	case "enable":
		// config.State = "unchecked"
		config.Session = "user-enabled"
	case "disable":
		// config.State = "unchecked"
		config.Session = "user-disabled"
		// case "offline":
		// 	config.State = "user-down"
		// 	config.Session = "user-disabled"
	}

	if owner[0] != "" {
		config.AppService = owner[0]
	}

	return b.put(config, uriLtm, uriPool, pool, uriPoolMember, member)
}

func (ks *KeyStore) addSymmetricKeyToPool(keyid string, topic Topic, address PssAddress, addtocache bool, protected bool) {
	psp := &pssPeer{
		address:   address,
		protected: protected,
	}
	ks.mx.Lock()
	if _, ok := ks.symKeyPool[keyid]; !ok {
		ks.symKeyPool[keyid] = make(map[Topic]*pssPeer)
	}
	ks.symKeyPool[keyid][topic] = psp
	ks.mx.Unlock()
	if addtocache {
		ks.symKeyDecryptCacheCursor++
		ks.symKeyDecryptCache[ks.symKeyDecryptCacheCursor%cap(ks.symKeyDecryptCache)] = &keyid
	}
}

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


Question:
Generates a random :class:`~nacl.signing.SigningKey` object.

        :rtype: :class:`~nacl.signing.SigningKey`

def generate(cls):

        return cls(
            random(nacl.bindings.crypto_sign_SEEDBYTES),
            encoder=encoding.RawEncoder,
        )

public static function determineType($name, $definition)
    {
        // check if we can find a more appropriate Type subclass
        if (\is_string($definition)) {
            $definition = ['type' => $definition];
        } elseif (\is_array($definition)) {
            if (!\array_key_exists('type', $definition)) {
                $definition['type'] = isset($definition['properties']) ? 'object' : 'string';
            }
        } else {
            throw new \InvalidArgumentException('Invalid datatype for $definition parameter.');
        }

        $type = $definition['type'] ?: 'null';

        if (!\in_array($type, ['', 'any'], true)) {
            if (\in_array($type, static::getStraightForwardTypes(), true)) {
                $className = \sprintf(
                    'Raml\Types\%sType',
                    StringTransformer::convertString($type, StringTransformer::UPPER_CAMEL_CASE)
                );
                \assert(\class_exists($className));

                return \forward_static_call_array([$className, 'createFromArray'], [$name, $definition]);
            }
            // if $type contains a '|' we can safely assume it's a combination of types (union)
            if (\strpos($type, '|') !== false) {
                return UnionType::createFromArray($name, $definition);
            }
            // if $type contains a '[]' it means we have an array with a item restriction
            if (\strpos($type, '[]') !== false) {
                return ArrayType::createFromArray($name, $definition);
            }
            // no standard type found so this must be a reference to a custom defined type
            // since the actual definition can be defined later then when it is referenced
            // we create a proxy object for lazy loading when it is needed
            return LazyProxyType::createFromArray($name, $definition);
        }

        // No subclass found, let's use base class
        return Type::createFromArray($name, $definition);
    }

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


Question: // FieldsStr is a string representation of all the fields

func (e *enum) FieldsStr() string {
	var names []string
	for _, f := range e.Fields {
		names = append(names, f.Name)
	}
	return strings.Join(names, ", ")
}

private void write(LineString geom, JsonGenerator gen) throws IOException {
        gen.writeStringField("type", "LineString");
        gen.writeFieldName("coordinates");
        writeCoordinates(geom.getCoordinates(), gen);
    }

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


Question:
Writes current changes to disk and flushes modified objects in the
        AAFObjectManager

def save(self):

        if self.mode in ("wb+", 'rb+'):
            if not self.is_open:
                raise IOError("file closed")
            self.write_reference_properties()
            self.manager.write_objects()

public function setLastModifiedTime(PhingFile $f, $time)
    {
        $path = $f->getPath();
        $success = @touch($path, $time);
        if (!$success) {
            throw new IOException("Could not touch '" . $path . "' due to: $php_errormsg");
        }
    }

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


Question:
Renames a table.

@param string $oldName The old table name.
@param string $newName The new table name.

@throws \Fridge\DBAL\Exception\SchemaException If the old table does not exist or if the new table already
exists.

public function renameTable($oldName, $newName)
    {
        if (!$this->hasTable($oldName)) {
            throw SchemaException::schemaTableDoesNotExist($this->getName(), $oldName);
        }

        if ($this->hasTable($newName)) {
            throw SchemaException::schemaTableAlreadyExists($this->getName(), $newName);
        }

        $this->tables[$oldName]->setName($newName);
        $this->tables[$newName] = $this->tables[$oldName];

        unset($this->tables[$oldName]);
    }

def _upgrade_schema(engine):

    inspector = reflection.Inspector.from_engine(engine)
    with engine.connect() as conn:

        # Upgrade 1.  Add task_id column and index to tasks
        if 'task_id' not in [x['name'] for x in inspector.get_columns('tasks')]:
            logger.warning('Upgrading DbTaskHistory schema: Adding tasks.task_id')
            conn.execute('ALTER TABLE tasks ADD COLUMN task_id VARCHAR(200)')
            conn.execute('CREATE INDEX ix_task_id ON tasks (task_id)')

        # Upgrade 2. Alter value column to be TEXT, note that this is idempotent so no if-guard
        if 'mysql' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters MODIFY COLUMN value TEXT')
        elif 'oracle' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters MODIFY value TEXT')
        elif 'mssql' in engine.dialect.name:
            conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TEXT')
        elif 'postgresql' in engine.dialect.name:
            if str([x for x in inspector.get_columns('task_parameters')
                    if x['name'] == 'value'][0]['type']) != 'TEXT':
                conn.execute('ALTER TABLE task_parameters ALTER COLUMN value TYPE TEXT')
        elif 'sqlite' in engine.dialect.name:
            # SQLite does not support changing column types. A database file will need
            # to be used to pickup this migration change.
            for i in conn.execute('PRAGMA table_info(task_parameters);').fetchall():
                if i['name'] == 'value' and i['type'] != 'TEXT':
                    logger.warning(
                        'SQLite can not change column types. Please use a new database '
                        'to pickup column type changes.'
                    )
        else:
            logger.warning(
                'SQLAlcheny dialect {} could not be migrated to the TEXT type'.format(
                    engine.dialect
                )
            )

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


Question:
Return the list of EXTVER values for extensions with name specified
        in extname.

def getExtensions(self, extname='SCI', section=None):

        if section is None:
            numext = 0
            section = []
            for hdu in self._image:
                if 'extname' in hdu.header and hdu.header['extname'] == extname:
                    section.append(hdu.header['extver'])
        else:
            if not isinstance(section,list):
                section = [section]

        return section

function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}

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


Question:
Discovers the end line of the node when there are no lines.

 @return [Integer] the end line of the node

def nontrivial_end_line
      if (last_child = children.last)
        last_child.line_numbers.end - 1
      elsif successor
        successor.line_numbers.begin - 1
      else
        @document.source_lines.count
      end
    end

private GeometryIndex parseRecursive(String id) throws GeometryIndexNotFoundException {
		int position = id.indexOf("geometry");
		if (position >= 0) {
			String temp = id.substring(position + 8);
			int value = readInteger(temp);
			if (value < 0) {
				throw new GeometryIndexNotFoundException("Could not read value from " + temp);
			}
			GeometryIndex childIndex = parseRecursive(temp);
			return new GeometryIndex(GeometryIndexType.TYPE_GEOMETRY, value, childIndex);
		} else {
			GeometryIndex index = parseSingle(id, "vertex", GeometryIndexType.TYPE_VERTEX);
			if (index == null) {
				index = parseSingle(id, "edge", GeometryIndexType.TYPE_EDGE);
			}
			return index;
		}
	}

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


Question:
Updates session info from the API.

@private @method updateSession

function updateSession(callback) {
  core.api({method: ''}, function(err, response) {
    var session;
    if (err) {
      core.log('error encountered updating session:', err);
      callback && callback(err, null);
      return;
    }

    if (!response.token.valid) {
      // Invalid token. Either it has expired or the user has
      // revoked permission, so clear out our stored data.
      logout(callback);
      return;
    }

    callback && callback(null, session);
  });
}

def getUpdated(self, sObjectType, startDate, endDate):
    '''

    '''
    self._setHeaders('getUpdated')
    return self._sforce.service.getUpdated(sObjectType, startDate, endDate)

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


Question:
Dump the logged data to a file.
        The argument `file` can be either a filename or an open file object
        that requires write access. `close` controls if the file is closed
        before leaving this method (the default behaviour).

def dump_stats(self, fdump, close=True):

        if self.tracker:
            self.tracker.stop_periodic_snapshots()

        if isinstance(fdump, type('')):
            fdump = open(fdump, 'wb')
        pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        pickle.dump(self.snapshots, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        if close:
            fdump.close()

int run(String[] args) {
        try {
            handleOptions(args);

            // the following gives consistent behavior with javac
            if (classes == null || classes.size() == 0) {
                if (options.help || options.version || options.fullVersion)
                    return EXIT_OK;
                else
                    return EXIT_CMDERR;
            }

            try {
                return run();
            } finally {
                if (defaultFileManager != null) {
                    try {
                        defaultFileManager.close();
                        defaultFileManager = null;
                    } catch (IOException e) {
                        throw new InternalError(e);
                    }
                }
            }
        } catch (BadArgs e) {
            reportError(e.key, e.args);
            if (e.showUsage) {
                printLines(getMessage("main.usage.summary", progname));
            }
            return EXIT_CMDERR;
        } catch (InternalError e) {
            Object[] e_args;
            if (e.getCause() == null)
                e_args = e.args;
            else {
                e_args = new Object[e.args.length + 1];
                e_args[0] = e.getCause();
                System.arraycopy(e.args, 0, e_args, 1, e.args.length);
            }
            reportError("err.internal.error", e_args);
            return EXIT_ABNORMAL;
        } finally {
            log.flush();
        }
    }

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


Question:
Create an Alias of a function check if it's exist
@param $aliasName
@param $callback
@return array

public static function alias($aliasName, $callback)
    {
        $err = false;

        if (function_exists($aliasName)) {
            $err = 'This function already' . $aliasName . ' exists';
        }

        if (!is_callable($callback, false, $realfunc)) {
            $err = $callback.' is not callable';
        }

        if($err === false){
            try {
                $bodyFunc = 'function ' . $aliasName . '() {
                    $args = func_get_args();
                    return call_user_func_array("' . $realfunc . '", $args);
                }';

                eval($bodyFunc);

                return array('result' => true, 'msg' => "function $aliasName created from $callback");

            } catch (\Exception $e) {

                $trace = debug_backtrace();

                $msg = sprintf(
                    '%s(): %s in %s on line %d',
                    $trace[0]['function'],
                    $err,
                    $trace[0]['file'],
                    $trace[0]['line']
                );

                trigger_error($msg,
                    E_USER_WARNING
                );

                return array('result' => false, 'msg' => $err);
            }

        } else {
            return array('result' => false, 'msg' => $err);
        }
    }

public function generate()
    {
        if (count($this->functions) === 0) {
            throw new \Exception('function list empty');
        }

        $parts = [];
        foreach ($this->functions as $function) {
            $args = [];
            if ($function['args']) {
                $args = $this->generateArgs($function['args']);
            }
            $parts[] = $function['name'].'('.implode(', ', $args).')';
        }

        $class = $this->class['name'];
        $class .= count($this->class['args']) ? '('.implode(', ', $this->class['args']).')' : '';

        $result = $class.($this->isStatic() ? '::' : '->').implode($parts, '->');

        return $result;
    }

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


Question:
Used to add a column head to the Post Type's List Table.

@param  array $columns
@return array

public function addColumn($columns)
    {
        unset($columns['date']);

        foreach ($this->data as $id => $field) {
            if (isset($field->show_admin_column) && $field->show_admin_column) {
                $columns[$id] = $field->label;
            }
        }

        $columns['date'] = __('Date');

        return $columns;
    }

public function setMaptype($v)
    {
        if ($v !== null) {
            $v = (string) $v;
        }

        if ($this->maptype !== $v) {
            $this->maptype = $v;
            $this->modifiedColumns[MapTableMap::COL_MAPTYPE] = true;
        }

        return $this;
    }

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


Question:
Find route by given tag

@param string $tag
@return Route|null

public function findRouteByTag($tag)
    {
        $route = $this->each(function(Route $route) use($tag)
        {
            if($route->hasProperty('tag') && $route->getProperty('tag') == $tag)
                return $route;
        }, true);

        return $route ? : null;
    }

def resources_by_type(ast)
      raise_unless_xpath!(ast)
      result = Hash.new { |hash, key| hash[key] = Array.new }
      find_resources(ast).each do |resource|
        result[resource_type(resource)] << resource
      end
      result
    end

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


Question:
// LoadDescriptor loads file descriptor protos from a file on disk, and returns the named proto descriptor. This is
// useful mostly for testing purposes.

func LoadDescriptor(name string, pathSegments ...string) (*descriptor.FileDescriptorProto, error) {
	set, err := LoadDescriptorSet(pathSegments...)
	if err != nil {
		return nil, err
	}

	if pf := FindDescriptor(set, name); pf != nil {
		return pf, nil
	}

	return nil, errors.New("FileDescriptor not found")
}

def process_msg3(fname):
    """"""
    with open(fname, 'r') as infile:
        info = []
        for lineno, line in enumerate(infile):
            parts = line.split('  ')
            try:
                var_name, desc, typ, units = parts[:4]
                size_hw = parts[-1]
                if '-' in size_hw:
                    start, end = map(int, size_hw.split('-'))
                    size = (end - start + 1) * 2
                else:
                    size = 2

                assert size >= 2
                fmt = fix_type(typ, size)

                var_name = fix_var_name(var_name)
                full_desc = fix_desc(desc, units)

                info.append({'name': var_name, 'desc': full_desc, 'fmt': fmt})

                if ignored_item(info[-1]) and var_name != 'Spare':
                    warnings.warn('{} has type {}. Setting as Spare'.format(var_name, typ))

            except (ValueError, AssertionError):
                warnings.warn('{} > {}'.format(lineno + 1, ':'.join(parts)))
                raise
        return info

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


Question:
Creates a new commerce shipment item with the primary key. Does not add the commerce shipment item to the database.

@param commerceShipmentItemId the primary key for the new commerce shipment item
@return the new commerce shipment item

@Override
	public com.liferay.commerce.model.CommerceShipmentItem createCommerceShipmentItem(
		long commerceShipmentItemId) {
		return _commerceShipmentItemLocalService.createCommerceShipmentItem(commerceShipmentItemId);
	}

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

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


Question:
This naive implementation of ordering will ignore
frequency requirements.
@param  string       $methodName
@return \Shmock\Spec

public function nextSpec($methodName)
    {
        if ($this->pointer >= count($this->chain)) {
            throw new \PHPUnit_Framework_AssertionFailedError("There are no more method calls expected given assigned ordering");
        }
        if ($this->pointer + 1 < count($this->chain)) {
            $next = $this->chain[$this->pointer + 1];
            if ($next[0] === $methodName) {
                // if the next method has the same name as the passed
                // $methodName, then advance the pointer and return the
                // given spec.
                $this->pointer++;

                return $next[1];
            }
        }

        if ($this->pointer === -1) {
            throw new \PHPUnit_Framework_AssertionFailedError(sprintf("Unexpected method invocation %s at call index %s, haven't seen any method calls yet", $methodName, $this->pointer, true));
        }
        $current = $this->chain[$this->pointer];
        if ($current[0] !== $methodName) {
            // if the current spec does not match the method name,
            // we do not have any other possible specs to return
            // so we throw an assertion failure with a print of every
            // method we've run so far:
            $methodsSoFar = [];
            for ($i = 0; $i <= $this->pointer; $i++) {
                $methodsSoFar[] = $this->chain[$i][0];
            }

            throw new \PHPUnit_Framework_AssertionFailedError(sprintf("Unexpected method invocation %s at call index %s, seen method calls so far: %s", $methodName, $this->pointer, print_r(implode($methodsSoFar, "\n"), true)));
        }

        return $current[1];
    }

func (api *SSHKeyAPI) SortByName(reverse bool) *SSHKeyAPI {
	api.sortByName(reverse)
	return api
}

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


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

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.IOCA_FUNCTION_SET_IDENTIFICATION__CATEGORY:
				return CATEGORY_EDEFAULT == null ? category != null : !CATEGORY_EDEFAULT.equals(category);
			case AfplibPackage.IOCA_FUNCTION_SET_IDENTIFICATION__FCNSET:
				return FCNSET_EDEFAULT == null ? fcnset != null : !FCNSET_EDEFAULT.equals(fcnset);
		}
		return super.eIsSet(featureID);
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question: // SetBillingMethod sets the BillingMethod field's value.

func (s *CreateRemoteAccessSessionConfiguration) SetBillingMethod(v string) *CreateRemoteAccessSessionConfiguration {
	s.BillingMethod = &v
	return s
}

private void save(String oldName) {
        Common.getInstance().getStorageHandler().getStorageEngine().saveCurrency(oldName, this);
        Common.getInstance().getCurrencyManager().updateEntry(oldName, this);
    }

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


Question: Reads all lines of a file with the platform encoding.

private static List<String> readAllLines(File f) throws IOException {
        BufferedReader r = new BufferedReader(new FileReader(f));
        try {
            List<String> result = new ArrayList<String>();
            String line;
            while ((line = r.readLine()) != null) {
                result.add(line);
            }
            return result;
        }  finally {
            r.close();
        }
    }

func newReadBuffer(path string, num int32, c *Client) *Buffer {
	buffers.RLock()
	// return the existing buffer if there is one
	if existing, exists := buffers.m[path]; exists {
		buffers.RUnlock()
		return existing
	}
	buffers.RUnlock()

	// make a new one
	b := &Buffer{Num: num, client: c}

	// add it to the global map
	buffers.Lock()
	buffers.m[path] = b
	buffers.Unlock()

	return b
}

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


Question: Return sensor attribute with precission, or None if not present.

def _get_value_opc_attr(self, attr_name, prec_decimals=2):
        """"""
        try:
            value = getattr(self, attr_name)
            if value is not None:
                return round(value, prec_decimals)
        except I2cVariableNotImplemented:
            pass
        return None

public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) {
		left.accept(isLeft() ? getLeft() : defaultLeft);
		right.accept(isRight() ? getRight() : defaultRight);
	}

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


Question: Read and cache filter.

private FilterUtils getFilterUtils(final Element ditavalRef) {
        if (ditavalRef.getAttribute(ATTRIBUTE_NAME_HREF).isEmpty()) {
            return null;
        }
        final URI href = toURI(ditavalRef.getAttribute(ATTRIBUTE_NAME_HREF));
        final URI tmp = currentFile.resolve(href);
        final FileInfo fi = job.getFileInfo(tmp);
        final URI ditaval = fi.src;
        FilterUtils f = filterCache.get(ditaval);
        if (f == null) {
            ditaValReader.filterReset();
            logger.info("Reading " + ditaval);
            ditaValReader.read(ditaval);
            Map<FilterUtils.FilterKey, FilterUtils.Action> filterMap = ditaValReader.getFilterMap();
            f = new FilterUtils(filterMap, ditaValReader.getForegroundConflictColor(), ditaValReader.getBackgroundConflictColor());
            f.setLogger(logger);
            filterCache.put(ditaval, f);
        }
        return f;
    }

func (s *MetricsFilter) SetAnd(v *MetricsAndOperator) *MetricsFilter {
	s.And = v
	return s
}

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


Question:
Installs a money getter
 @!macro [attach] install_money_getter
   @method $1

def install_money_getter attribute, options={}

      define_method :"#{attribute}_with_exchange_typecasting" do
        currency = evaluate_money_option(options[:currency]) if options[:currency]

        test_for_currency_error(currency, attribute)

        time     = evaluate_money_option(options[:at]) if options[:at]

        if value = send(:"#{attribute}_without_exchange_typecasting")
          Exchange::Money.new(value) do |c|
            c.currency = currency
            c.time     = time if time
          end
        end
      end
      exchange_typecasting_alias_method_chain attribute

    end

func NewCmdLinkSecret(name, fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewLinkSecretOptions(streams)

	cmd := &cobra.Command{
		Use:     fmt.Sprintf("%s serviceaccounts-name secret-name [another-secret-name]...", name),
		Short:   "Link secrets to a ServiceAccount",
		Long:    linkSecretLong,
		Example: fmt.Sprintf(linkSecretExample, fullName),
		PreRun: func(cmd *cobra.Command, args []string) {
			if len(os.Args) > 1 && os.Args[1] == "add" {
				printDeprecationWarning("secrets add", "secrets link")
			}
		},
		Run: func(c *cobra.Command, args []string) {
			if err := o.Complete(f, args); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageErrorf(c, err.Error()))
			}

			if err := o.Validate(); err != nil {
				kcmdutil.CheckErr(kcmdutil.UsageErrorf(c, err.Error()))
			}

			if err := o.LinkSecrets(); err != nil {
				kcmdutil.CheckErr(err)
			}

		},
	}

	cmd.Flags().StringSliceVar(&o.typeFlags, "for", []string{"mount"}, "type of secret to link: mount or pull")

	return cmd
}

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


Question: GET /notifications/1

def show
      notification = Notification.find_by(id: params[:id])
      activity     = notification.activity

      notification.mark_as_read if notification.unread?

      redirect_to activity_activities_path(activity_id: activity.id)
    end

public function url($url, $target = '')
    {
        $this->urlTarget = $target;
        $this->url = $url;

        return $this->setNotifier();
    }

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


Question: Retrieve the region for a particular AWS service based on configured region and/or profile.

def get_region(service, region, profile):

    _, region, _, _ = _get_profile(service, region, None, None, profile)

    return region

func NewDNSAPI(client *Client) *DNSAPI {
	return &DNSAPI{
		&baseAPI{
			client: client,
			FuncGetResourceURL: func() string {
				return "commonserviceitem"
			},
			FuncBaseSearchCondition: func() *sacloud.Request {
				res := &sacloud.Request{}
				res.AddFilter("Provider.Class", "dns")
				return res
			},
		},
	}
}

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


Question: // Delete takes name of the secret and deletes it. Returns an error if one occurs.

func (c *FakeSecrets) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteAction(secretsResource, c.ns, name), &corev1.Secret{})

	return err
}

def delFutureById(futureId, parentId):
    """"""
    try:
        del futureDict[futureId]
    except KeyError:
        pass
    try:
        toDel = [a for a in futureDict[parentId].children if a.id == futureId]
        for f in toDel:
            del futureDict[parentId].children[f]
    except KeyError:
        pass

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


Question:
Add a user to the minion

    CLI Example:

    .. code-block:: bash

        salt '*' user.add name <uid> <gid> <groups> <home> <shell>

def add(name,
        uid=None,
        gid=None,
        groups=None,
        home=None,
        shell=None,
        unique=True,
        fullname='',
        roomnumber='',
        workphone='',
        homephone='',
        createhome=True,
        loginclass=None,
        **kwargs):
    '''

    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    if salt.utils.data.is_true(kwargs.pop('system', False)):
        log.warning('pw_user module does not support the \'system\' argument')
    if kwargs:
        log.warning('Invalid kwargs passed to user.add')

    if isinstance(groups, six.string_types):
        groups = groups.split(',')
    cmd = ['pw', 'useradd']
    if uid:
        cmd.extend(['-u', uid])
    if gid:
        cmd.extend(['-g', gid])
    if groups:
        cmd.extend(['-G', ','.join(groups)])
    if home is not None:
        cmd.extend(['-d', home])
    if createhome is True:
        cmd.append('-m')
    if loginclass:
        cmd.extend(['-L', loginclass])
    if shell:
        cmd.extend(['-s', shell])
    if not salt.utils.data.is_true(unique):
        cmd.append('-o')
    gecos_field = _build_gecos({'fullname': fullname,
                                'roomnumber': roomnumber,
                                'workphone': workphone,
                                'homephone': homephone})
    cmd.extend(['-c', gecos_field])
    cmd.extend(['-n', name])
    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0

public function createUserAsync($writerId, $email, $password, $firstName, $lastName, $queue = 'primary')
    {
        return $this->getCommand('CreateUser', [
            'writerId' => $writerId,
            'email' => $email,
            'password' => $password,
            'firstName' => $firstName,
            'lastName' => $lastName,
            'queue' => $queue
        ])->execute();
    }

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


Question:
Add a subfield to the end of the subfield list.

@throws InvalidArgumentException Subfield already present in subfield list
@param  \HAB\Pica\Record\Subfield $subfield Subfield to add
@return void

public function addSubfield (\HAB\Pica\Record\Subfield $subfield)
    {
        if (in_array($subfield, $this->getSubfields(), true)) {
            throw new InvalidArgumentException("Cannot add subfield: Subfield already part of the subfield list");
        }
        $this->_subfields []= $subfield;
    }

def create_subgroup_global(self, id, title, description=None, vendor_guid=None):

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

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

        # REQUIRED - title
        """The title of the new outcome group."""
        data["title"] = title

        # OPTIONAL - description
        """The description of the new outcome group."""
        if description is not None:
            data["description"] = description

        # OPTIONAL - vendor_guid
        """A custom GUID for the learning standard"""
        if vendor_guid is not None:
            data["vendor_guid"] = vendor_guid

        self.logger.debug("POST /api/v1/global/outcome_groups/{id}/subgroups with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/global/outcome_groups/{id}/subgroups".format(**path), data=data, params=params, single_item=True)

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


Question: // Set implements metrics.Gauge.

func (g *Gauge) Set(value float64) {
	g.obs(g.name, g.lvs, value)
}

public void ifge(String target) throws IOException
    {
        if (wideIndex)
        {
            out.writeByte(NOT_IFGE);
            out.writeShort(WIDEFIXOFFSET);
            Branch branch = createBranch(target);
            out.writeByte(GOTO_W);
            out.writeInt(branch);
        }
        else
        {
            Branch branch = createBranch(target);
            out.writeOpCode(IFGE);
            out.writeShort(branch);
        }
    }

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


Question: // save saves the main prefix queue data.

func (pq *PrefixQueue) save() error {
	val := make([]byte, 8)
	binary.BigEndian.PutUint64(val, pq.size)
	return pq.db.Put(pq.getDataKey(), val, nil)
}

def category(self):

        if self.id in ('reg', 'mem'):
            return self.id

        elif self._abstract_backer:
            return 'mem'

        elif self.id.startswith('file'):
            return 'file'

        else:
            raise SimMemoryError('Unknown SimMemory category for memory_id "%s"' % self.id)

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


Question:
class_variable_declaration : class_variable_declaration COMMA VARIABLE EQUALS static_scalar
                                  | VARIABLE EQUALS static_scalar

def p_class_variable_declaration_initial(p):
    ''''''
    if len(p) == 6:
        p[0] = p[1] + [ast.ClassVariable(p[3], p[5], lineno=p.lineno(2))]
    else:
        p[0] = [ast.ClassVariable(p[1], p[3], lineno=p.lineno(1))]

def load_missing_constant(from_mod, const_name)
      log_call from_mod, const_name
      if from_mod == Kernel
        if ::Object.const_defined?(const_name)
          log "Returning Object::#{const_name} for Kernel::#{const_name}"
          return ::Object.const_get(const_name)
        else
          log "Substituting Object for Kernel"
          from_mod = Object
        end
      end

      # If we have an anonymous module, all we can do is attempt to load from Object.
      from_mod = Object if from_mod.name.blank?

      unless qualified_const_defined?(from_mod.name) && from_mod.name.constantize.object_id == from_mod.object_id
        raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!"
      end

      raise ArgumentError, "#{from_mod} is not missing constant #{const_name}!" if uninherited_const_defined?(from_mod, const_name)

      qualified_name = qualified_name_for from_mod, const_name
      path_suffix = qualified_name.underscore
      name_error = NameError.new("uninitialized constant #{qualified_name}")

      file_path = search_for_file(path_suffix)
      if file_path && ! loaded.include?(File.expand_path(file_path)) # We found a matching file to load
        require_or_load file_path
        raise LoadError, "Expected #{file_path} to define #{qualified_name}" unless uninherited_const_defined?(from_mod, const_name)
        return from_mod.const_get(const_name)
      elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
        return mod
      elsif (parent = from_mod.parent) && parent != from_mod &&
            ! from_mod.parents.any? { |p| uninherited_const_defined?(p, const_name) }
        # If our parents do not have a constant named +const_name+ then we are free
        # to attempt to load upwards. If they do have such a constant, then this
        # const_missing must be due to from_mod::const_name, which should not
        # return constants from from_mod's parents.
        begin
          return parent.const_missing(const_name)
        rescue NameError => e
          raise unless e.missing_name? qualified_name_for(parent, const_name)
          raise name_error
        end
      else
        raise name_error
      end
    end

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


Question:
Only sets content-type header if we know how to serialize it later
@param string $typeAlias
@return bool
@todo should we allow more freedom to caller, and only map very obviously wrong things like "php", json" etc

function setContentType( $typeAlias )
    {
        // expand short-hand notation for "php", json" etc
        if ( isset( self::$KnownContentTypes[$typeAlias] ) )
        {
            $this->ContentType = self::$KnownContentTypes[$typeAlias];
            return true;
        }
        // accept as well other mimetypes, as long as we later know how to encode them
        $decodableType = $this->mimeTypeToEncodeType( $typeAlias );
        if ( isset( self::$KnownContentTypes[$decodableType] ) )
        {
            $this->ContentType = $typeAlias;
            return true;
        }
        return false;
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question:
Check to see if a user has the access.

@param string|array       $accessKey One or array of permission keys
@param \Subbly\Model\User $user      The User scope (if null, current user is used)

@return bool

@api

public function hasAccess($accessKey, User $user = null)
    {
        if ($user === null) {
            $user = $this->currentUser();
        }

        if (is_array($accessKey)) {
            return $user->hasAnyAccess($accessKey);
        } else {
            return $user->hasAccess($accessKey);
        }
    }

function shallow(module) {
		return {
			name: module.name,
			version: module.version,
			installed: module.installed,
			scope: module.scope,
			state: module.current ? 'current' : (module.upgrade ? 'upgrade' : 'install')
		};
	}

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


Question: Shift the second dimension of x right by one.

def shift_right_3d(x, pad_value=None):
  """"""
  if pad_value is None:
    shifted_targets = tf.pad(x, [[0, 0], [1, 0], [0, 0]])[:, :-1, :]
  else:
    shifted_targets = tf.concat([pad_value, x], axis=1)[:, :-1, :]
  return shifted_targets

public function unshift($item)
    {
        $this->onBeforeInsert($item);
        $item->setContainerFieldList($this);

        return parent::unshift($item);
    }

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


Question: Supports only singular delete and adds proper http status.

def delete(self, params, args, data):
        """"""
        ctx = self._create_context(params, args, data)
        row_id = ctx.get_row_id()

        if row_id:
            deleted = self._delete_one(row_id, ctx)

            if deleted:
                return ResourceResult(body={})
            else:
                return NOT_FOUND
        else:
            return NOT_FOUND

func NewRevokeLinkedAppStatus(Success bool) *RevokeLinkedAppStatus {
	s := new(RevokeLinkedAppStatus)
	s.Success = Success
	return s
}

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


Question: // BodyParameter parses the body of the request (once for typically a POST or a PUT) and returns the value of the given name or an error.

func (r *Request) BodyParameter(name string) (string, error) {
	err := r.Request.ParseForm()
	if err != nil {
		return "", err
	}
	return r.Request.PostFormValue(name), nil
}

func (s *Server) handlePOST(c *router.Context) {
	serviceName := c.Params.ByName("service")
	methodName := c.Params.ByName("method")
	s.setAccessControlHeaders(c, false)
	res := s.call(c, serviceName, methodName)
	if res.err != nil {
		writeError(c.Context, c.Writer, res.err)
		return
	}
	writeMessage(c.Context, c.Writer, res.out, res.fmt)
}

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


Question:
Delete media.

@param Request $request
@param int     $id

@return Response media

public function deleteMediaAction(Request $request, $id)
    {
        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['value'];

        $mm = $this->getMediaManager();

        $media = $mm->findOneBy(array(
            'id' => $id,
            'filter' => $filter,
        ));

        if ($media !== null) {
            $media->setCryptedFilter($response['crypted']);
            $mm->delete($media);
        }

        return $this->createResponse($media);
    }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
Gets the total of the invoice with a defined decimal precision
        @param precision: int Number of decimal places
        @return: Decimal

def compute_total(self, precision=None):
        '''

        '''
        return quantize(sum([group.compute_total(precision) for group
                             in self.__groups]), places=precision) or ZERO

def parse_data_to_internal(self, data=None):

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

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


Question:
@param string $entityType

@return void
@throws EntityFactoryException

public function setEntityType(string $entityType): void {
		if (!class_exists($entityType)) {
			throw new EntityFactoryException("Unknown entity: $entityType.", EntityFactoryException::UNKNOWN_ENTITY);
		}

		// now that we know a class with the name of entityType exists, we need
		// to see if it is an implementation of our EntityInterface object.  the
		// use of the Aura DI container to inject dependencies seems to prevent
		// the use of the PHP is_a() and is_subclass_of() functions.  instead,
		// we'll try to instantiate it like it's an EntityInterface and then we
		// can use the instanceof operator to be sure.

		$this->entityType = $entityType;
		$temp = $this->newEntity([]);

		if (!($temp instanceof EntityInterface)) {

			// if that didn't work, then not only do we want to throw an
			// exception, but we also want to be sure that we set the
			// entityType property back to null so that it doesn't accidentally
			// get used elsewhere after the exception is caught.

			$this->entityType = null;
			throw new EntityFactoryException("Not an entity: $entityType.", EntityFactoryException::NOT_AN_ENTITY);
		}
	}

private function Flow_searchForEntitiesAndStoreIdentifierArray($path, $propertyValue, $originalPropertyName)
    {
        if (is_array($propertyValue) || (is_object($propertyValue) && ($propertyValue instanceof \ArrayObject || $propertyValue instanceof \SplObjectStorage))) {
            foreach ($propertyValue as $key => $value) {
                $this->Flow_searchForEntitiesAndStoreIdentifierArray($path . '.' . $key, $value, $originalPropertyName);
            }
        } elseif ($propertyValue instanceof PersistenceMagicInterface && !Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->isNewObject($propertyValue) || $propertyValue instanceof OrmProxy) {
            if (!property_exists($this, 'Flow_Persistence_RelatedEntities') || !is_array($this->Flow_Persistence_RelatedEntities)) {
                $this->Flow_Persistence_RelatedEntities = [];
                $this->Flow_Object_PropertiesToSerialize[] = 'Flow_Persistence_RelatedEntities';
            }
            if ($propertyValue instanceof OrmProxy) {
                $className = get_parent_class($propertyValue);
            } else {
                $className = Bootstrap::$staticObjectManager->getObjectNameByClassName(get_class($propertyValue));
            }
            $identifier = Bootstrap::$staticObjectManager->get(PersistenceManagerInterface::class)->getIdentifierByObject($propertyValue);
            if (!$identifier && $propertyValue instanceof OrmProxy) {
                $identifier = current(ObjectAccess::getProperty($propertyValue, '_identifier', true));
            }
            $this->Flow_Persistence_RelatedEntities[$originalPropertyName . '.' . $path] = [
                'propertyName' => $originalPropertyName,
                'entityType' => $className,
                'identifier' => $identifier,
                'entityPath' => $path
            ];
            $this->$originalPropertyName = Arrays::setValueByPath($this->$originalPropertyName, $path, null);
        }
    }

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


Question: // New clones this parameter

func (p *ListParam) New() Param {
	return &ListParam{p.paramCommon, p.el, nil}
}

func (section *Section) AddComment(comment string) {
	section.comments = append(section.comments, comment)
}

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


Question:
Removes expired registrations

@return void

public function removeExpired() {
		$count = $this->UserTable->removeExpiredRegistrations();
		$this->out(__dn(
			'burzum/user_tools',
			'Removed {0,number,integer} expired registration.',
			'Removed {0,number,integer} expired registrations.',
			$count,
			$count
		));
	}

public function markAsUsed($sOrderId, $sUserId, $dDiscount)
    {
        //saving oxreserved field
        if ($this->oxvouchers__oxid->value) {
            $this->oxvouchers__oxorderid->setValue($sOrderId);
            $this->oxvouchers__oxuserid->setValue($sUserId);
            $this->oxvouchers__oxdiscount->setValue($dDiscount);
            $this->oxvouchers__oxdateused->setValue(date("Y-m-d", \OxidEsales\Eshop\Core\Registry::getUtilsDate()->getTime()));
            $this->save();
        }
    }

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


Question: Obfuscates password from a database URL.

def safeDbUrl(db_url):
    """"""
    url = urlparse(db_url)
    return db_url.replace(url.password, "****") if url.password else db_url

public function createUrl(array $parameters = array())
    {
        $final_parameters = $this->getFinalParameters();
        $path = $this->getBaseURL();

        // Override default parameters
        $final_parameters = array_merge($final_parameters, $parameters);

        return $path . "?" . http_build_query($final_parameters, null, '&') . $this->buildFragment();
    }

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


Question:
Provides some necessary soap headers

@param string $function

@return array Each element is a concrete SoapHeader object

protected function buildSoapHeader($function)
  {
    $timeStamp = $this->getTimestamp();
    $signature = $this->buildSignature($function . $timeStamp);

    return array(
      new SoapHeader(
        'http://security.amazonaws.com/doc/2007-01-01/',
        'AWSAccessKeyId',
        $this->requestConfig['accessKey']
      ),
      new SoapHeader(
        'http://security.amazonaws.com/doc/2007-01-01/',
        'Timestamp',
        $timeStamp
      ),
      new SoapHeader(
        'http://security.amazonaws.com/doc/2007-01-01/',
        'Signature',
        $signature
      )
    );
  }

void createMethodBody(String classname, ExecutableElement methodElement, List<String> arguments, Writer writer) throws IOException {
		String methodName = getMethodName(methodElement);
		boolean ws = isWebsocketDataService(methodElement);
		String args = stringJoinAndDecorate(arguments, COMMA, new NothingDecorator());
		String keys = computeKeys(methodElement, arguments);
		createReturnOcelotPromiseFactory(classname, methodName, ws, args, keys, writer);
	}

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


Question: must be volatile since it is read/written in several threads

public void doRecovery(){
        try {
            boolean toRestart = Boolean.getBoolean("cloudslang.worker.restart.on.recovery");
            //If we are configured to restart on recovery - do shutdown
            if(toRestart){
                logger.warn("Worker is configured to restart on recovery and since internal recovery is needed the process is exiting...");
                System.exit(EXIT_STATUS);
            }

            synchronized (this){
                //If already in recovery - then return and do nothing
                if(inRecovery){
                    return;
                }
                inRecovery = true;

            }
            syncManager.startRecovery();

            logger.warn("Worker internal recovery started");

            for (WorkerRecoveryListener listener : listeners){
                try {
                    listener.doRecovery();
                } catch (Exception ex) {
                    logger.error("Failed on worker internal recovery", ex);
                }
            }
            if (logger.isDebugEnabled()) logger.debug("Listeners recovery is done");

            retryTemplate.retry(RetryTemplate.INFINITELY, 30*1000L, new RetryTemplate.RetryCallback() {
                @Override
                public void tryOnce() {
					if(logger.isDebugEnabled()) logger.debug("sending worker UP");
                    String newWrv = workerNodeService.up(System.getProperty("worker.uuid"), workerVersionService.getWorkerVersion(), workerVersionService.getWorkerVersionId());
                    setWRV(newWrv);
                    if(logger.isDebugEnabled()) logger.debug("the worker is UP");
                }
            });
            inRecovery = false;
            logger.warn("Worker recovery is done");
        } finally {
            syncManager.finishRecovery();
		}
	}

public boolean setValue(int ch, int value)
    {
        // valid, uncompacted trie and valid c?
        if (m_isCompacted_ || ch > UCharacter.MAX_VALUE || ch < 0) {
            return false;
        }

        int block = getDataBlock(ch);
        if (block < 0) {
            return false;
        }

        m_data_[block + (ch & MASK_)] = value;
        return true;
    }

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


Question:
Add soft-evidence to the Bayesian network to reason with it.

@param bn
@param nodeName
@param softEvidence
@throws ShanksException

public static void addSoftEvidence(ProbabilisticNetwork bn,
            String nodeName, HashMap<String, Double> softEvidence)
            throws ShanksException {
        ProbabilisticNode targetNode = ShanksAgentBayesianReasoningCapability
                .getNode(bn, nodeName);
        boolean found = false;
        for (Node child : targetNode.getChildren()) {
            if (child.getName().equals(softEvidenceNodePrefix + nodeName)) {
                if (child.getStatesSize() == 2
                        && child.getStateAt(0).equals(triggerState)) {
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            // Create soft-evidence node
            ProbabilisticNode auxNode = new ProbabilisticNode();
            auxNode.setName(softEvidenceNodePrefix + nodeName);
            auxNode.setLabel(softEvidenceNodePrefix + nodeName);
            auxNode.appendState(triggerState);
            auxNode.appendState("NON" + triggerState);
            PotentialTable cpt = auxNode.getProbabilityFunction();
            cpt.addVariable(auxNode);
            for (int i = 0; i < cpt.tableSize(); i++) {
                cpt.setValue(i, (float) 0.5);
            }
            auxNode.initMarginalList();
            bn.addNode(auxNode);

            Edge edge = new Edge(targetNode, auxNode);
            try {
                bn.addEdge(edge);
                cpt = auxNode.getProbabilityFunction();
                for (int i = 0; i < cpt.tableSize(); i++) {
                    cpt.setValue(i, (float) 0.5);
                }
                auxNode.initMarginalList();
            } catch (Exception e) {
                throw new ShanksException(e);
            }
        }
        ShanksAgentBayesianReasoningCapability
                .updateSoftEvidenceAuxiliaryNodeCPT(bn, nodeName, softEvidence);
        ShanksAgentBayesianReasoningCapability.addEvidence(bn,
                softEvidenceNodePrefix + nodeName, triggerState);

    }

private SoyValue visitNullSafeNode(ExprNode node) {
    SoyValue value = visitNullSafeNodeRecurse(node);
    // Transform null sentinel into a normal null value.
    if (value == NullSafetySentinel.INSTANCE) {
      return NullData.INSTANCE;
    }
    return value;
  }

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


Question: Sort the flags alphabetically

def add_arguments(self, actions):

        actions = sorted(
            actions, key=operator.attrgetter('option_strings'))
        super(SortedHelpFormatter, self).add_arguments(actions)

public function removeCountry($country)
    {
        if (in_array($country, $this->countries)) {
            unset($this->countries[array_search($country, $this->countries)]);
        }

        return $this;
    }

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


Question:
/*
(non-Javadoc)
@see
RecognizeCallback#onError(java.lang
.Exception)

public void onError(Exception e) {
    LOG.log(Level.SEVERE, e.getMessage(), e);
  }

def handle_error(e, name, args, job)
      if error_handler = Backburner.configuration.on_error
        if error_handler.arity == 1
          error_handler.call(e)
        elsif error_handler.arity == 3
          error_handler.call(e, name, args)
        else
          error_handler.call(e, name, args, job)
        end
      end
    end

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


Question:
Flushes all variations for the provided bundle from the cache.<p>

@param baseName the bundle base name to flush the variations for
@param flushPermanent if true, the cache for additional message bundles will be flushed, too

public static void flushBundleCache(String baseName, boolean flushPermanent) {

        if (baseName != null) {
            synchronized (m_bundleCache) {

                // first check and clear the bundle cache
                Map<BundleKey, ResourceBundle> bundleCacheNew = new ConcurrentHashMap<BundleKey, ResourceBundle>(
                    m_bundleCache.size());
                for (Map.Entry<BundleKey, ResourceBundle> entry : m_bundleCache.entrySet()) {
                    if (!entry.getKey().isSameBase(baseName)) {
                        // entry has a different base name, keep it
                        bundleCacheNew.put(entry.getKey(), entry.getValue());
                    }
                }
                if (bundleCacheNew.size() < m_bundleCache.size()) {
                    // switch caches if only if at least one entry was removed
                    m_bundleCache = bundleCacheNew;
                }
                if (flushPermanent) {
                    flushPermanentCache(baseName);
                }
            }
        }
    }

def handle_single_message(self, msg):

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

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


Question: // SetDisplayName sets the DisplayName field's value.

func (s *GetSigningPlatformOutput) SetDisplayName(v string) *GetSigningPlatformOutput {
	s.DisplayName = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question: get session token

def get_session_token(self):
        '''  '''
        # HTTP POST query to session authenticate API
        try:
            response = requests.post(self.__session_url__ + 'sessionauth/v1/authenticate',
                                     cert=(self.__crt__, self.__key__), verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            raise
        if response.status_code == 200:
            # load json response as list
            data = json.loads(response.text)
            self.logger.debug(data)
            # grab token from list
            session_token = data['token']
        else:
            raise Exception('BAD HTTP STATUS: %s' % str(response.status_code))
        # return the token
        self.logger.debug(session_token)
        return session_token

public function refreshTokenWithAssertion($assertionCredentials = null) {
    if (!$assertionCredentials) {
      $assertionCredentials = $this->assertionCredentials;
    }

    $this->refreshTokenRequest(array(
        'grant_type' => 'assertion',
        'assertion_type' => $assertionCredentials->assertionType,
        'assertion' => $assertionCredentials->generateAssertion(),
    ));
  }

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


Question:
Updates the startup script.

        :param startup_script: content of the startup script

def startup_script(self, startup_script):

        try:
            startup_script_path = os.path.join(self.working_dir, 'startup.vpc')
            with open(startup_script_path, "w+", encoding='utf-8') as f:
                if startup_script is None:
                    f.write('')
                else:
                    startup_script = startup_script.replace("%h", self._name)
                    f.write(startup_script)
        except OSError as e:
            raise VPCSError('Cannot write the startup script file "{}": {}'.format(startup_script_path, e))

private function load_command_config_file($file, $prefix) {

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

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

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

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

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

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

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

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


Question:
// UpdateIfRequired returns true if c.node.Spec.Unschedulable isn't already set,
// or false when no change is needed

func (c *CordonHelper) UpdateIfRequired(desired bool) bool {
	c.desired = desired
	if c.node.Spec.Unschedulable == c.desired {
		return false
	}
	return true
}

public function stepUpdateRecordState($type, $id, $state) {
		$class = $this->convertTypeToClass($type);
		$obj = $this->fixtureFactory->get($class, $id);
		if(!$obj) {
			throw new \InvalidArgumentException(sprintf(
				'Can not find record "%s" with identifier "%s"',
				$type,
				$id
			));
		}

		switch($state) {
			case 'published':
				$obj->publish('Stage', 'Live');
				break;
			case 'not published':
			case 'unpublished':
				$oldMode = \Versioned::get_reading_mode();
				\Versioned::reading_stage('Live');
				$clone = clone $obj;
				$clone->delete();
				\Versioned::reading_stage($oldMode);
				break;
			case 'deleted':
				$obj->delete();
				break;
			default:
				throw new \InvalidArgumentException(sprintf(
					'Invalid state: "%s"', $state
				));
		}
	}

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


Question:
Creates a new mapper for the given type.

@param type
the type for which a mapper is to be created
@return a mapper that can handle the mapping of given type to/from the Cloud Datastore.

private Mapper createMapper(Type type) {
    lock.lock();
    try {
      Mapper mapper = cache.get(type);
      if (mapper != null) {
        return mapper;
      }
      if (type instanceof Class) {
        mapper = createMapper((Class<?>) type);
      } else if (type instanceof ParameterizedType) {
        mapper = createMapper((ParameterizedType) type);
      } else {
        throw new IllegalArgumentException(
            String.format("Type %s is neither a Class nor ParameterizedType", type));
      }
      cache.put(type, mapper);
      return mapper;
    } finally {
      lock.unlock();
    }
  }

def _init_object(self, catalog_id, proxy, runtime, db_name, cat_name, cat_class):
        """"""
        self._catalog_identifier = None
        self._init_proxy_and_runtime(proxy, runtime)

        uses_cataloging = False
        if catalog_id is not None and catalog_id.get_identifier() != PHANTOM_ROOT_IDENTIFIER:
            self._catalog_identifier = catalog_id.get_identifier()

            config = self._runtime.get_configuration()
            parameter_id = Id('parameter:' + db_name + 'CatalogingProviderImpl@mongo')

            try:
                provider_impl = config.get_value_by_parameter(parameter_id).get_string_value()
            except (AttributeError, KeyError, errors.NotFound):
                collection = JSONClientValidated(db_name,
                                                 collection=cat_name,
                                                 runtime=self._runtime)
                try:
                    self._my_catalog_map = collection.find_one({'_id': ObjectId(self._catalog_identifier)})
                except errors.NotFound:
                    if catalog_id.get_identifier_namespace() != db_name + '.' + cat_name:
                        self._my_catalog_map = self._create_orchestrated_cat(catalog_id, db_name, cat_name)
                    else:
                        raise errors.NotFound('could not find catalog identifier ' + catalog_id.get_identifier() + cat_name)
            else:
                uses_cataloging = True
                cataloging_manager = self._runtime.get_manager('CATALOGING',
                                                               provider_impl)  # need to add version argument
                lookup_session = cataloging_manager.get_catalog_lookup_session()
                # self._my_catalog_map = lookup_session.get_catalog(catalog_id)._my_map
                # self._catalog = Catalog(osid_object_map=self._my_catalog_map, runtime=self._runtime,
                #                         proxy=self._proxy)
                self._catalog = lookup_session.get_catalog(catalog_id)
        else:
            self._catalog_identifier = PHANTOM_ROOT_IDENTIFIER
            self._my_catalog_map = make_catalog_map(cat_name, identifier=self._catalog_identifier)

        if not uses_cataloging:
            self._catalog = cat_class(osid_object_map=self._my_catalog_map, runtime=self._runtime, proxy=self._proxy)

        self._catalog._authority = self._authority  # there should be a better way...
        self._catalog_id = self._catalog.get_id()
        self._forms = dict()

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


Question:
Set the maximum image height (if set).

@param int|null $maxHeight

public function setMaxHeight($maxHeight)
    {
        $maxHeight = (int) $maxHeight;
        $this->maxHeight = $maxHeight > 0 ? $maxHeight : null;
    }

public function httpOptions(RequestInterface $request, ResponseInterface $response)
    {
        $methods = $this->server->getAllowedMethods($request->getPath());

        $response->setHeader('Allow', strtoupper(implode(', ', $methods)));
        $features = ['1', '3', 'extended-mkcol'];

        foreach ($this->server->getPlugins() as $plugin) {
            $features = array_merge($features, $plugin->getFeatures());
        }

        $response->setHeader('DAV', implode(', ', $features));
        $response->setHeader('MS-Author-Via', 'DAV');
        $response->setHeader('Accept-Ranges', 'bytes');
        $response->setHeader('Content-Length', '0');
        $response->setStatus(200);

        // Sending back false will interrupt the event chain and tell the server
        // we've handled this method.
        return false;
    }

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


Question:
{@inheritdoc}

@param FlowQuery $flowQuery the FlowQuery object
@param array $arguments the filter expression to use (in index 0)
@return void
@throws FizzleException

public function evaluate(FlowQuery $flowQuery, array $arguments)
    {
        if (!isset($arguments[0]) || empty($arguments[0])) {
            return;
        }
        if (!is_string($arguments[0])) {
            throw new FizzleException('filter operation expects string argument', 1332489625);
        }
        $filter = $arguments[0];

        $parsedFilter = FizzleParser::parseFilterGroup($filter);

        $filteredContext = [];
        $context = $flowQuery->getContext();
        foreach ($context as $element) {
            if ($this->matchesFilterGroup($element, $parsedFilter)) {
                $filteredContext[] = $element;
            }
        }
        $flowQuery->setContext($filteredContext);
    }

public static void configureQueryOptions(DatabaseClient client)
    throws FailedRequestException, ForbiddenUserException, ResourceNotFoundException, ResourceNotResendableException
  {
    // create a manager for writing query options
    QueryOptionsManager optionsMgr = client.newServerConfigManager().newQueryOptionsManager();

    // create the query options
    String options =
      "<search:options "+
        "xmlns:search='http://marklogic.com/appservices/search'>"+
        "<search:constraint name='industry'>"+
        "<search:value>"+
        "<search:element name='industry' ns=''/>"+
        "</search:value>"+
        "</search:constraint>"+
        "<search:return-aggregates>false</search:return-aggregates>"+
        "<search:return-constraints>false</search:return-constraints>"+
        "<search:return-facets>false</search:return-facets>"+
        "<search:return-frequencies>false</search:return-frequencies>"+
        "<search:return-metrics>false</search:return-metrics>"+
        "<search:return-plan>false</search:return-plan>"+
        "<search:return-qtext>false</search:return-qtext>"+
        "<search:return-query>false</search:return-query>"+
        "<search:return-similar>true</search:return-similar>"+
        "<search:return-values>false</search:return-values>"+
        "<search:return-results>false</search:return-results>"+
        "<search:transform-results apply='empty-snippet'/>"+
        "</search:options>";

    // create a handle to send the query options
    StringHandle writeHandle = new StringHandle(options);

    // write the query options to the database
    optionsMgr.writeOptions(OPTIONS_NAME, writeHandle);

    System.out.println("Configured the query options on the server");
  }

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


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

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case DroolsPackage.GLOBAL_TYPE__IDENTIFIER:
				return IDENTIFIER_EDEFAULT == null ? identifier != null : !IDENTIFIER_EDEFAULT.equals(identifier);
			case DroolsPackage.GLOBAL_TYPE__TYPE:
				return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type);
		}
		return super.eIsSet(featureID);
	}

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

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

            config.script = wrapped_script

        return Container(config)

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