Question:
If the given {@link EventPattern} matches the given event type, runs the given action, consumes the event,
and does not attempt to match additional {@code InputMap}s (if they exist).

public static <S, T extends Event, U extends T> InputMapTemplate<S, U> consume(
            EventPattern<? super T, ? extends U> eventPattern,
            BiConsumer<? super S, ? super U> action) {
        return process(eventPattern, (s, u) -> {
            action.accept(s, u);
            return Result.CONSUME;
        });
    }

public CompletableFuture<DeleteStreamStatus.Status> deleteStream(final String scope, final String stream,
                                                                     final OperationContext contextOpt) {
        final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt;
        final long requestId = requestTracker.getRequestIdFor("deleteStream", scope, stream);

        return streamMetadataStore.getState(scope, stream, false, context, executor)
                .thenCompose(state -> {
                    if (!state.equals(State.SEALED)) {
                        return CompletableFuture.completedFuture(false);
                    } else {
                        return streamMetadataStore.getCreationTime(scope, stream, context, executor)
                                                  .thenApply(time -> new DeleteStreamEvent(scope, stream, requestId, time))
                                                  .thenCompose(event -> writeEvent(event))
                                .thenApply(x -> true);
                    }
                })
                .thenCompose(result -> {
                    if (result) {
                        return checkDone(() -> isDeleted(scope, stream))
                                .thenApply(x -> DeleteStreamStatus.Status.SUCCESS);
                    } else {
                        return CompletableFuture.completedFuture(DeleteStreamStatus.Status.STREAM_NOT_SEALED);
                    }
                })
                .exceptionally(ex -> {
                    log.warn(requestId, "Exception thrown while deleting stream {}", ex.getMessage());
                    return handleDeleteStreamError(ex, requestId);
                });
    }

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


Question:
Check if the band structure indicates a metal by looking if the fermi
        level crosses a band.

        Returns:
            True if a metal, False if not

def is_metal(self, efermi_tol=1e-4):

        for spin, values in self.bands.items():
            for i in range(self.nb_bands):
                if np.any(values[i, :] - self.efermi < -efermi_tol) and \
                        np.any(values[i, :] - self.efermi > efermi_tol):
                    return True
        return False

function(time) {
			var t        = this;

			time = time ? time : (this.factory.time.time ? this.factory.time.time : this.factory.time.getTime());

			this.base(time);
			this.meridiumText = this._isPM() ? 'PM' : 'AM';
			this.meridium = $([
				'
',
					'
',
						''+this.meridiumText+'',
					'
',
				'
'
			].join(''));

			this.meridium.insertAfter(this.factory.lists[this.factory.lists.length-1].$obj);
		}

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


Question:
Use the tables in self.paleos and self.chrons (sorted by idx) to put in self.noaa_data_sorted.
        :return:

def __get_table_pairs(self):

        try:
            for _idx, _p in enumerate(self.data_paleos):
                _c = {}
                try:
                    _c = self.data_chrons[_idx]
                except IndexError:
                    pass
                # create entry in self object collection of data tables
                self.noaa_data_sorted["Data"].append({"paleo": _p, "chron": _c})
        except KeyError:
            logger_lpd_noaa.warning("lpd_noaa: get_meas_table: 0 paleo data tables")

        self.output_file_ct = len(self.noaa_data_sorted["Data"])
        return

public function getMenu() {
        $wt_tree = Globals::getTree();
        $menu = null;
        if(ModuleManager::getInstance()->isOperational($this->getName())) {

            $root_url = 'module.php?mod=' . $this->getName() . '&ged=' . $wt_tree->getNameUrl() . '&';
            $sosa_stat_menu = new Menu(I18N::translate('Sosa Statistics'), $root_url . 'mod_action=SosaStats', 'menu-maj-sosa-stats');

            $menu = clone $sosa_stat_menu;
            $menu->setClass('menu-maj-sosa');

            $submenus = array_filter(array(
                new Menu(I18N::translate('Sosa Ancestors'), $root_url . 'mod_action=SosaList', 'menu-maj-sosa-list', array('rel' => 'nofollow')),
                new Menu(I18N::translate('Missing Ancestors'), $root_url . 'mod_action=SosaList@missing', 'menu-maj-sosa-missing', array('rel' => 'nofollow')),
                $sosa_stat_menu
            ));

            if (ModuleManager::getInstance()->isOperational(Constants::MODULE_MAJ_GEODISP_NAME)
                && $ga_list = Module::getModuleByName(Constants::MODULE_MAJ_GEODISP_NAME)->getProvider()->getGeoAnalysisList()
                )
            {
                if(count($ga_list) > 0) {
                    $submenus[] = new Menu(I18N::translate('Geographical Dispersion'), 'module.php?mod=' . Constants::MODULE_MAJ_GEODISP_NAME . '&ged=' . $wt_tree->getNameUrl() . '&mod_action=GeoAnalysis@listAll', 'menu-maj-sosa-geodispersion');
                }
            }

            if(Auth::check()) {
                $submenus[] = new Menu(
                    I18N::translate('Sosa Configuration'),
                    $this->getConfigLink(),
                    'menu-maj-sosa-configuration',
                    array('rel' => 'nofollow'));
            }

            //-- recompute Sosa submenu
            $controller = Globals::getController();
            if (!empty($controller) && $controller instanceof IndividualController
                && Auth::check() && $wt_tree->getUserPreference(Auth::user(), 'MAJ_SOSA_ROOT_ID')
                ) {
                $controller
                    ->addInlineJavascript('
                        function majComputeSosaFromIndi(){
                            if($("#computesosadlg").length == 0) {
                                $("body").append("

");
                            }
	                        $("#computesosadlg").dialog({
                                modal: true,
                                closeOnEscape: false,
		                        width: 300,
		                        open: function(event, ui) {
			                        $("button.ui-dialog-titlebar-close").hide();
                                    $("#sosaloadingarea").empty().html("");
			                        $("#sosaloadingarea").load("module.php?mod=' . $this->getName() . '&mod_action=SosaConfig@computePartial&ged='. $wt_tree->getNameUrl() .'&userid='.Auth::user()->getUserId().'&pid=' . $controller->getSignificantIndividual()->getXref() . '",
					                   function(){
						                  $("button.ui-dialog-titlebar-close").show();
                                          setTimeout(function(){
                                            $("#computesosadlg").dialog("close");
                                          }, 2000);
			                            });
		                          }
	                         });
                        }');

                $submenus[] = new Menu(
                    I18N::translate('Complete Sosas'),
                    '#',
                    'menu-maj-sosa-recompute',
                    array(
                        'rel' => 'nofollow',
                        'onclick' => 'return majComputeSosaFromIndi();'
                    ));
            }

        }

        $menu->setSubmenus($submenus);

        return $menu;

    }

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


Question: Refreshes/reloads cache and other state information periodically.

private function refreshCacheStateInfo()
    {
        if ( time() < ( $this->lastRefreshTimestamp + $this->sleepInterval ) )
        {
            return;
        }

        // Reload expiry timestamps
        eZExpiryHandler::instance()->restore();

        $this->lastRefreshTimestamp = time();
    }

@Override
	public void clearCache() {
		entityCache.clearCache(CommerceDiscountRelImpl.class);

		finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

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


Question:
Update a group

@author Steve Montambeault
@link   http://stevemo.ca

@param array $data

@return Bool

public function update(array $data)
    {
        try
        {
            if ($this->validator->with($data)->validForUpdate())
            {
                $this->groups->update($data);
                return true;
            }
        }
        catch (GroupExistsException $e)
        {
            $this->validator->add('GroupExistsException', $e->getMessage());
        }
        catch (NameRequiredException $e)
        {
            $this->validator->add('NameRequiredException', $e->getMessage());
        }

        return false;
    }

def auth_traps_enabled(name, status=True):
    '''

    '''
    ret = {'name': name,
           'changes': {},
           'comment': six.text_type(),
           'result': None}

    vname = 'EnableAuthenticationTraps'
    current_status = __salt__['win_snmp.get_auth_traps_enabled']()

    if status == current_status:
        ret['comment'] = '{0} already contains the provided value.'.format(vname)
        ret['result'] = True
    elif __opts__['test']:
        ret['comment'] = '{0} will be changed.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
    else:
        ret['comment'] = 'Set {0} to contain the provided value.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
        ret['result'] = __salt__['win_snmp.set_auth_traps_enabled'](status=status)

    return ret

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


Question: Internal delete message helper.

def _delete_uncompressed(
        collection_name, spec, safe, last_error_args, opts, flags=0):
    """"""
    op_delete, max_bson_size = _delete(collection_name, spec, opts, flags)
    rid, msg = __pack_message(2006, op_delete)
    if safe:
        rid, gle, _ = __last_error(collection_name, last_error_args)
        return rid, msg + gle, max_bson_size
    return rid, msg, max_bson_size

public function hDel($key, $field) {
        return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field);
    }

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


Question:
{@inheritdoc}
@param array $fieldDeclaration
@param AbstractPlatform $platform
@return string

public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
	{
		$fieldDeclaration['length'] = 20;
		$fieldDeclaration['fixed'] = true;

		$sql = $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);

		//todo: check if this is sane, at least
		$sql .= ' COLLATE ascii_general_ci';

		return $sql;
	}

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

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

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

        $class = new ReflectionClass($model);

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

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

        return $ret;
    }

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


Question:
Return a link to this field

@param string $action
@return string
@throws LogicException If no form is set yet

public function Link($action = null)
    {
        if (!$this->form) {
            throw new LogicException(
                'Field must be associated with a form to call Link(). Please use $field->setForm($form);'
            );
        }

        $link = Controller::join_links($this->form->FormAction(), 'field/' . $this->name, $action);
        $this->extend('updateLink', $link, $action);
        return $link;
    }

public function toRoute($route)
	{
		if ($this->caller != null)
			$this->disableRender[] = $this->caller->identifier;
		$r = $this->router->getRoute($route);
		if ($r != null) {
			$this->currentRoute = $r;
			try {
				$this->execute();
			} catch (\Exception $e) {
				Logger::Log('log/error.txt', $e->getMessage());
				\decoy\base\ErrorController::$errors[] = $e->getMessage();
				$this->toRoute('error_page');
			}
		}
		$this->caller = null;
	}

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


Question:
@param Connection              $connection
@param DatabaseSchemaInterface $schema

@return void

@throws DBALException

protected function createTokensTable(Connection $connection, DatabaseSchemaInterface $schema): void
    {
        $manager = $connection->getSchemaManager();

        $table = new Table($schema->getTokensTable());
        $table->addColumn($schema->getTokensIdentityColumn(), Type::INTEGER)
            ->setNotnull(true)->setAutoincrement(true)->setUnsigned(true);
        $table->addColumn($schema->getTokensIsEnabledColumn(), Type::BOOLEAN)->setNotnull(true)->setDefault(true);
        $table->addColumn($schema->getTokensIsScopeModified(), Type::BOOLEAN)->setNotnull(true)->setDefault(false);
        $table->addColumn($schema->getTokensClientIdentityColumn(), Type::STRING)->setNotnull(true);
        $table->addColumn($schema->getTokensUserIdentityColumn(), Type::INTEGER)->setNotnull(false)->setUnsigned(true);
        $table->addColumn($schema->getTokensRedirectUriColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensCodeColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensTypeColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensValueColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensRefreshColumn(), Type::STRING)->setNotnull(false);
        $table->addColumn($schema->getTokensCodeCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->addColumn($schema->getTokensValueCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->addColumn($schema->getTokensRefreshCreatedAtColumn(), Type::DATETIME)->setNotnull(false);
        $table->setPrimaryKey([$schema->getTokensIdentityColumn()]);

        $table->addForeignKeyConstraint(
            $schema->getClientsTable(),
            [$schema->getTokensClientIdentityColumn()],
            [$schema->getClientsIdentityColumn()],
            $this->getOnDeleteCascadeConstraint()
        );

        $usersTable          = $schema->getUsersTable();
        $usersIdentityColumn = $schema->getUsersIdentityColumn();
        if ($usersTable !== null && $usersIdentityColumn !== null) {
            $table->addForeignKeyConstraint(
                $usersTable,
                [$schema->getTokensUserIdentityColumn()],
                [$usersIdentityColumn],
                $this->getOnDeleteCascadeConstraint()
            );
        }

        $manager->dropAndCreateTable($table);
    }

String getLiteralPrefix() {

        switch (type) {

            case Types.SQL_BINARY :
            case Types.SQL_BLOB :
            case Types.SQL_CHAR :
            case Types.SQL_NCHAR :
            case Types.SQL_CLOB :
            case Types.SQL_VARBINARY :
            case Types.SQL_VARCHAR :
            case Types.SQL_NVARCHAR :
                return "'";

            case Types.SQL_DATALINK :
                return "'";    // hypothetically: "{url '";

            case Types.SQL_DATE :
                return "'";    // or JDBC escape: "{d '";

            case Types.OTHER :
                return "'";    // hypothetically: "{o '"; or new "pkg.cls"(...)

            case Types.SQL_TIME_WITH_TIME_ZONE :
            case Types.SQL_TIME :
                return "'";    // or JDBC escape: "{t '";

            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
            case Types.SQL_TIMESTAMP :
                return "'";    // or JDBC escape: "{ts '";

            case Types.SQL_XML :
                return "'";    // hypothetically: "{xml '";

            default :
                return null;
        }
    }

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


Question: Return a string of text containing part-of-speech, lemma pairs.

def get_bigram_pair_string(self, text):

        bigram_pairs = []

        if len(text) <= 2:
            text_without_punctuation = text.translate(self.punctuation_table)
            if len(text_without_punctuation) >= 1:
                text = text_without_punctuation

        document = self.nlp(text)

        if len(text) <= 2:
            bigram_pairs = [
                token.lemma_.lower() for token in document
            ]
        else:
            tokens = [
                token for token in document if token.is_alpha and not token.is_stop
            ]

            if len(tokens) < 2:
                tokens = [
                    token for token in document if token.is_alpha
                ]

            for index in range(1, len(tokens)):
                bigram_pairs.append('{}:{}'.format(
                    tokens[index - 1].pos_,
                    tokens[index].lemma_.lower()
                ))

        if not bigram_pairs:
            bigram_pairs = [
                token.lemma_.lower() for token in document
            ]

        return ' '.join(bigram_pairs)

public function parseToken($content, $position, $state, TokenList $tokenList) {
        switch ($state) {
            case Lexer::STATE_MATCHED:
                $this->handleMatchedState($content, $position, $tokenList);
                break;
            default:
                parent::parseToken($content, $position, $state, $tokenList);
                break;
        }
    }

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


Question:
Boot the service provider.

@return void

public function bootExtensionComponents()
    {
        $path = __DIR__ . '/../';
        $this->addConfigComponent('antares/notifications', 'antares/notifications', "{$path}/resources/config");
        $this->addLanguageComponent('antares/notifications', 'antares/notifications', "{$path}/resources/lang");
        $this->addViewComponent('antares/notifications', 'antares/notifications', "{$path}/resources/views");
        $this->bootMemory();
        $this->attachMenu(NotificationsTopMenuHandler::class);
        if (config('antares/notifications::sockets')) {
            publish('notifications', 'scripts.default');
        }
        $this->attachMenu(NotificationsBreadcrumbMenu::class);
        $this->app->make('view')->composer('antares/notifications::admin.logs.config', ControlPane::class);

        Option::observe(new ConfigurationListener());
    }

public function redirectAbs($url, $statusCode = 302)
    {
        $router = $this->getService('Router');
        $router->redirect($url, $statusCode);
        exit;
    }

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


Question: // SetCreatedAt sets the CreatedAt field's value.

func (s *Operation) SetCreatedAt(v time.Time) *Operation {
	s.CreatedAt = &v
	return s
}

public function markAsRead()
    {
        if (is_null($this->read_at)) {
            $this->forceFill(array(
                'read_at' => $this->freshTimestamp()
            ));

            $this->save();
        }
    }

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


Question: store binaries ribbon objects (pictures)

public function setRibbonBinObjects($BinObjectsNames = null, $BinObjectsData = null)
    {
        if (!is_null($BinObjectsNames) && !is_null($BinObjectsData)) {
            $this->ribbonBinObjects = array('names' => $BinObjectsNames, 'data' => $BinObjectsData);
        } else {
            $this->ribbonBinObjects = null;
        }
    }

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: r"""Convert the container to a string in latex syntax.

def dumps(self):
        """

        content = self.dumps_content()

        if not content.strip() and self.omit_if_empty:
            return ''

        string = ''

        start = Command(self.latex_name, arguments=self.arguments,
                        options=self.options)

        string += start.dumps() + '{ \n'

        if content != '':
            string += content + '\n}'
        else:
            string += '}'

        return string

def to_html(self):

        text = self.text
        if text is None:
            text = self.uri
        return '%s' % (
            self.uri, self.html_attributes(), text)

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


Question:
Format a column of data for display

@param stdClass $row
@return string

public function col_grademax(stdClass $row) {
        if ($this->assignment->get_instance()->grade > 0) {
            $gradeitem = $this->assignment->get_grade_item();
            return format_float($this->assignment->get_instance()->grade, $gradeitem->get_decimals());
        } else {
            return '';
        }
    }

public function getProgressBar() : ProgressBar
    {
        if (!$this->progressBar) {
            $this->progressBar = new ProgressBar($this->getOutput(), $this->numRecords);
            $this->progressBar->setFormat('debug');
            $this->progressBar->setBarWidth((int) exec('tput cols'));
        }

        return $this->progressBar;
    }

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


Question:
Tests if an object is of the SavantPHPerror class.

@param $obj
@return bool

public function isError($obj)
    {
        // is it even an object?
        if (! is_object($obj)) { // if not an object, can't even be a SavantPHPerror object
            return false;
        } else {
            // now compare the parentage
            $is = $obj instanceof SavantPHPerror;
            $sub = is_subclass_of($obj, 'SavantPHPerror');
            return ($is || $sub);
        }
    }

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

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

        $this->emitSentryClientCreated($client);
    }

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


Question:
Returns reference name for identifying this model's records in version table.

@return string

protected function _referenceName()
    {
        $table = $this->_table;
        $name = namespaceSplit(get_class($table));
        $name = substr(end($name), 0, -5);
        if (empty($name)) {
            $name = $table->getTable() ?: $table->getAlias();
            $name = Inflector::camelize($name);
        }

        return $name;
    }

def tableinfo(tableid, lang=DEFAULT_LANGUAGE):

    request = Request('tableinfo', tableid, lang=lang)

    return Tableinfo(request.json, lang=lang)

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


Question:
Traverses the Spark application master in YARN to get a Spark application ID.

        Return a dictionary of {app_id: (app_name, tracking_url)} for Spark applications

def _get_spark_app_ids(self, running_apps, requests_config, tags):

        spark_apps = {}
        for app_id, (app_name, tracking_url) in iteritems(running_apps):
            response = self._rest_request_to_json(
                tracking_url, SPARK_APPS_PATH, SPARK_SERVICE_CHECK, requests_config, tags
            )

            for app in response:
                app_id = app.get('id')
                app_name = app.get('name')

                if app_id and app_name:
                    spark_apps[app_id] = (app_name, tracking_url)

        return spark_apps

def shard_query_generator(self, query):
    ''''''
    shard_query = query.copy()

    for shard in self._stores:
      # yield all items matching within this shard
      cursor = shard.query(shard_query)
      for item in cursor:
        yield item

      # update query with results of first query
      shard_query.offset = max(shard_query.offset - cursor.skipped, 0)
      if shard_query.limit:
        shard_query.limit = max(shard_query.limit - cursor.returned, 0)

        if shard_query.limit <= 0:
          break

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


Question: Insert user data into.

protected function createsession(){
		bimport('users.general');
		bimport('users.social.user');
		bimport('users.social.users');
		$bsu=BUsersSocialUsers::getInstance();
		$list=$bsu->items_filter(array('provider'=>$this->provider,'social_id'=>$this->getSocialId()));
		$user=NULL;
		if(!empty($list)){
			BLog::addToLog('[Social.Adapter] Found social record in the database!');
			$su=reset($list);
			$user=$su->getuser();
			}else{
			BLog::addToLog('[Social.Adapter] Could not find social record in the database! Need to create it.');
			//Try to load existing user with such email.
			$email=$this->getEmail();
			if(!empty($email)){
				BLog::addToLog('[Social.Adapter] Loading user by email "'.$email.'"!');
				$bu=BUsers::getInstance();
				$user=$bu->get_user_byemail($email);
				}
			//If we have not loaded user =
			if(empty($user)){
				BLog::addToLog('[Social.Adapter] Could not load user! Creating it. Email="'.$email.'"');
				$user=new BUser();
				$user->email=empty($email)?NULL:$email;
				$user->name=$this->getName();
				$user->active='Y';
				$user->birthday=$this->getBirthdayObject();
				$user->last_action=new DateTime();
				$r=$user->saveToDB();
				if(empty($r)){
					BLog::addToLog('[Social.Adapter] Could not save user!',LL_ERROR);
					return false;
					}
				BLog::addToLog('[Social.Adapter] User saved. User id='.$user->id.'.');
				//User saved.
				}
			$su=new BUsersSocialUser();
			$su->user=$user->id;
			$su->social_id=$this->getSocialId();
			$su->provider=$this->provider;
			$su->created=new DateTime();
			}
		if(empty($su)){
			BLog::addToLog('[Social.Adapter] Could not load social user record!',LL_ERROR);
			return false;
			}
		if(empty($user)){
			BLog::addToLog('[Social.Adapter] Could not load user!',LL_ERROR);
			return false;
			}
		//Get fields.
		$su->name=$this->getName();
		$su->email=$this->getEmail();
		$su->sex=$this->getSex();
		$su->birthday=$this->getBirthdayObject();
		$su->lastlogin=new DateTime();
		$su->avatar_remote=$this->getAvatar();
		$su->social_page=$this->getSocialPage();
		if(!empty($su->avatar_remote)){
			$r=$su->downloadavatar();
			if(!$r){
				return false;
				}
			}
		$r=$su->saveToDB();
		if(!$r){
			return false;
			}
		if((!empty($su->avatar_local))&&($user->avatar!=$su->avatar_local)){
			$user->avatar=$su->avatar_local;
			$user->saveToDB();
			}
		//Session.
		$options=array('interval'=>2592000,'updatestep'=>60);
		$sess=BUsersSession::getInstance();
		$r=$sess->newSession($user->id,$options);
		if(empty($r)){
			return false;
			}
		return true;
		}

func (m *MetaClient) CreateUser(ctx context.Context, name, passwd string) error {
	return m.CreateUpdateUser(ctx, "create", name, passwd)
}

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


Question:
Returns a {@code com.google.protobuf.Timestamp} initialized to the same point in time as {@code
this}.

public com.google.protobuf.Timestamp toProto() {
    return com.google.protobuf.Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
  }

public void marshall(Operator operator, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(operator.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(operator.getValues(), VALUES_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
获取JsApi使用签名
@param string $url 网页的URL
@param string $appid 用于多个appid时使用(可空)
@param string $ticket 强制指定ticket
@return array
@throws Exceptions\LocalCacheException
@throws InvalidResponseException

public function getJsSign($url, $appid = null, $ticket = null)
    {
        list($url,) = explode('#', $url);
        is_null($ticket) && $ticket = $this->getTicket('jsapi');
        is_null($appid) && $appid = $this->config->get('appid');
        $data = ["url" => $url, "timestamp" => '' . time(), "jsapi_ticket" => $ticket, "noncestr" => Tools::createNoncestr(16)];
        return [
            'debug'     => false,
            "appId"     => $appid,
            "nonceStr"  => $data['noncestr'],
            "timestamp" => $data['timestamp'],
            "signature" => $this->getSignature($data, 'sha1'),
            'jsApiList' => [
                'updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone',
                'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice',
                'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation',
                'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem',
                'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard',
            ],
        ];
    }

func (o *UpdateJSONWebKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewUpdateJSONWebKeyOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 401:
		result := NewUpdateJSONWebKeyUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 403:
		result := NewUpdateJSONWebKeyForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewUpdateJSONWebKeyInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

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


Question: // Float32 generates arbitrary float32 numbers that do not contain NaN or Inf

func Float32() gopter.Gen {
	return gopter.CombineGens(
		Int32Range(0, 1),
		Int32Range(0, 0xfe),
		Int32Range(0, 0x7fffff),
	).Map(func(values []interface{}) float32 {
		sign := uint32(values[0].(int32))
		exponent := uint32(values[1].(int32))
		mantissa := uint32(values[2].(int32))

		return math.Float32frombits((sign << 31) | (exponent << 23) | mantissa)
	}).WithShrinker(Float32Shrinker)
}

func randomStagger(interval time.Duration) time.Duration {
	stagger := time.Duration(mrand.Int63()) % (interval / 2)
	return 3*(interval/4) + stagger
}

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


Question:
{@inheritDoc}

@param otherObj object to compare to
@return -1, 0, or 1

@Override
    public int compareTo(final AbstractAttr<T> otherObj) {
        if (otherObj == null) {
            return 1;
        } else {
            return value.compareTo(otherObj.value);
        }
    }

def _do_document(self, node):
        ''''''

        self.documentOrder = _LesserElement
        for child in node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE:
                self.documentOrder = _Element        # At document element
                self._do_element(child)
                self.documentOrder = _GreaterElement # After document element
            elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._do_pi(child)
            elif child.nodeType == Node.COMMENT_NODE:
                self._do_comment(child)
            elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
                pass
            else:
                raise TypeError, str(child)

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


Question:
Updates the given custom field.

@param CustomField $customField The custom field to update

@return CustomField

public function update(CustomField $customField): CustomField
    {
        $id = $customField->getId();

        $customField->setId(null);

        $response = $this->client->put($this->prepareUrlForKey('update-custom-field', ['id' => $id]), [], $customField->jsonSerialize());
        $responseData = $response->getDecodedBody();

        return new CustomField($responseData);
    }

public function createMarkAction(Request $request, Result $result, User $user)
    {
        $this->assertCanEdit($result);
        $mark = $request->request->get('mark', false);
        $response = new JsonResponse();

        if ($mark !== false) {
            if (!$this->manager->isValidMark($result, $mark)) {
                $response->setData('Mark is not valid');
                $response->setStatusCode(422);
            } else {
                $mark = $this->manager->createMark($result, $user, $mark);
                $response->setData($mark->getId());
            }
        } else {
            $response->setData('Field "mark" is missing');
            $response->setStatusCode(422);
        }

        return $response;
    }

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


Question:
Return download data by version.

        :return: dict of cache data; keys are datetime objects, values are
          dict of version (str) to count (int)
        :rtype: dict

def per_version_data(self):

        ret = {}
        for cache_date in self.cache_dates:
            data = self._cache_get(cache_date)
            if len(data['by_version']) == 0:
                data['by_version'] = {'other': 0}
            ret[cache_date] = data['by_version']
        return ret

func (c *Chunk) AppendDatum(colIdx int, d *types.Datum) {
	switch d.Kind() {
	case types.KindNull:
		c.AppendNull(colIdx)
	case types.KindInt64:
		c.AppendInt64(colIdx, d.GetInt64())
	case types.KindUint64:
		c.AppendUint64(colIdx, d.GetUint64())
	case types.KindFloat32:
		c.AppendFloat32(colIdx, d.GetFloat32())
	case types.KindFloat64:
		c.AppendFloat64(colIdx, d.GetFloat64())
	case types.KindString, types.KindBytes, types.KindBinaryLiteral, types.KindRaw, types.KindMysqlBit:
		c.AppendBytes(colIdx, d.GetBytes())
	case types.KindMysqlDecimal:
		c.AppendMyDecimal(colIdx, d.GetMysqlDecimal())
	case types.KindMysqlDuration:
		c.AppendDuration(colIdx, d.GetMysqlDuration())
	case types.KindMysqlEnum:
		c.AppendEnum(colIdx, d.GetMysqlEnum())
	case types.KindMysqlSet:
		c.AppendSet(colIdx, d.GetMysqlSet())
	case types.KindMysqlTime:
		c.AppendTime(colIdx, d.GetMysqlTime())
	case types.KindMysqlJSON:
		c.AppendJSON(colIdx, d.GetMysqlJSON())
	}
}

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


Question:
removes first value found by linear search from array a
@param a array to remove from
@param value value to remove from array
@return new array with value removed

public static int[] removeFromIntArray(int[] a, int value) {

		if(a == null) {
			throw new NullPointerException("Array was null");
		}

		int index = -1;
		for(int i = 0; i < a.length; i++) {
			if(a[i] == value) {
				index = i;
				break;
			}
		}
		if(index < 0) {
			throw new IllegalArgumentException(String.format("Element %d not found in array", value));
		}

		int[] array = new int[a.length - 1];
		if(index > 0) {
			System.arraycopy(a, 0, array, 0, index);
		}
		if(index < a.length) {
			System.arraycopy(a, index + 1, array, index, array.length - index);
		}

		return array;
	}

private function parseCet(ResponseInterface $response, $photoSavePath = '', $saveName = '')
    {
        $body = $this->checkAndThrow($response);

        $crawler = new Crawler($body);
        // 教务信息
        $ret['info'] = [
            'year'   => $crawler->filter('#Label1')->text(),
            'term'   => $crawler->filter('#Label2')->text(),
            'remark' => $crawler->filter('#Label3')->text(),
        ];
        // 可报名列表
        $ret['list'] = Parser::table($crawler, '#DBGrid', [
            ['chk', function (Crawler $crawler, $getValueMethod) {
                return $crawler->filter('input')->attr('name');
            }],
            'name', 'type', '', 'can_apply', 'require', 'fit', 'limit', 'remark', 'markup',
        ], 0, 1);
        // 已报名列表
        $ret['applied'] = Parser::table($crawler, '#DBGridInfo', [
            'no', 'name', '', '', 'id_card', 'is_pay', 'original_no', 'reserve_type', 'reserve_grade', ['delete_id', function (Crawler $crawler, $getValueMethod) {
                if (preg_match('/\'(.*?)\'/', $crawler->filter('a')->attr('href'), $matches)) {
                    return str_replace('$', ":", $matches[1]);
                }

                return '';
            }],
        ], 8);
        // 学生信息
        $ret['student'] = [
            'photo'   => $crawler->filter('#xszp')->attr('src'),
            'id_card' => $crawler->filter('#Labsfzh')->text(),
        ];
        // 是否下载学生照片
        if ($photoSavePath) {
            if (!$saveName) {
                $saveName = 'student-photo-' . $this->getUsername() . '.png';
            }
            // 头像下载地址
            $downloadUrl = Config::get('url.student_photo');
            // 下载文件
            $response = $this->request('get', [$downloadUrl, [], [
                'sink' => $photoSavePath . $saveName,
            ]]);

            $ret['student']['photo_save'] = $saveName;
        }

        return $ret;
    }

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


Question:
// Expiry returns expiry time for temporary users. Prefer expires from
// metadata, if it does not exist, fall back to expires in spec.

func (u *UserV2) Expiry() time.Time {
	if u.Metadata.Expires != nil && !u.Metadata.Expires.IsZero() {
		return *u.Metadata.Expires
	}
	return u.Spec.Expires
}

func serviceWatch(params map[string]interface{}) (WatcherFunc, error) {
	stale := false
	if err := assignValueBool(params, "stale", &stale); err != nil {
		return nil, err
	}

	var (
		service string
		tags    []string
	)
	if err := assignValue(params, "service", &service); err != nil {
		return nil, err
	}
	if service == "" {
		return nil, fmt.Errorf("Must specify a single service to watch")
	}
	if err := assignValueStringSlice(params, "tag", &tags); err != nil {
		return nil, err
	}

	passingOnly := false
	if err := assignValueBool(params, "passingonly", &passingOnly); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		health := p.client.Health()
		opts := makeQueryOptionsWithContext(p, stale)
		defer p.cancelFunc()
		nodes, meta, err := health.ServiceMultipleTags(service, tags, passingOnly, &opts)
		if err != nil {
			return nil, nil, err
		}
		return WaitIndexVal(meta.LastIndex), nodes, err
	}
	return fn, nil
}

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


Question:
This method is intend to return the current month.

@param mixed $timestamp The timestamp to use as date/time-base

@author Benjamin Carl <opensource@clickalicious.de>
@return string Month
@access public

public function getMonth($timestamp = false)
    {
        if (!$timestamp) {
            $timestamp = $this->dateTime->getTimestamp();
        }

        return date('n', $timestamp);
    }

public static function get_metadata(collection $collection) : collection {
        $statsuserdaily = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];

        $statsuserweekly = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];

        $statsusermonthly = [
            'courseid' => 'privacy:metadata:courseid',
            'userid' => 'privacy:metadata:userid',
            'roleid' => 'privacy:metadata:roleid',
            'timeend' => 'privacy:metadata:timeend',
            'statsreads' => 'privacy:metadata:statsreads',
            'statswrites' => 'privacy:metadata:statswrites',
            'stattype' => 'privacy:metadata:stattype'
        ];
        $collection->add_database_table('stats_user_daily', $statsuserdaily, 'privacy:metadata:statssummary');
        $collection->add_database_table('stats_user_weekly', $statsuserweekly, 'privacy:metadata:statssummary');
        $collection->add_database_table('stats_user_monthly', $statsusermonthly, 'privacy:metadata:statssummary');
        return $collection;
    }

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


Question:
Parses the message for this type

@param array

public function parseFromArray()
    {
        $this->value = $this->reader->next();
        $this->value = ($this->value !== 0) ? 1 : 0;
    }

func NewRunMessage(statement string, parameters map[string]interface{}) RunMessage {
	return RunMessage{
		statement:  statement,
		parameters: parameters,
	}
}

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


Question:
// NewSnapshotter returns a Snapshotter which copies layers on the underlying
// file system. A metadata file is stored under the root.

func NewSnapshotter(root string) (snapshots.Snapshotter, error) {
	if err := os.MkdirAll(root, 0700); err != nil {
		return nil, err
	}
	ms, err := storage.NewMetaStore(filepath.Join(root, "metadata.db"))
	if err != nil {
		return nil, err
	}

	if err := os.Mkdir(filepath.Join(root, "snapshots"), 0700); err != nil && !os.IsExist(err) {
		return nil, err
	}

	return &snapshotter{
		root: root,
		ms:   ms,
	}, nil
}

def _setup_metrics(self):

        path = os.environ.get("prometheus_multiproc_dir")
        if not os.path.exists(self.metrics_dir):
            try:
                log.info("Creating metrics directory")
                os.makedirs(self.metrics_dir)
            except OSError:
                log.error("Failed to create metrics directory!")
                raise ConfigurationException("Failed to create metrics directory!")
            path = self.metrics_dir
        elif path != self.metrics_dir:
            path = self.metrics_dir
        os.environ['prometheus_multiproc_dir'] = path
        log.info("Cleaning metrics collection directory")
        log.debug("Metrics directory set to: {}".format(path))
        files = os.listdir(path)
        for f in files:
            if f.endswith(".db"):
                os.remove(os.path.join(path, f))
            log.debug("Starting metrics exposition")
        if self.metrics_enabled:
            registry = CollectorRegistry()
            multiprocess.MultiProcessCollector(registry)
            start_http_server(
                port=self.metrics_port,
                addr=self.metrics_address,
                registry=registry
            )

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


Question:
Close the direct edit tag, also prints the direct edit HTML to the current page.<p>

@return {@link #EVAL_PAGE}

@throws JspException in case something goes wrong

@Override
    public int doEndTag() throws JspException {

        if (m_firstOnPage || m_manualPlacement) {
            // only execute action for the first "editable" tag on the page (include file), or in manual mode
            editableTagAction(pageContext, m_provider, m_mode, m_file);
        }
        if (OpenCms.getSystemInfo().getServletContainerSettings().isReleaseTagsAfterEnd()) {
            // need to release manually, JSP container may not call release as required (happens with Tomcat)
            release();
        }

        return EVAL_PAGE;
    }

def simple_value(self, elt, ps, mixed=False):
        '''
        '''
        if not _valid_encoding(elt):
            raise EvaluateException('Invalid encoding', ps.Backtrace(elt))
        c = _children(elt)
        if mixed is False:
            if len(c) == 0:
                raise EvaluateException('Value missing', ps.Backtrace(elt))
            for c_elt in c:
                if c_elt.nodeType == _Node.ELEMENT_NODE:
                    raise EvaluateException('Sub-elements in value',
                        ps.Backtrace(c_elt))

        # It *seems* to be consensus that ignoring comments and
        # concatenating the text nodes is the right thing to do.
        return ''.join([E.nodeValue for E in c
                if E.nodeType
                in [ _Node.TEXT_NODE, _Node.CDATA_SECTION_NODE ]])

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


Question:
Asked if can be deallocate (is not shared in other statement and not in cache) Set deallocate
flag to true if so.

@return true if can be deallocate

public synchronized boolean canBeDeallocate() {
    if (shareCounter > 0 || isBeingDeallocate) {
      return false;
    }
    if (!inCache.get()) {
      isBeingDeallocate = true;
      return true;
    }
    return false;
  }

func reorderChunks(name string, respCh <-chan *chunkResp, chunkRespc chan<- *chunkResp, eofCh chan<- struct{}, closedc <-chan struct{}) {
	pending := make(map[int64]*chunkResp)
	var off int64
	for resp := range respCh {
		glog.V(2).Infof("Received chunk (off=%d chunk=<%d bytes> err=%v", resp.off, len(resp.chunk), resp.err)
		pending[resp.off] = resp
		if resp.err != nil && eofCh != nil {
			close(eofCh)
			eofCh = nil
		}
		for {
			resp, ok := pending[off]
			if !ok {
				break
			}
			if resp.err != nil && resp.err != io.EOF {
				glog.Errorf("readahead %s: about to report an error %v", name, resp.err)
			}
			glog.V(2).Infof("Returning chunk (off=%d chunk=<%d bytes> err=%v", resp.off, len(resp.chunk), resp.err)
			select {
			case chunkRespc <- resp:
			case <-closedc:
				// N.B. We are aborting here before draining respCh; the other
				// goroutines will abort asynchronously on closedc as well.
				return
			}
			delete(pending, off)
			off += int64(len(resp.chunk))
		}
	}
}

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


Question:
Members list

@link https://developer.github.com/v3/orgs/members/#members-list

@param string $org
@param string $filter
@param string $role

@return array

public function listMembers(string $org, string $filter = AbstractApi::FILTER_ALL, string $role = 'admin'): array
    {
        $this->getApi()->setAccept('application/vnd.github.moondragon+json');

        return $this->getApi()->request($this->getApi()->sprintf('/orgs/:org/members?:args', $org,
            http_build_query(['filter' => $filter, 'role' => $role])));
    }

function handleRequest(providedUrl, req, res) {
  let $
  // Check for the filter parameter
  const filter = req.params.filter || req.query.filter || req.query.search || ''

  // Add name filtering if it is requested
  let url = providedUrl || ''
  if (filter !== '') {
    url += `&Nafn=${filter}`
  }

  request.get({
    headers: { 'User-Agent': h.browser() },
    url,
  }, (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({ error: 'www.island.is refuses to respond or give back data' })
    }

    try {
      $ = cheerio.load(body)
    } catch (exc) {
      return res.status(500).json({ error: 'Could not parse body' })
    }

    const obj = { results: [] }

    // Clear data regarding the acceptance date of the name (not needed)
    $('.dir li i').each(() => {
      $(this).remove()
    })

    // Loop through all the names in the list and add them to our array
    $('.dir li').each(() => {
      const name = $(this).text()
      obj.results.push(name.trim())
    })

    // Return the results as JSON and cache for 24 hours
    return res.cache(86400).json(obj)
  })
}

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


Question:
// AddStatusListener allows the submission of a StatusListener implementation
// whose OnChange() function will be called whenever the node is notified of any
// change in the status of a cluster member.

func AddStatusListener(listener StatusListener) {
	statusListeners.Lock()
	statusListeners.s = append(statusListeners.s, listener)
	statusListeners.Unlock()
}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question: Callback for "order-get" command

public function cmdGetOrder()
    {
        $result = $this->getListOrder();
        $this->outputFormat($result);
        $this->outputFormatTableOrder($result);
        $this->output();
    }

@Override
	public com.liferay.commerce.model.CommerceOrder fetchCommerceOrderByUuidAndGroupId(
		String uuid, long groupId) {
		return _commerceOrderLocalService.fetchCommerceOrderByUuidAndGroupId(uuid,
			groupId);
	}

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


Question:
Clean up node, edge table for the deleted nodes with passed ids.

@param array $ids Deleted node ids

public function cleanupNodesWithIds($ids)
    {
        $ids = array_merge($this->getRelatedNodeIds($ids), $ids);

        if (!empty($ids)) {
            $repositories = $this->getNodeRepositories($ids);

            //delete all the nodes
            $this->getService('repos:base.node')->destroy($ids);

            //set the creator,updator,authors to null
            $in = '('.implode(',', $ids).')';
            $query[] = "last_comment_id = IF(last_comment_id IN $in, NULL, last_comment_id)";
            $query[] = "created_by = IF(created_by IN $in, NULL, created_by)";
            $query[] = "modified_by = IF(modified_by IN $in, NULL, modified_by)";
            $query[] = "last_comment_by = IF(last_comment_by IN $in, NULL, last_comment_by)";
            $query = implode(', ', $query);
            $where = $this->getService('repos:base.node')
                        ->getQuery()
                        ->where("last_comment_by IN $in OR created_by IN $in OR modified_by IN $in OR last_comment_by IN $in");

            $this->getService('repos:base.node')->update($query, $where);

            //cleanup all the relationship of every deleted node
            $query = $this->getService('repos:base.edge')
                ->getQuery()
                ->where('nodeA.id', 'IN', $ids)
                ->where('nodeB.id', 'IN', $ids, 'OR');

            $this->getService('repos:base.edge')->destroy($query);

            //now lets the repositories know so they can
            //handle the cleanup
            foreach ($repositories as $repository) {
                $context = $repository->getCommandContext();
                $context->node_ids = $ids;
                $repository->getCommandChain()->run('after.deletenodes', $context);
            }
        }
    }

def adapt_step_table!(parsed_step_table)
      # Saving off the original data
      parsed_step_table['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_step_table))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_step_table['cuke_modeler_parsing_data'][:rows] = nil

      parsed_step_table['rows'] = []
      parsed_step_table[:rows].each do |row|
        adapt_table_row!(row)
      end
      parsed_step_table['rows'].concat(parsed_step_table.delete(:rows))
      parsed_step_table['line'] = parsed_step_table.delete(:location)[:line]
    end

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


Question:
this code creates the debugging plots to understand
        the behavior of the hypothetical building model

def _debug_output(self):

        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        c = self.config

        df_d = self.dev_d
        keys = df_d.keys()
        keys = sorted(keys)
        for key in keys:
            logger.debug("\n" + str(key) + "\n")
            logger.debug(df_d[key])
        for form in self.config.forms:
            logger.debug("\n" + str(key) + "\n")
            logger.debug(self.get_ave_cost_sqft(form, "surface"))

        keys = c.forms.keys()
        keys = sorted(keys)
        cnt = 1
        share = None
        fig = plt.figure(figsize=(12, 3 * len(keys)))
        fig.suptitle('Profitable rents by use', fontsize=40)
        for name in keys:
            sumdf = None
            for parking_config in c.parking_configs:
                df = df_d[(name, parking_config)]
                if sumdf is None:
                    sumdf = pd.DataFrame(df['far'])
                sumdf[parking_config] = df['ave_cost_sqft']
            far = sumdf['far']
            del sumdf['far']

            if share is None:
                share = plt.subplot(len(keys) / 2, 2, cnt)
            else:
                plt.subplot(len(keys) / 2, 2, cnt, sharex=share, sharey=share)

            handles = plt.plot(far, sumdf)
            plt.ylabel('even_rent')
            plt.xlabel('FAR')
            plt.title('Rents for use type %s' % name)
            plt.legend(
                handles, c.parking_configs, loc='lower right',
                title='Parking type')
            cnt += 1
        plt.savefig('even_rents.png', bbox_inches=0)

def display(self, dset_id: str):

        # update result
        self.skd[dset_id].compute()
        # build layout
        self.build_layout(dset_id=dset_id)
        # display widgets
        display(self._('dashboard'))
        # display data table and chart
        self._display_result(dset_id=dset_id)

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


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

public String convertObjectClassificationStrucFlgsToString(EDataType eDataType, Object instanceValue) {
		return instanceValue == null ? null : instanceValue.toString();
	}

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: private wrapper around C{self.db.state.getState}

def _getState(self, name, default=None):
        ""
        d = self.getObjectId()

        @d.addCallback
        def get(objectid):
            return self.db.state.getState(objectid, name, default)
        return d

func (f *Facade) AddHostPrivate(ctx datastore.Context, entity *host.Host) ([]byte, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.AddHostPrivate"))
	alog := f.auditLogger.Message(ctx, "Adding Host with common key").Action(audit.Add).Entity(entity)
	glog.V(2).Infof("Facade.AddHostPrivate: %v", entity)
	if err := f.DFSLock(ctx).LockWithTimeout("add host", userLockTimeout); err != nil {
		glog.Warningf("Cannot add host: %s", err)
		return nil, alog.Error(err)
	}
	defer f.DFSLock(ctx).Unlock()
	key, err := f.addHostPrivate(ctx, entity)
	return key, alog.Error(err)
}

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


Question: // SetVersionLabel sets the VersionLabel field's value.

func (s *CreateApplicationVersionInput) SetVersionLabel(v string) *CreateApplicationVersionInput {
	s.VersionLabel = &v
	return s
}

func DefaultUpdaterLabel(runMode libkb.RunMode) string {
	label := AppUpdaterLabel.String()
	if runMode != libkb.ProductionRunMode {
		label = label + "." + string(runMode)
	}
	return label
}

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


Question:
Adds an {@link EvictionAdvisor} to the returned builder.

@param evictionAdvisor the eviction advisor to use
@return a new builder with the added eviction advisor

public UserManagedCacheBuilder<K, V, T> withEvictionAdvisor(EvictionAdvisor<K, V> evictionAdvisor) {
    if (evictionAdvisor == null) {
      throw new NullPointerException("Null eviction advisor");
    }
    UserManagedCacheBuilder<K, V, T> otherBuilder = new UserManagedCacheBuilder<>(this);
    otherBuilder.evictionAdvisor = evictionAdvisor;
    return otherBuilder;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return $userCreateStruct;
    }

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


Question:
Index comment tags position in source HTML

@param  stdClass $o
@return stdClass $o

protected function _index_comments_html($o)
    {
        if (!isset($o->l)) {
            $o->l = strlen($o->h);
        }

        $o->tg = self::$_ar_;
        $i     = $o->i;
        while ($i < $o->l) {
            $i = strpos($o->h, '<!--', $i);
            if (false === $i) {
                break;
            }

            $p = $i;
            $i += 4;
            $i = strpos($o->h, '-->', $i);
            if (false === $i) {
                $i = $o->l;
            } else {
                $i += 3;
            }

            $o->tg[$p] = $i;
        }
        return $o;
    }

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question: // NewGroupMembersAddArg returns a new GroupMembersAddArg instance

func NewGroupMembersAddArg(Group *GroupSelector, Members []*MemberAccess) *GroupMembersAddArg {
	s := new(GroupMembersAddArg)
	s.Group = Group
	s.Members = Members
	s.ReturnMembers = true
	return s
}

def onTagAdd(self, name, func):
        '''

        '''
        # TODO allow name wild cards
        if '*' in name:
            self.ontagaddglobs.add(name, func)
        else:
            self.ontagadds[name].append(func)

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


Question: Helper function to sort scenes based on their index and view key.

function compareScenes(one, two) {
  if (one.index > two.index) {
    return 1;
  }
  if (one.index < two.index) {
    return -1;
  }

  return compareKey(one.key, two.key);
}

def action_scope(self, action_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]:
        '''
        '''
        return dict(zip(self.rddl.domain.action_fluent_ordering, action_fluents))

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


Question:
// NewSnapFactory returns a new object that can read from and write to encrypted
// snapshots on disk

func NewSnapFactory(encrypter encryption.Encrypter, decrypter encryption.Decrypter) SnapFactory {
	return snapCryptor{
		encrypter: encrypter,
		decrypter: decrypter,
	}
}

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question: // SetGroupName sets the GroupName field's value.

func (s *GroupDetail) SetGroupName(v string) *GroupDetail {
	s.GroupName = &v
	return s
}

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

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

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


Question:
Builds a query from a SQLDelete expression

@param SQLDelete $query The expression object to build from
@param array $parameters Out parameter for the resulting query parameters
@return string Completed SQL string

protected function buildDeleteQuery(SQLDelete $query, array &$parameters)
    {
        $sql  = $this->buildDeleteFragment($query, $parameters);
        $sql .= $this->buildFromFragment($query, $parameters);
        $sql .= $this->buildWhereFragment($query, $parameters);
        return $sql;
    }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: Completes this node, moving the parent node to its next child.

public void complete() {
    // we have to traverse up to our parent, so be careful about locking.
    Progress myParent;
    synchronized(this) {
      progress = 1.0f;
      myParent = parent;
    }
    if (myParent != null) {
      // this will synchronize on the parent, so we make sure we release
      // our lock before getting the parent's, since we're traversing
      // against the normal traversal direction used by get() or toString().
      // We don't need transactional semantics, so we're OK doing this.
      myParent.startNextPhase();
    }
  }

private static String adjustData(String data, ClassNode type, DelegationMetadata dmd) {
        StringBuilder path = new StringBuilder();
        int i = 0;
        String[] propertyPath = data.split("\\.");
        while (dmd != null) {
            int strategy = dmd.getStrategy();
            ClassNode delegate = dmd.getType();
            dmd = dmd.getParent();
            switch (strategy) {
                case Closure.DELEGATE_FIRST:
                    if (!delegate.isDerivedFrom(CLOSURE_TYPE) && !delegate.isDerivedFrom(type)) {
                        path.append("owner"); // must be non-delegate case
                    } else {
                        path.append("delegate");
                    }
                    break;
                default:
                    if (i >= propertyPath.length) return data;
                    path.append(propertyPath[i]);
            }
            if (type.equals(delegate)) break;
            i++;
            if (dmd != null) path.append('.');
        }
        String result = path.toString();
        if (!result.isEmpty()) {
            return result;
        }
        return data;
    }

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


Question:
Semaphore requires a numeric value as the key

@param $identifier
@return int

protected function _stringToSemKey($identifier)
    {
        $md5 = md5($identifier);
        $key = 0;
        for ($i = 0; $i < 32; $i++) {
            $key += ord($md5{$i}) * $i;
        }
        return $key;
    }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question: // SetPartner sets the Partner field's value.

func (s *ListSigningPlatformsInput) SetPartner(v string) *ListSigningPlatformsInput {
	s.Partner = &v
	return s
}

protected function insertAndSetId(Builder $query, $attributes)
    {
        $id = $query->insertGetId($attributes, $keyName = $this->getKeyName());

        $this->setAttribute($keyName, $id);
    }

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


Question:
Register the service provider.

@return void

public function register()
    {
        $app    = parent::register();

        $app->singleton('fs', Filesystem::class);
        $this->registerStubs();
        $this->registerHelpers();
    }

protected function queueRecallerCookie(AuthenticatableContract $user)
    {
        $this->getCookieJar()->queue($this->createRecaller(
            $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword()
        ));
    }

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


Question:
// URLFor returns a URL which may be used to retrieve the content stored at the given path.
// May return an UnsupportedMethodErr in certain StorageDriver implementations.

func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) {
	methodString := "GET"
	method, ok := options["method"]
	if ok {
		methodString, ok = method.(string)
		if !ok || (methodString != "GET") {
			return "", storagedriver.ErrUnsupportedMethod{}
		}
	}

	expiresTime := time.Now().Add(20 * time.Minute)

	expires, ok := options["expiry"]
	if ok {
		et, ok := expires.(time.Time)
		if ok {
			expiresTime = et
		}
	}
	logrus.Infof("methodString: %s, expiresTime: %v", methodString, expiresTime)
	signedURL := d.Bucket.SignedURLWithMethod(methodString, d.ossPath(path), expiresTime, nil, nil)
	logrus.Infof("signed URL: %s", signedURL)
	return signedURL, nil
}

public static void printMountInfo(Map<String, MountPointInfo> mountTable) {
    for (Map.Entry<String, MountPointInfo> entry : mountTable.entrySet()) {
      String mMountPoint = entry.getKey();
      MountPointInfo mountPointInfo = entry.getValue();

      long capacityBytes = mountPointInfo.getUfsCapacityBytes();
      long usedBytes = mountPointInfo.getUfsUsedBytes();

      String usedPercentageInfo = "";
      if (capacityBytes > 0) {
        int usedPercentage = (int) (100L * usedBytes / capacityBytes);
        usedPercentageInfo = String.format("(%s%%)", usedPercentage);
      }

      String leftAlignFormat = getAlignFormat(mountTable);

      System.out.format(leftAlignFormat, mountPointInfo.getUfsUri(), mMountPoint,
          mountPointInfo.getUfsType(), FormatUtils.getSizeFromBytes(capacityBytes),
          FormatUtils.getSizeFromBytes(usedBytes) + usedPercentageInfo,
          mountPointInfo.getReadOnly() ? "" : "not ",
          mountPointInfo.getShared() ? "" : "not ");
      System.out.println("properties=" + mountPointInfo.getProperties() + ")");
    }
  }

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


Question: Poll vmadm for changes

def beacon(config):
    '''

    '''
    ret = []

    # NOTE: lookup current images
    current_vms = __salt__['vmadm.list'](
        keyed=True,
        order='uuid,state,alias,hostname,dns_domain',
    )

    # NOTE: apply configuration
    if VMADM_STATE['first_run']:
        log.info('Applying configuration for vmadm beacon')

        _config = {}
        list(map(_config.update, config))

        if 'startup_create_event' not in _config or not _config['startup_create_event']:
            VMADM_STATE['vms'] = current_vms

    # NOTE: create events
    for uuid in current_vms:
        event = {}
        if uuid not in VMADM_STATE['vms']:
            event['tag'] = "created/{}".format(uuid)
            for label in current_vms[uuid]:
                if label == 'state':
                    continue
                event[label] = current_vms[uuid][label]

        if event:
            ret.append(event)

    # NOTE: deleted events
    for uuid in VMADM_STATE['vms']:
        event = {}
        if uuid not in current_vms:
            event['tag'] = "deleted/{}".format(uuid)
            for label in VMADM_STATE['vms'][uuid]:
                if label == 'state':
                    continue
                event[label] = VMADM_STATE['vms'][uuid][label]

        if event:
            ret.append(event)

    # NOTE: state change events
    for uuid in current_vms:
        event = {}
        if VMADM_STATE['first_run'] or \
           uuid not in VMADM_STATE['vms'] or \
           current_vms[uuid].get('state', 'unknown') != VMADM_STATE['vms'][uuid].get('state', 'unknown'):
            event['tag'] = "{}/{}".format(current_vms[uuid].get('state', 'unknown'), uuid)
            for label in current_vms[uuid]:
                if label == 'state':
                    continue
                event[label] = current_vms[uuid][label]

        if event:
            ret.append(event)

    # NOTE: update stored state
    VMADM_STATE['vms'] = current_vms

    # NOTE: disable first_run
    if VMADM_STATE['first_run']:
        VMADM_STATE['first_run'] = False

    return ret

public void updateMapping(String virtual, String physical, String archive, String primary, short inspect, boolean toplevel, int listenerMode, int listenerType,
	    boolean readOnly) throws ExpressionException, SecurityException {
	checkWriteAccess();
	_updateMapping(virtual, physical, archive, primary, inspect, toplevel, listenerMode, listenerType, readOnly);
    }

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


Question:
// GetPlugins returns the loaded and available plugins through an HTTP GET request.
// By specifying the details flag to tweak output info. An error returns if it failed.

func (c *Client) GetPlugins(details bool) *GetPluginsResult {
	r := &GetPluginsResult{}

	var path string
	if details {
		path = "/plugins?details"
	} else {
		path = "/plugins"
	}

	resp, err := c.do("GET", path, ContentTypeJSON)
	if err != nil {
		r.Err = err
		return r
	}

	switch resp.Meta.Type {
	// TODO change this to concrete const type when Joel adds it
	case rbody.PluginListType:
		// Success
		b := resp.Body.(*rbody.PluginList)
		r.LoadedPlugins = convertLoadedPlugins(b.LoadedPlugins)
		r.AvailablePlugins = convertAvailablePlugins(b.AvailablePlugins)
		return r
	case rbody.ErrorType:
		r.Err = resp.Body.(*rbody.Error)
	default:
		r.Err = ErrAPIResponseMetaType
	}
	return r
}

def list_streams(self, types=[], inactive=False):
        '''  '''
        req_hook = 'pod/v1/streams/list'
        json_query = {
                       "streamTypes": types,
                       "includeInactiveStreams": inactive
                     }
        req_args = json.dumps(json_query)
        status_code, response = self.__rest__.POST_query(req_hook, req_args)
        self.logger.debug('%s: %s' % (status_code, response))
        return status_code, response

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


Question:
Push a single job onto the queue.

@param string $callable    a job callable
@param array  $args        an array of data to set for the job
@param array  $options     an array of options for publishing the job

@return boolean the result of the push

public function push($callable, $args = [], $options = [])
    {
        $queue = $this->engine->setting($options, 'queue');
        $item = [
            'queue' => $queue,
            'class' => $callable,
            'args'  => [$args],
            'id'    => md5(uniqid('', true)),
            'queue_time' => microtime(true),
        ];
        $success = $this->engine->push($item, $options);

        unset($item['id']);
        if ($success) {
            $item['id'] = $this->engine->lastJobId();
        }

        $item['args'] = $args;
        $this->dispatchEvent('Queue.afterEnqueue', [
            'item' => $item,
            'success' => $success,
        ]);

        return $success;
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end

      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end

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


Question:
Retrieve a list of the collection URLs for all collections
        hosted on the server.

        :rtype: List
        :returns: a List of tuples of (name, url) for each collection

def get_collections(self):

        result = self.api_request('/catalog')

        # get the collection name from the url
        return [(os.path.split(x)[1], x) for x in result['collections']]

def get_points(self, measurement=None, tags=None):

        # Raise error if measurement is not str or bytes
        if not isinstance(measurement,
                          (bytes, type(b''.decode()), type(None))):
            raise TypeError('measurement must be an str or None')

        for series in self._get_series():
            series_name = series.get('measurement',
                                     series.get('name', 'results'))
            if series_name is None:
                # this is a "system" query or a query which
                # doesn't return a name attribute.
                # like 'show retention policies' ..
                if tags is None:
                    for item in self._get_points_for_series(series):
                        yield item

            elif measurement in (None, series_name):
                # by default if no tags was provided then
                # we will matches every returned series
                series_tags = series.get('tags', {})
                for item in self._get_points_for_series(series):
                    if tags is None or \
                            self._tag_matches(item, tags) or \
                            self._tag_matches(series_tags, tags):
                        yield item

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


Question:
// New returns a new instance of Master from the given config.
// Certain config fields will be set to a default value if unset.
// Certain config fields must be specified, including:
//   KubeletClientConfig

func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*Master, error) {
	if reflect.DeepEqual(c.ExtraConfig.KubeletClientConfig, kubeletclient.KubeletClientConfig{}) {
		return nil, fmt.Errorf("Master.New() called with empty config.KubeletClientConfig")
	}

	s, err := c.GenericConfig.New("kube-apiserver", delegationTarget)
	if err != nil {
		return nil, err
	}

	if c.ExtraConfig.EnableLogsSupport {
		routes.Logs{}.Install(s.Handler.GoRestfulContainer)
	}

	m := &Master{
		GenericAPIServer: s,
	}

	// install legacy rest storage
	if c.ExtraConfig.APIResourceConfigSource.VersionEnabled(apiv1.SchemeGroupVersion) {
		legacyRESTStorageProvider := corerest.LegacyRESTStorageProvider{
			StorageFactory:              c.ExtraConfig.StorageFactory,
			ProxyTransport:              c.ExtraConfig.ProxyTransport,
			KubeletClientConfig:         c.ExtraConfig.KubeletClientConfig,
			EventTTL:                    c.ExtraConfig.EventTTL,
			ServiceIPRange:              c.ExtraConfig.ServiceIPRange,
			ServiceNodePortRange:        c.ExtraConfig.ServiceNodePortRange,
			LoopbackClientConfig:        c.GenericConfig.LoopbackClientConfig,
			ServiceAccountIssuer:        c.ExtraConfig.ServiceAccountIssuer,
			ServiceAccountMaxExpiration: c.ExtraConfig.ServiceAccountMaxExpiration,
			APIAudiences:                c.GenericConfig.Authentication.APIAudiences,
		}
		m.InstallLegacyAPI(&c, c.GenericConfig.RESTOptionsGetter, legacyRESTStorageProvider)
	}

	// The order here is preserved in discovery.
	// If resources with identical names exist in more than one of these groups (e.g. "deployments.apps"" and "deployments.extensions"),
	// the order of this list determines which group an unqualified resource name (e.g. "deployments") should prefer.
	// This priority order is used for local discovery, but it ends up aggregated in `k8s.io/kubernetes/cmd/kube-apiserver/app/aggregator.go
	// with specific priorities.
	// TODO: describe the priority all the way down in the RESTStorageProviders and plumb it back through the various discovery
	// handlers that we have.
	restStorageProviders := []RESTStorageProvider{
		auditregistrationrest.RESTStorageProvider{},
		authenticationrest.RESTStorageProvider{Authenticator: c.GenericConfig.Authentication.Authenticator, APIAudiences: c.GenericConfig.Authentication.APIAudiences},
		authorizationrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorization.Authorizer, RuleResolver: c.GenericConfig.RuleResolver},
		autoscalingrest.RESTStorageProvider{},
		batchrest.RESTStorageProvider{},
		certificatesrest.RESTStorageProvider{},
		coordinationrest.RESTStorageProvider{},
		extensionsrest.RESTStorageProvider{},
		networkingrest.RESTStorageProvider{},
		noderest.RESTStorageProvider{},
		policyrest.RESTStorageProvider{},
		rbacrest.RESTStorageProvider{Authorizer: c.GenericConfig.Authorization.Authorizer},
		schedulingrest.RESTStorageProvider{},
		settingsrest.RESTStorageProvider{},
		storagerest.RESTStorageProvider{},
		// keep apps after extensions so legacy clients resolve the extensions versions of shared resource names.
		// See https://github.com/kubernetes/kubernetes/issues/42392
		appsrest.RESTStorageProvider{},
		admissionregistrationrest.RESTStorageProvider{},
		eventsrest.RESTStorageProvider{TTL: c.ExtraConfig.EventTTL},
	}
	m.InstallAPIs(c.ExtraConfig.APIResourceConfigSource, c.GenericConfig.RESTOptionsGetter, restStorageProviders...)

	if c.ExtraConfig.Tunneler != nil {
		m.installTunneler(c.ExtraConfig.Tunneler, corev1client.NewForConfigOrDie(c.GenericConfig.LoopbackClientConfig).Nodes())
	}

	m.GenericAPIServer.AddPostStartHookOrDie("ca-registration", c.ExtraConfig.ClientCARegistrationHook.PostStartHook)

	return m, nil
}

def create_node(**kwargs):
    '''

    '''
    name = kwargs['name']
    size = kwargs['size']
    image = kwargs['image']
    location = kwargs['location']
    networks = kwargs.get('networks')
    tag = kwargs.get('tag')
    locality = kwargs.get('locality')
    metadata = kwargs.get('metadata')
    firewall_enabled = kwargs.get('firewall_enabled')

    create_data = {
        'name': name,
        'package': size['name'],
        'image': image['name'],
    }
    if networks is not None:
        create_data['networks'] = networks

    if locality is not None:
        create_data['locality'] = locality

    if metadata is not None:
        for key, value in six.iteritems(metadata):
            create_data['metadata.{0}'.format(key)] = value

    if tag is not None:
        for key, value in six.iteritems(tag):
            create_data['tag.{0}'.format(key)] = value

    if firewall_enabled is not None:
        create_data['firewall_enabled'] = firewall_enabled

    data = salt.utils.json.dumps(create_data)

    ret = query(command='my/machines', data=data, method='POST',
                location=location)
    if ret[0] in VALID_RESPONSE_CODES:
        return ret[1]
    else:
        log.error('Failed to create node %s: %s', name, ret[1])

    return {}

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


Question:
Adds a new element to the HashedArrayTree.

@param elem The element to add.
@return true

@Override
    public boolean add(T elem) {
        /* First, check if we're completely out of space.  If so, do a resize
         * to ensure we do indeed have room.
         */
        if (size() == mArrays.length * mArrays.length)
            grow();

        /* Compute the (arr, index) pair for the next position.  The next
         * position is at the location indicated by size(), but we know that
         * space exists from the previous call.
         */
        final int offset = computeOffset(size());
        final int index = computeIndex(size());

        /* Check if an array exists here.  If not, make one up. */
        if (mArrays[offset] == null)
            mArrays[offset] = (T[]) new Object[mArrays.length];

        /* Write the element to its location. */
        mArrays[offset][index] = elem;

        /* Update the element count. */
        ++mSize;

        /* Per the Collections contract, return true to signal a successful
         * add.
         */
        return true;
    }

public static function section($name, $args, $child) {
		//Convenient under the hood change to
		//make things easier
		$args["sectionPath"] = $args["path"];
		unset($args["path"]);

		//Add to sections
		Router::$sections[] = [$name, $args, $child, Router::$context];
	}

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