Question:
Sets the data associated to the layout.
No validation checks are performed at this step.

@param mixed $data

@return \BackBee\Site\Layout

public function setData($data)
    {
        if (true === is_object($data)) {
            return $this->setDataObject($data);
        }

        $this->_picpath = null;
        $this->_isValid = null;
        $this->_domdocument = null;
        $this->_zones = null;

        $this->_data = $data;

        return $this;
    }

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

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


Question:
Parse the actors out of a movie hash.

 @param [Hash] hash The movie has to extract the actors out of.

 @return [Array<BadFruit::Actor>] An array of BadFruit::Actor objects.

def parse_actors_array(hash)
      actorsArray = Array.new
       hash["cast"].each do |actor|
         actorsArray.push(Actor.new(actor))
       end
       return actorsArray
    end

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question:
Creates a copy of an array with another array prepended to it.
@param prepend The array to prepend
@param tail The original array
@param <T> The base type of the array
@return The extended array

public static <T> T[] offerArray(T[] prepend, T[] tail) {
        if (prepend == null || prepend.length < 1) {
            return tail;
        } else if (tail == null || tail.length < 1) {
            return prepend;
        } else {
            T[] result = newArrayInstance(tail, prepend.length + tail.length);
            System.arraycopy(prepend, 0, result, 0, prepend.length);
            System.arraycopy(tail, 0, result, prepend.length, tail.length);
            return result;
        }
    }

func interpolationFuncDistinct() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeList},
		ReturnType:   ast.TypeList,
		Variadic:     true,
		VariadicType: ast.TypeList,
		Callback: func(args []interface{}) (interface{}, error) {
			var list []string

			if len(args) != 1 {
				return nil, fmt.Errorf("accepts only one argument.")
			}

			if argument, ok := args[0].([]ast.Variable); ok {
				for _, element := range argument {
					if element.Type != ast.TypeString {
						return nil, fmt.Errorf(
							"only works for flat lists, this list contains elements of %s",
							element.Type.Printable())
					}
					list = appendIfMissing(list, element.Value.(string))
				}
			}

			return stringSliceToVariableValue(list), nil
		},
	}
}

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


Question:
Render an exception into an HTTP response.

@param  \Illuminate\Http\Request  $request
@param  \Exception  $exception
@return \Illuminate\Http\Response

public function render($request, Exception $exception)
    {
        foreach ($this->getHandlers() as $handler) {
            if ($return = $handler->render($request, $exception)) {
                return $return;
            }
        }

        # Search throught all Handler defined in Package
        return parent::render($request, $exception);
    }

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

        return;
    }

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


Question: // NewTxSimulator implements method in interface `txmgmt.TxMgr`

func (txmgr *LockBasedTxMgr) NewTxSimulator(txid string) (ledger.TxSimulator, error) {
	logger.Debugf("constructing new tx simulator")
	s, err := newLockBasedTxSimulator(txmgr, txid)
	if err != nil {
		return nil, err
	}
	txmgr.commitRWLock.RLock()
	return s, nil
}

public function send(MessageInterface $message)
    {
        if (!$this->supports($message->getTargetOS())) {
            throw new \RuntimeException("OS type {$message->getTargetOS()} not supported");
        }

        return $this->handlers[$message->getTargetOS()]->send($message);
    }

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


Question:
serial no with date format, 生成日期格式的流水号，最少位数为20
@param  int    $length
@param  string $prefix
@return string

static public function serial($length=20, $prefix=null)
    {
        if ($length < 20) $length = 20;
        $mtime = floor(microtime(true) * 1000);
        $value = date('YmdHis') . substr($mtime, strlen($mtime)-3); // 14bit + 3bit micortime
        $value .= static::randomNumber($length-17);
        if ($prefix) $value = $prefix . $value;

        return $value;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question: Deletes an importJob.

public boolean deleteImportJob(Integer importJobId) throws URISyntaxException, HttpException {

        LOG.debug("Deleting the import job " + importJobId);

        Response httpResponse = HttpUtil.delete(
            this.addEndPoint(importJobId.toString()),
            this.username,
            this.password);

        boolean success = httpResponse.getStatusCode().equals(HttpStatus.NO_CONTENT);

        if (success) {
            LOG.debug("Successfully deleted the import job " + importJobId);
        } else {
            LOG.error("Unknown error occured while deleting the import job " + importJobId);
        }

        return success;
    }

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

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


Question:
Configures this session with a custom class loader that will be used when unserializing
classes from the network.

public void setClassLoader (ClassLoader loader)
    {
        _loader = loader;
        PresentsConnection conn = getConnection();
        if (conn != null) {
            conn.setClassLoader(loader);
        }
    }

def serialize_hook(instance):

    if getattr(instance, 'serialize_hook', None) and callable(instance.serialize_hook):
        return instance.serialize_hook(hook=instance)
    if getattr(settings, 'HOOK_SERIALIZER', None):
        serializer = get_module(settings.HOOK_SERIALIZER)
        return serializer(instance, hook=instance)
    # if no user defined serializers, fallback to the django builtin!
    return {
        'hook': instance.dict(),
        'data': serializers.serialize('python', [instance])[0]
    }

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


Question:
Add lineItem

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2012-04-05

@param HarvestCloud\CoreBundle\Entity\OrderLineItem $lineItems

public function addLineItem(\HarvestCloud\CoreBundle\Entity\OrderLineItem $lineItem)
    {
        $this->lineItems[] = $lineItem;

        $lineItem->setOrder($this);
    }

protected function applyHttpAttributes($http, $postData)
    {
        $postData['protocol_version'] = '1.1';
        $postData['client'] = 'october';

        $postData['server'] = base64_encode(serialize([
            'php'   => PHP_VERSION,
            'url'   => Url::to('/'),
            'since' => PluginVersion::orderBy('created_at')->value('created_at')
        ]));

        if ($projectId = Parameter::get('system::project.id')) {
            $postData['project'] = $projectId;
        }

        if (Config::get('cms.edgeUpdates', false)) {
            $postData['edge'] = 1;
        }

        if ($this->key && $this->secret) {
            $postData['nonce'] = $this->createNonce();
            $http->header('Rest-Key', $this->key);
            $http->header('Rest-Sign', $this->createSignature($postData, $this->secret));
        }

        if ($credentials = Config::get('cms.updateAuth')) {
            $http->auth($credentials);
        }

        $http->noRedirect();
        $http->data($postData);
    }

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


Question:
Wraps the given {@link RepresentationModel} into a {@link HeaderLinksResponseEntity}. Will default the status code
to {@link HttpStatus#OK}.

@param entity must not be {@literal null}.
@return

public static <S extends RepresentationModel<?>> HeaderLinksResponseEntity<S> wrap(S entity) {

		Assert.notNull(entity, "ResourceSupport must not be null!");

		return new HeaderLinksResponseEntity<>(ResponseEntity.ok(entity));
	}

func (c oauthClient) Root() (wl.Root, error) {
	url := fmt.Sprintf(
		"%s/root",
		c.apiURL,
	)

	req, err := c.newGetRequest(url)
	if err != nil {
		return wl.Root{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Root{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.Root{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	root := wl.Root{}
	err = json.NewDecoder(resp.Body).Decode(&root)
	if err != nil {
		return root, err
	}
	return root, nil
}

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


Question: Use this API to kill aaasession.

public static base_response kill(nitro_service client, aaasession resource) throws Exception {
		aaasession killresource = new aaasession();
		killresource.username = resource.username;
		killresource.groupname = resource.groupname;
		killresource.iip = resource.iip;
		killresource.netmask = resource.netmask;
		killresource.all = resource.all;
		return killresource.perform_operation(client,"kill");
	}

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

        if 'timeout' not in kwargs:
            kwargs['timeout'] = self.timeout

        req = self.session.delete(*args, **kwargs)
        return req

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


Question:
设置授权方的选项信息
@param $authorizerAppId
@param $key
@param $value
@return \EasyWeChat\Support\Collection

public function setAuthorizerSetting($authorizerAppId, $key, $value)
    {
        $body = $this->parseJSON('json', [
            self::API_SET_AUTHORIZER_SETTING,
            [
                'component_appid'  => $this->getAccessToken()->getAppId(),
                'authorizer_appid' => $authorizerAppId,
                'option_name'      => $key,
                'option_value'     => $value
            ]
        ]);

        return $body;
    }

func (c *Chat) UnmarshalJSON(data []byte) error {
	s := &struct {
		ID                          int        `json:"id"`
		Type                        string     `json:"type"`
		Title                       string     `json:"title"`
		Username                    string     `json:"username"`
		FirstName                   string     `json:"first_name"`
		LastName                    string     `json:"last_name"`
		Photo                       *ChatPhoto `json:"photo"`
		Description                 string     `json:"description"`
		InviteLink                  string     `json:"invite_link"`
		PinnedMessage               *Message   `json:"pinned_message"`
		StickerSetName              string     `json:"sticker_set_name"`
		AllMembersAreAdministrators bool       `json:"all_members_are_administrators"`
		CanSetStickerSet            bool       `json:"can_set_sticker_set"`
	}{}
	err := json.Unmarshal(data, s)
	if err != nil {
		return err
	}
	*c = Chat{
		ID:                          fmt.Sprint(s.ID),
		Type:                        s.Type,
		Title:                       s.Title,
		Username:                    s.Username,
		FirstName:                   s.FirstName,
		LastName:                    s.LastName,
		Photo:                       s.Photo,
		Description:                 s.Description,
		InviteLink:                  s.InviteLink,
		PinnedMessage:               s.PinnedMessage,
		StickerSetName:              s.StickerSetName,
		AllMembersAreAdministrators: s.AllMembersAreAdministrators,
		CanSetStickerSet:            s.CanSetStickerSet,
	}
	return nil
}

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


Question: // constructInnerTableScan is specially used to construct the inner plan for PhysicalIndexJoin.

func (p *LogicalJoin) constructInnerTableScan(ds *DataSource, pk *expression.Column, outerJoinKeys []*expression.Column, us *LogicalUnionScan) PhysicalPlan {
	ranges := ranger.FullIntRange(mysql.HasUnsignedFlag(pk.RetType.Flag))
	ts := PhysicalTableScan{
		Table:           ds.tableInfo,
		Columns:         ds.Columns,
		TableAsName:     ds.TableAsName,
		DBName:          ds.DBName,
		filterCondition: ds.pushedDownConds,
		Ranges:          ranges,
		rangeDecidedBy:  outerJoinKeys,
	}.Init(ds.ctx)
	ts.SetSchema(ds.schema)

	ts.stats = property.NewSimpleStats(1)
	ts.stats.StatsVersion = ds.statisticTable.Version
	if ds.statisticTable.Pseudo {
		ts.stats.StatsVersion = statistics.PseudoVersion
	}

	copTask := &copTask{
		tablePlan:         ts,
		indexPlanFinished: true,
	}
	selStats := ts.stats.Scale(selectionFactor)
	ts.addPushedDownSelection(copTask, selStats)
	t := finishCopTask(ds.ctx, copTask)
	reader := t.plan()
	return p.constructInnerUnionScan(us, reader)
}

public function up()
    {
        Schema::table('search_texts', function (Blueprint $table) {
            $table->text('meta')->nullable();
        });

        DB::statement('CREATE FULLTEXT INDEX search_texts_meta on search_texts(meta)');
        DB::statement('ALTER TABLE search_texts drop index search_texts_all');
        DB::statement('CREATE FULLTEXT INDEX search_texts_all on search_texts(title, standfirst, text, meta)');
    }

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


Question:
Sprawdza, czy plik spełnia warunki filtrowania
@param \Mmi\Http\RequestFile $requestFile
@return boolean

private function _filterFile(\Mmi\Http\RequestFile $requestFile)
    {
        if (empty($this->_filters)) {
            return true;
        }
        if (!isset($this->_filters['mime_types']) || empty($this->_filters['mime_types'])) {
            return true;
        }
        $allowedTypes = $allowedExts = [];
        foreach ($this->_filters['mime_types'] as $mt) {
            if (array_key_exists('mime', $mt)) {
                $allowedTypes[] = strtolower($mt['mime']);
            } elseif (array_key_exists('extensions', $mt)) {
                $allowedExts = array_merge($allowedExts, explode(",", strtolower(preg_replace('/ \s/', '', $mt['extensions']))));
            }
        }
        //sprawdzamy typy mime
        if (in_array(strtolower($requestFile->type), $allowedTypes)) {
            return true;
        }
        //sprawdzamy rozszerzenie
        if (strrpos($this->_fileName, '.') > 0) {
            $ext = strtolower(substr($this->_fileName, strrpos($this->_fileName, '.') + 1));
            if (in_array($ext, $allowedExts)) {
                return true;
            }
        }
        return false;
    }

public function getWaiting(TemplateInterface $template, MediaType $mediaType, $createOnDemand = true)
    {
        $filename = $this->worker->getWaitingFilename($template, $mediaType);

        if (file_exists($filename)) {
            return $filename;
        }

        if (!$createOnDemand) {
            return null;
        }

        $this->worker->write($mediaType, $template);

        return $filename;
    }

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


Question:
Toggle full screen.

@param frame
the frame

public static void toggleFullScreen(@NonNull JFrame frame)
	{
		GraphicsDevice device = frame.getGraphicsConfiguration().getDevice();
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		if (frame.equals(device.getFullScreenWindow()))
		{
			device.setFullScreenWindow(null);
		}
		else
		{
			frame.setVisible(true);
			device.setFullScreenWindow(frame);
		}
	}

def remove_pane(self, pane):

        assert isinstance(pane, Pane)

        for w in self.windows:
            w.remove_pane(pane)

            # No panes left in this window?
            if not w.has_panes:
                # Focus next.
                for app, active_w in self._active_window_for_cli.items():
                    if w == active_w:
                        with set_app(app):
                            self.focus_next_window()

                self.windows.remove(w)

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


Question: Check if SlackBuild archive.tar.gz and sources exist

def files_exist(self):

        if not os.path.isfile(self.path + self.script):
            print("\nslpkg: Error: SlackBuild archive.tar.gz not found\n")
            raise SystemExit()
        for src in self.sources:
            if not os.path.isfile(self.path + src):
                print("\nslpkg: Error: Source file '{0}' not found\n".format(
                    src))
                raise SystemExit()

def setup_zk
      unless @zk
        @zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}")
        @zk.register(manual_failover_path) do |event|
          handle_manual_failover_update(event)
        end
        @zk.on_connected { @zk.stat(manual_failover_path, :watch => true) }
      end

      create_path(@root_znode)
      create_path(current_state_root)
      @zk.stat(manual_failover_path, :watch => true)
    end

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


Question:
// Since we don't want useless single underlying type struct definitions everywhere we resolve
// any references to single underlying type objects.

func (d *Domain) resolveReference(prop PropSetter) bool {

	if prop.GetRef() == "" {
		fmt.Printf("ref was empty: %s\n", prop.GetGoType())
		return false
	}
	refName := ""
	// Local reference, add . between domain/ref type so we can look it up in our globalRefs
	if !strings.Contains(prop.GetRef(), ".") {
		refName = d.Domain + "." + prop.GetRef()
	} else {
		refName = prop.GetRef()
	}

	ref := globalRefs[refName]
	fmt.Printf("REF (%s): %#v\n", refName, ref)
	// base type
	if ref.IsBaseType {
		prop.SetGoType(ref.BaseType)
	} else {
		// we can have this type, reference another type, which is just a base type
		// so just set that here.
		if ref2ref, ok := globalRefs[ref.RefToRefName]; ok {
			if ref2ref.IsBaseType {
				prop.SetGoType(ref2ref.BaseType)
			}
		} else {
			prop.SetGoType(ref.ExternalGoName)
		}
		prop.SetIsRef(true)
	}
	// set the type as being an array of whatever type it references
	if ref.IsArrayRef {
		prop.SetIsTypeArray(true)
	}
	// add enum possible values to description
	if ref.EnumDescription != "" {
		prop.SetDescription(prop.GetDescription() + ref.EnumDescription)
	}

	if isPointerType(prop) {
		prop.SetPointerType(true)
	}
	return true
}

public function register()
    {
        $this->app->singleton('seotools.metatags', function($app) {
            return new SEOMeta(new Config($app['config']->get('seotools.meta', [])));
        });

        $this->app->singleton('seotools.opengraph', function($app) {
            return new OpenGraph($app['config']->get('seotools.opengraph', []));
        });

        $this->app->singleton('seotools.twitter', function($app) {
            return new TwitterCards($app['config']->get('seotools.twitter.defaults', []));
        });

        $this->app->singleton('seotools.json-ld', function($app) {
            return new JsonLd($app['config']->get('seotools.json-ld.defaults', []));
        });

        $this->app->singleton('seotools', function() {
            return new SEOTools();
        });

        $this->app->bind(Contracts\MetaTags::class, 'seotools.metatags');
        $this->app->bind(Contracts\OpenGraph::class, 'seotools.opengraph');
        $this->app->bind(Contracts\TwitterCards::class, 'seotools.twitter');
        $this->app->bind(Contracts\JsonLd::class, 'seotools.json-ld');
        $this->app->bind(Contracts\SEOTools::class, 'seotools');
    }

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


Question:
Update group
@param groupId group id to update
@param groupConfig group config
@return <tt>true</tt> if update was successful, <br/>
<tt>false</tt> otherwise

private boolean updateGroup(String groupId, GroupConfig groupConfig) {
        return client
            .updateGroup(
                groupId,
                converter.createUpdateGroupRequest(
                    groupConfig,
                    groupConfig.getParentGroup() != null ? idByRef(groupConfig.getParentGroup()) : null,
                    groupConfig.getCustomFields() == null || groupConfig.getCustomFields().size() == 0 ?
                        null : client.getCustomFields())
            );
    }

func (r *Relation) SetStatus(statusInfo status.StatusInfo) error {
	currentStatus, err := r.Status()
	if err != nil {
		return errors.Trace(err)
	}

	if currentStatus.Status != statusInfo.Status {
		validTransition := true
		switch statusInfo.Status {
		case status.Broken:
		case status.Suspending:
			validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Suspended
		case status.Joining:
			validTransition = currentStatus.Status != status.Broken && currentStatus.Status != status.Joined
		case status.Joined, status.Suspended:
			validTransition = currentStatus.Status != status.Broken
		case status.Error:
			if statusInfo.Message == "" {
				return errors.Errorf("cannot set status %q without info", statusInfo.Status)
			}
		default:
			return errors.NewNotValid(nil, fmt.Sprintf("cannot set invalid status %q", statusInfo.Status))
		}
		if !validTransition {
			return errors.NewNotValid(nil, fmt.Sprintf(
				"cannot set status %q when relation has status %q", statusInfo.Status, currentStatus.Status))
		}
	}
	return setStatus(r.st.db(), setStatusParams{
		badge:     "relation",
		globalKey: r.globalScope(),
		status:    statusInfo.Status,
		message:   statusInfo.Message,
		rawData:   statusInfo.Data,
		updated:   timeOrNow(statusInfo.Since, r.st.clock()),
	})
}

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


Question:
Move a node (model) below the parent and in between left and right

@param integer $id the primaryKey of the moved node
@return array
@throws HttpException

public function run($id)
    {
        /** @var ActiveRecord|TreeInterface $model */
        $model = $this->findModel($id);

        $form = new MoveNodeForm();

        $params = Yii::$app->getRequest()->getBodyParams();
        $form->load($params, '');

        if (!$form->validate()) {
            return $form;
        }

        try {
            if ($form->prev_id > 0) {
                $parentModel = $this->findModel($form->prev_id);
                if ($parentModel->isRoot()) {
                    return $model->appendTo($parentModel)->save();
                } else {
                    return $model->insertAfter($parentModel)->save();
                }
            } elseif ($form->next_id > 0) {
                $parentModel = $this->findModel($form->next_id);
                return $model->insertBefore($parentModel)->save();
            } elseif ($form->parent_id > 0) {
                $parentModel = $this->findModel($form->parent_id);
                return $model->appendTo($parentModel)->save();
            }
        } catch (Exception $ex) {
        }

        return false;
    }

private void parseFieldUpdate(String fieldName, UNode valueNode) {
        if (valueNode.isValue()) {
            addFieldValue(fieldName, valueNode.getValue());
        } else if (valueNode.childrenAreValues()) {
            parseFieldAdd(fieldName, valueNode);
        } else {
            for (UNode childNode : valueNode.getMemberList()) {
                if (childNode.isCollection() && childNode.getName().equals("add") && childNode.childrenAreValues()) {
                    // "add" for an MV field
                    parseFieldAdd(fieldName, childNode);
                } else if (childNode.isCollection() && childNode.getName().equals("remove") && childNode.childrenAreValues()) {
                    // "remove" for an MV field
                    parseFieldRemove(fieldName, childNode);
                } else {
                    parseFieldUpdate(childNode.getName(), childNode);
                }
            }
        }
    }

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


Question:
Bind all local and remote interfaces for a bean to all binding locations.

@param binder the namespace binder
@param bmd the bean
@param homeSet the remote and local home wrappers, or <tt>null</tt> if
deferred initialization bindings should be used

protected void bindInterfaces(NameSpaceBinder<?> binder, BeanMetaData bmd) throws Exception {
        HomeWrapperSet homeSet = null;
        EJSHome home = bmd.homeRecord.getHome();
        if (home != null) {
            homeSet = home.getWrapperSet();
        }

        int numRemoteInterfaces = countInterfaces(bmd, false);
        int numLocalInterfaces = countInterfaces(bmd, true);
        boolean singleGlobalInterface = (numRemoteInterfaces + numLocalInterfaces) == 1;

        bindInterfaces(binder, bmd, homeSet, false, numRemoteInterfaces, singleGlobalInterface);
        bindInterfaces(binder, bmd, homeSet, true, numLocalInterfaces, singleGlobalInterface);
    }

def load(self, callback=None, errback=None, reload=False):

        if not reload and self.data:
            raise AddressException('Address already loaded')

        def success(result, *args):
            self.data = result
            self.id = result['id']
            self.prefix = result['prefix']
            self.type = result['type']
            self.network = Network(self.config, id=result['network_id'])
            # self.scope_group = Scopegroup(config=self.config, id=result['scope_group_id']) NYI
            if self.type != 'host':
                self.report = self._rest.report(self.id)
                children = self._rest.retrieve_children(self.id)
                self.children = [Address(self.config, id=child['id']) for child in
                                 children if len(children) > 0]
            try:
                parent = self._rest.retrieve_parent(self.id)
                self.parent = Address(self.config, id=parent['id'])
            except ResourceException:
                pass
            if callback:
                return callback(self)
            else:
                return self

        if self.id is None:
            if self.prefix is None or self.type is None or self.network is None:
                raise AddressException('Must at least specify an id or prefix, type and network')
            else:
                network_id = self.network.id
                try:
                    self.id = [address for address in self._rest.list() if address['prefix'] == self.prefix and address[
                        'type'] == self.type and address['network_id'] == network_id][0]['id']
                except IndexError:
                    raise AddressException("Could not find address by prefix. It may not exist, or is a child address. "
                                           "Use the topmost parent prefix or specify ID")

        return self._rest.retrieve(self.id, callback=success,
                                   errback=errback)

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


Question: Gets a run for a build or creates it if it does not exist.

def _get_or_create_run(build):
    """"""
    release_name, release_number = _get_release_params()
    run_name = request.form.get('run_name', type=str)
    utils.jsonify_assert(run_name, 'run_name required')

    release = (
        models.Release.query
        .filter_by(build_id=build.id, name=release_name, number=release_number)
        .first())
    utils.jsonify_assert(release, 'release does not exist')

    run = (
        models.Run.query
        .filter_by(release_id=release.id, name=run_name)
        .first())
    if not run:
        # Ignore re-reports of the same run name for this release.
        logging.info('Created run: build_id=%r, release_name=%r, '
                     'release_number=%d, run_name=%r',
                     build.id, release.name, release.number, run_name)
        run = models.Run(
            release_id=release.id,
            name=run_name,
            status=models.Run.DATA_PENDING)
        db.session.add(run)
        db.session.flush()

    return release, run

function ElmRunner(filename, baseDir, defaults) {
  var relativePath = path.relative(baseDir, filename);
  var baseName = path.basename(filename, path.extname(filename));

  this.filename = filename;
  this.defaults = defaults || {};

  this.moduleName = resolveModuleName(relativePath);
  this.outputPath = path.join(path.dirname(filename), baseName + ".js");

  var self = this;
  withCheckedPath(this.outputPath, function() {
    try {
      compile.call(self);
      execute.call(self);
      wrap.call(self);
    } catch (e) {
      return e;
    }

    return true;
  });
}

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


Question:
Sets the transaction isolation level.

        :param level: the level to set

def set_transaction_isolation(self, level):

        self.ensure_connected()
        self._transaction_isolation_level = level
        self._platform.set_transaction_isolation(level)

protected function catchError($error){
        if($this->connection->inTransaction()){
            $this->errorTran[]= $error;
            $this->stateTran= FALSE;
        }
        $this->lastError= $error;

    }

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


Question: // This method returns disk space usage data for your CDN FTP.

func (r Network_ContentDelivery_Account) GetDiskSpaceUsageDataByDate(beginDateTime *datatypes.Time, endDateTime *datatypes.Time) (resp []datatypes.Metric_Tracking_Object_Data, err error) {
	params := []interface{}{
		beginDateTime,
		endDateTime,
	}
	err = r.Session.DoRequest("SoftLayer_Network_ContentDelivery_Account", "getDiskSpaceUsageDataByDate", params, &r.Options, &resp)
	return
}

def retrieveVals(self):
        """"""
        file_stats = self._fileInfo.getContainerStats()
        for contname in self._fileContList:
            stats = file_stats.get(contname)
            if stats is not None:
                if self.hasGraph('rackspace_cloudfiles_container_size'):
                    self.setGraphVal('rackspace_cloudfiles_container_size', contname,
                                     stats.get('size'))
                if self.hasGraph('rackspace_cloudfiles_container_count'):
                    self.setGraphVal('rackspace_cloudfiles_container_count', contname,
                                     stats.get('count'))

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


Question:
Update PluginsInstalled config

@param array $plugins Plugins

private function updatePluginsInstalledConfig($plugins)
    {
        $section = PiwikConfig::getInstance()->PluginsInstalled;
        $section['PluginsInstalled'] = $plugins;
        PiwikConfig::getInstance()->PluginsInstalled = $section;
    }

public function start(): int
    {
        $scripts = $this->installManager->install();

        $this->processRunner = new ProcessRunner($scripts->getStubService(), $this->getArguments());

        $processId =  $this->processRunner->run();
        \sleep(1); // wait for server to start

        return $processId;
    }

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


Question: Return text position inside of the given axis

def get_text_position(fig, ax, ha='left', va='top', pad_scale=1.0):
    """"""
    ## Check and preprocess input arguments
    try: pad_scale = float(pad_scale)
    except: raise TypeError("'pad_scale should be of type 'float'")

    for arg in [va, ha]:
        assert type(arg) is str
        arg = arg.lower() # Make it lowercase to prevent case problem.

    ## Get axis size in inches
    ax_height, ax_width = get_ax_size_in_inch(fig, ax)

    ## Construct inversion factor from inch to plot coordinate
    length_x = ax.get_xlim()[1] - ax.get_xlim()[0]
    length_y = ax.get_ylim()[1] - ax.get_ylim()[0]
    inch2coord_x = length_x / ax_width
    inch2coord_y = length_y / ax_height

    ## Set padding size relative to the text size
    #pad_inch = text_bbox_inch.height * pad_scale
    #pad_inch = fontsize_points * point2inch * pad_scale
    ax_length_geom_average = (ax_height * ax_width) ** 0.5
    pad_inch = ax_length_geom_average * 0.03 * pad_scale
    pad_inch_x, pad_inch_y = pad_inch, pad_inch

    pad_coord_x = pad_inch_x * inch2coord_x
    pad_coord_y = pad_inch_y * inch2coord_y

    if ha == 'left': pos_x = ax.get_xlim()[0] + pad_coord_x
    elif ha == 'right': pos_x = ax.get_xlim()[1] - pad_coord_x
    else: raise Exception("Unsupported value for 'ha'")

    if va in ['top','up','upper']: pos_y = ax.get_ylim()[1] - pad_coord_y
    elif va in ['bottom','down','lower']: pos_y = ax.get_ylim()[0] + pad_coord_y
    else: raise Exception("Unsupported value for 'va'")

    return pos_x, pos_y

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

		$this->_renderCartesianPlotArea();

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

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


Question:
/*
When the connection fails - send exit to all local pids with links
through this connection

synchronized void breakLinks() {
        if (links != null) {
            final Link[] l = links.clearLinks();

            if (l != null) {
                final int len = l.length;

                for (int i = 0; i < len; i++) {
                    // send exit "from" remote pids to local ones
                    self.deliver(new OtpMsg(OtpMsg.exitTag, l[i].remote(), l[i]
                            .local(), new OtpErlangAtom("noconnection")));
                }
            }
        }
    }

def write_channel(self, out_data):

        self._lock_netmiko_session()
        try:
            self._write_channel(out_data)
        finally:
            # Always unlock the SSH channel, even on exception.
            self._unlock_netmiko_session()

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


Question:
// checkIndexConsistency verifies a number of invariants on FileInfos received in
// index messages.

func checkIndexConsistency(fs []FileInfo) error {
	for _, f := range fs {
		if err := checkFileInfoConsistency(f); err != nil {
			return fmt.Errorf("%q: %v", f.Name, err)
		}
	}
	return nil
}

def _latch_file_info(self):

        self.files.file_dict.clear()
        self.sub_files.file_dict.clear()
        self.files.latch_file_info(self.args)
        self._scatter_link._update_sub_file_dict(self.sub_files)

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


Question: Strip a reference to a registry to just the hostname:port

def registry_hostname(registry):

    if registry.startswith('http:') or registry.startswith('https:'):
        return urlparse(registry).netloc
    else:
        return registry

def remove_coreference_layer(self):

        if self.coreference_layer is not None:
            this_node = self.coreference_layer.get_node()
            self.root.remove(this_node)
        if self.header is not None:
            self.header.remove_lp('coreferences')

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


Question: // HasColumnKeys returns true if any values use a column key.

func (p Bits) HasColumnKeys() bool {
	for i := range p {
		if p[i].ColumnKey != "" {
			return true
		}
	}
	return false
}

def set_ele(row, col, val)
      unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s)
        raise ArgumentError, 'Illegal argument type'
      end

      set_row(row, [''] * @col_keys.size) unless @row_keys[row]
      set_col(col, [''] * @row_keys.size) unless @col_keys[col]

      row = @row_keys[row]
      col = @col_keys[col]
      @content[row][col] = val.to_s

      self
    end

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


Question:
// ScriptedUpsert should be set to true if the referenced script
// (defined in Script or ScriptId) should be called to perform an insert.
// The default is false.

func (b *UpdateService) ScriptedUpsert(scriptedUpsert bool) *UpdateService {
	b.scriptedUpsert = &scriptedUpsert
	return b
}

private function executeBySyntax($syntax, $table, $data, $where = null, $where_params = array(), $stmt_key = null)
    {
        if (!is_null($where) && !is_array($where)) {
            $where = array($where);
        }

        if (is_object($data)) {
            $data = (array) $data;
        }

        $data = $this->removeNonExistentColumns($table, $data, $stmt_key);

        // support for scalar param
        if (!is_array($where_params)) {
            $where_params = array($where_params);
        }

        if (empty($stmt_key)) {
            $stmt = $this->getSetStmt($syntax, $table, $data, $where);
        } elseif (empty($this->prev_stmt[$stmt_key])) {
            $stmt = $this->getSetStmt($syntax, $table, $data, $where);
            $this->prev_stmt[$stmt_key] = $stmt;
        } else {
            $stmt = $this->prev_stmt[$stmt_key];
        }

        $stmt->execute(array_merge(array_values($data), $where_params));

        return $stmt;
    }

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


Question:
Transform a response.

@param string|object $response

@return mixed

public function transform($response)
    {
        $binding = $this->getBinding($response);

        return $this->adapter->transform($response, $binding->resolveTransformer(), $binding, $this->getRequest());
    }

public static function ddp($obj = NULL)
	{
		try
		{
			$json_str = json_encode($obj, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
			echo $json_str;
			die();
		}
		catch(SangriaException $e)
		{
			/**
			 * Default to dd if there is an exception while encoding to JSON
			 */
			var_dump($obj);
			die();
		}
	}

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


Question:
Removed field from object
@param string|array $fields
@return $this

public function unsetField($fields)
    {
        $fields = (array)$fields;
        foreach ($fields as $field) {
            unset($this->data[$field]);
        }

        return $this;
    }

function(attrs, attrsToRemove) {
    _.forEach(attrs, function(val, key) {
      // shouldRemove is either an object or a boolean
      var shouldRemove = attrsToRemove[key];
      if (_.isUndefined(shouldRemove)) {
        return;
      }

      // Support nested object
      if (_.isPlainObject(val) && !_.isArray(val) && _.isPlainObject(shouldRemove)) {
        return this._removeExpandableAttributes(val, shouldRemove);
      }

      // Make sure attribute is an object
      // Strip all nested properties except for `_id`
      if (_.isPlainObject(attrs[key]) && shouldRemove) {
        attrs[key] = _.pick(attrs[key], ['_id']);
      }
    }.bind(this));
  }

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


Question: Parses link to homepage and set value

def set_link(self):
        """"""
        try:
            self.link = self.soup.find('link').string
        except AttributeError:
            self.link = None

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

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

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

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


Question: list of periods, false if not

public boolean IsContained( String pFrom, String pTo )
	{
		if( periods == null )
		{
			// echo "IsContained() TO BE IMPLEMENTED FLLKJ :: {{ } ''<br/>";
			throw new RuntimeException( "Error Periods is Null" );
		}

		for( int i = 0; i < periods.size(); i++ )
		{
			Period period = periods.get( i );
			if( period.getFrom().compareTo( pFrom ) > 0 )
				return false;

			if( (pFrom.compareTo( period.getFrom() ) >= 0) && (pTo.compareTo( period.getTo() ) <= 0) )
				return true;
		}

		return false;
	}

public function isPeriodicTimerActive(TopicInterface $topic, $name)
    {
        $namespace = $this->getTopicNamespace($topic);

        return isset($this->registry[$namespace][$name]);
    }

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


Question: Refresh the job info.

def _refresh_state(self):

    # DataFlow's DataflowPipelineResult does not refresh state, so we have to do it ourselves
    # as a workaround.
    # TODO(Change this to use runner_results.state once it refreshes itself)
    dataflow_internal_job = (
        self._runner_results._runner.dataflow_client.get_job(self._runner_results.job_id()))
    self._is_complete = str(dataflow_internal_job.currentState) in ['JOB_STATE_STOPPED',
                                                                    'JOB_STATE_DONE',
                                                                    'JOB_STATE_FAILED',
                                                                    'JOB_STATE_CANCELLED']
    self._fatal_error = getattr(self._runner_results._runner, 'last_error_msg', None)
    # Sometimes Dataflow does not populate runner.last_error_msg even if the job fails.
    if self._fatal_error is None and self._runner_results.state == 'FAILED':
      self._fatal_error = 'FAILED'

func (s *CreateJobPlaylist) SetName(v string) *CreateJobPlaylist {
	s.Name = &v
	return s
}

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


Question:
Reset Search Term

@return mixed

public function reset()
    {
        session()->forget($this->getSearchableKey());

        if (request()->redirectUri) {
            return redirect()->to(request()->redirectUri);
        }

        return redirect()->to($this->previousUrl());
    }

def seek(value,type = :relative)
      command = case type
      when :percent then "seek #{value} 1"
      when :absolute then "seek #{value} 2"
      else "seek #{value} 0"
      end
      resp = command command, /Position/
      resp.gsub("Position: ","").gsub(" %\n","")
    end

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


Question:
Loads the select2 behavior and attaches it to a specified element

@see    https://select2.github.io

@param  array|ObjectConfig $config
@return string   The html output

public function select2($config = array())
    {
        $config = new ObjectConfigJson($config);
        $config->append(array(
            'cleanup' => false,
            'debug'   => \Kodekit::getInstance()->isDebug(),
            'element' => '.select2-listbox',
            'options_callback' => null, // wraps the call to select2 options in JavaScript, can be used to add JS code
            'options' => array(
                'theme'   => 'bootstrap',
                'width' => 'resolve'
            )
        ));

        $html = '';

        if (!static::isLoaded('select2'))
        {
            $html .= $this->jquery();
            $html .= '<ktml:script src="assets://js/'.($config->debug ? 'build/' : 'min/').'kodekit.select2.js" />';

            static::setLoaded('select2');
        }

        $options   = $config->options;
        $signature = md5('select2-'.$config->element.$config->options_callback.$options);

        if($config->element && !static::isLoaded($signature))
        {
            $options = (string) $options;

            if ($config->options_callback) {
                $options = $config->options_callback.'('.$options.')';
            }

            $html .= '<script>
            kQuery(function($){
                $("'.$config->element.'").select2('.$options.');
            });</script>';

            static::setLoaded($signature);
        }

        return $html;
    }

public function addConfigurationSetting($name, $value)
    {
        $this->checkConnectionUp("Cannot set configuration once a connection is made with the server.")
            ->configurator->set($name, $value);

        return $this;
    }

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


Question:
getBattery.

@return array of battery status

public function getBattery()
    {

        // Time?
        if (!empty($this->settings['timer'])) {
            $t = new Timer('Batteries');
        }

        // Return values
        $return = [];

        // Here they should be
        $bats = (array) @glob('/sys/class/power_supply/BAT*', GLOB_NOSORT);

        // Get vals for each battery
        foreach ($bats as $b) {
            foreach (array($b.'/manufacturer', $b.'/status') as $f) {
                if (!is_file($f)) {
                    continue 2;
                }
            }

            // Get these from the simple text files
            if (is_file($b.'/energy_full')) {
                $charge_full = Common::getIntFromFile($b.'/energy_full');
                $charge_now = Common::getIntFromFile($b.'/energy_now');
            }
            else if (is_file($b.'/charge_full')) {
                $charge_full = Common::getIntFromFile($b.'/charge_full');
                $charge_now = Common::getIntFromFile($b.'/charge_now');
            }
            else {
                continue;
            }

            // Alleged percentage
            $percentage = $charge_now != 0 && $charge_full != 0 ? (round($charge_now / $charge_full, 4) * 100) : '?';

            // Save result set
            $return[] = array(
                'charge_full' => $charge_full,
                'charge_now' => $charge_now,
                'percentage' => (is_numeric($percentage) && $percentage > 100 ? 100 : $percentage),
                'device' => Common::getContents($b.'/manufacturer').' '.Common::getContents($b.'/model_name', 'Unknown'),
                'state' => Common::getContents($b.'/status', 'Unknown'),
            );
        }

        // Give it
        return $return;
    }

private function _temperature()
    {
        if (isset($this->_buf['Temperature'])) foreach ($this->_buf['Temperature'] as $name=>$value) {
            $dev = new SensorDevice();
            $dev->setName($name);
            $dev->setValue($value);
            $this->mbinfo->setMbTemp($dev);
        }
    }

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


Question:
先序遍历当前节点树
@param  {Function} fn 遍历函数

function(fn, excludeThis) {
            var children = this.getChildren();
            if (!excludeThis) fn(this);
            for (var i = 0; i < children.length; i++) {
                children[i].preTraverse(fn);
            }
        }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question:
Saves the configuration information of the current running vent
        instance to be used for restoring at a later time

def backup(self):

        status = (True, None)
        # initialize all needed variables (names for backup files, etc.)
        backup_name = ('.vent-backup-' + '-'.join(Timestamp().split(' ')))
        backup_dir = join(expanduser('~'), backup_name)
        backup_manifest = join(backup_dir, 'backup_manifest.cfg')
        backup_vcfg = join(backup_dir, 'backup_vcfg.cfg')
        manifest = self.manifest

        # create new backup directory
        try:
            mkdir(backup_dir)
        except Exception as e:  # pragma: no cover
            self.logger.error(str(e))
            return (False, str(e))
        # create new files in backup directory
        try:
            # backup manifest
            with open(backup_manifest, 'w') as bmanifest:
                with open(manifest, 'r') as manifest_file:
                    bmanifest.write(manifest_file.read())
            # backup vent.cfg
            with open(backup_vcfg, 'w') as bvcfg:
                with open(self.vent_config, 'r') as vcfg_file:
                    bvcfg.write(vcfg_file.read())
            self.logger.info('Backup information written to ' + backup_dir)
            status = (True, backup_dir)
        except Exception as e:  # pragma: no cover
            self.logger.error("Couldn't backup vent: " + str(e))
            status = (False, str(e))
        # TODO #266
        return status

def initialize(self, action):
        # type: (CliContext, settings.TransferAction) -> None

        self._init_config()
        self.general_options = settings.create_general_options(
            self.config, action)
        self.credentials = settings.create_azure_storage_credentials(
            self.config, self.general_options)

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


Question: // Len returns the length of p in bits.

func (p *Prefix) Len() int {
	l, _ := p.Mask.Size()
	return l
}

func (pin Pin) DutyCycle(dutyLen, cycleLen uint32) {
	SetDutyCycle(pin, dutyLen, cycleLen)
}

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


Question:
Initalizes the technical information dialog
@private

function () {
			// create i18n model
			var oI18nModel = new ResourceModel({
				bundleName: "sap.ui.core.messagebundle"
			});
			this._oDialog.setModel(oI18nModel, "i18n");
			this._oDialog.setModel(this._createViewModel(), "view");

			// set compact/cozy style class
			this._oDialog.addStyleClass(this._getContentDensityClass());
		}

def save(self, commit=True):
        '''  '''
        if getattr(self.instance,'instructor',None):
            self.instance.instructor.availableForPrivates = self.cleaned_data.pop('availableForPrivates',self.instance.instructor.availableForPrivates)
            self.instance.instructor.save(update_fields=['availableForPrivates',])
        super(StaffMemberBioChangeForm,self).save(commit=True)

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


Question:
设置cookie原始参数，包含expires、path、domain等
@param array $cookiesOrigin
@return void

public function withCookieOriginParams(array $cookiesOrigin)
    {
        $self = clone $this;
        $self->cookiesOrigin = $cookiesOrigin;
        $self->cookies = [];
        foreach($cookiesOrigin as $name => $value)
        {
            $self->cookies[$name] = $value['value'];
        }
        return $self;
    }

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

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

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


Question:
Based on Twig_Extension_Debug / twig_var_dump
(c) 2011 Fabien Potencier

@param \Twig_Environment $env
@param string $context

public function dump(\Twig_Environment $env, $context)
    {
        if (!$env->isDebug() || !$this->debugger) {
            return;
        }

        $count = func_num_args();
        if (2 === $count) {
            $data = [];
            foreach ($context as $key => $value) {
                if (is_object($value)) {
                    if (method_exists($value, 'toArray')) {
                        $data[$key] = $value->toArray();
                    } else {
                        $data[$key] = "Object (" . get_class($value) . ")";
                    }
                } else {
                    $data[$key] = $value;
                }
            }
            $this->debugger->addMessage($data, 'debug');
        } else {
            for ($i = 2; $i < $count; $i++) {
                $this->debugger->addMessage(func_get_arg($i), 'debug');
            }
        }
    }

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


Question:
@param string $tableName
@param string $alias

@return QueryBuilder

public static function table(string $tableName, string $alias = null): QueryBuilder
    {
        $query = new QueryBuilder();
        $query = $query->table($tableName, $alias);

        return $query;
    }

private function getJobs()
    {
        if ($this->hasParameter('profile')) {
            $this->fetchJobs($this->getParameter('profile'));

            return;
        }

        $this->buildJobs([$this->getParameter('job')]);
    }

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


Question:
Fetch an image if it isn't already present.

    This works like ``docker pull`` and will pull the tag ``latest`` if no tag
    is specified in the image name.

def fetch_image(client, name):

    try:
        image = client.images.get(name)
    except docker.errors.ImageNotFound:
        name, tag = _parse_image_tag(name)
        tag = 'latest' if tag is None else tag

        log.info("Pulling tag '{}' for image '{}'...".format(tag, name))
        image = client.images.pull(name, tag=tag)

    log.debug("Found image '{}' for tag '{}'".format(image.id, name))
    return image

private function getRandomTags($count = 5)
    {
        $tags = ['action', 'adult', 'adventure', 'alpha', 'animals', 'animation', 'anime', 'architecture', 'art',
            'astronomy', 'baby', 'batshitinsane', 'biography', 'biology', 'book', 'books', 'business', 'business',
            'camera', 'cars', 'cats', 'cinema', 'classic', 'comedy', 'comics', 'computers', 'cookbook', 'cooking',
            'crime', 'culture', 'dark', 'design', 'digital', 'documentary', 'dogs', 'drama', 'drugs', 'education',
            'environment', 'evolution', 'family', 'fantasy', 'fashion', 'fiction', 'film', 'fitness', 'food',
            'football', 'fun', 'gaming', 'gift', 'health', 'hip', 'historical', 'history', 'horror', 'humor',
            'illustration', 'inspirational', 'internet', 'journalism', 'kids', 'language', 'law', 'literature', 'love',
            'magic', 'math', 'media', 'medicine', 'military', 'money', 'movies', 'mp3', 'murder', 'music', 'mystery',
            'news', 'nonfiction', 'nsfw', 'paranormal', 'parody', 'philosophy', 'photography', 'photos', 'physics',
            'poetry', 'politics', 'post-apocalyptic', 'privacy', 'psychology', 'radio', 'relationships', 'research',
            'rock', 'romance', 'rpg', 'satire', 'science', 'sciencefiction', 'scifi', 'security', 'self-help',
            'series', 'software', 'space', 'spirituality', 'sports', 'story', 'suspense', 'technology', 'teen',
            'television', 'terrorism', 'thriller', 'travel', 'tv', 'uk', 'urban', 'us', 'usa', 'vampire', 'video',
            'videogames', 'war', 'web', 'women', 'world', 'writing', 'wtf', 'zombies',
        ];

        shuffle($tags);

        $picked = array_slice($tags, 0, $count);

        return $picked;
    }

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


Question:
Ensure the major and minor are int.

    Parameters
    ----------
    version: list
        Version components

    Returns
    -------
    version: list
        List of components where first two components has been sanitised

def _sane_version_list(version):

    v0 = str(version[0])
    if v0:
        # Test if the major is a number.
        try:
            v0 = v0.lstrip("v").lstrip("V")
            # Handle the common case where tags have v before major.
            v0 = int(v0)
        except ValueError:
            v0 = None

    if v0 is None:
        version = [0, 0] + version
    else:
        version[0] = v0

    try:
        # Test if the minor is a number.
        version[1] = int(version[1])
    except ValueError:
        # Insert Minor 0.
        version = [version[0], 0] + version[1:]

    return version

func (s *SecretVersionsListEntry) SetVersionStages(v []*string) *SecretVersionsListEntry {
	s.VersionStages = v
	return s
}

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


Question:
Устанавливает параметры столбца

Перезаписываются только параметры указанные в $params

@access public

@param  int    $index  Номер столбца
@param  array  $params Описание столбца

function setColumn($index, $params)
	{
		if (isset($this->columns[$index])) $this->columns[$index] = array_merge($this->columns[$index], $params);
		else $this->columns[$index] = $params;
	}

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


Question:
@param SchemaQName $qname
@param string      $slug

@return string

private function getSlugCacheKey(SchemaQName $qname, string $slug): string
    {
        return str_replace('-', '_', sprintf(
            'stnr.%s.%s.%s',
            $qname->getVendor(),
            $qname->getMessage(),
            md5($slug)
        ));
    }

def build_collection_query_object(name, additional_parameters, *args)
    root = "/#{name.to_s}"
    if args.empty?
      #nothing to add
    elsif args.size == 1
      if args.first.to_s =~ /\d+/
        id_metadata = find_id_metadata(name.to_s)
        root << build_id_path(args.first, id_metadata)
      else
        root << "(#{args.first})"
      end
    else
      root << "(#{args.join(',')})"
    end
    QueryBuilder.new(root, additional_parameters)
  end

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


@Override
    public String getSessionCookieName() {
        String result = getSessionCookieNameFromContext((Context) getContainer());
        if ( result == null ) {
            result = Globals.SESSION_COOKIE_NAME;
            _log.debug( "Using session cookie name from context: " + result );
        }
        return result;
    }

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Search the item with the given ID.

@param id
the ID of the item to search, can be null.
@return An {@link Optional} containing the item if found, or
{@link Optional#absent()} if not found.

public Optional<OPFItem> getItemById(String id)
  {
    return Optional.fromNullable(itemsById.get(id));
  }

public ResourceDescription getChildDescription(String type, String name) {
        if (hasChildrenDefined()) {
            List<Property> children = get("children").asPropertyList();
            for (Property child : children) {
                if (type.equals(child.getName()) && child.getValue().hasDefined(MODEL_DESCRIPTION)) {
                    List<Property> modelDescriptions = child.getValue().get(MODEL_DESCRIPTION).asPropertyList();
                    for (Property modelDescription : modelDescriptions) {
                        if (name.equals(modelDescription.getName())) {
                            return new ResourceDescription(modelDescription.getValue());
                        }
                    }
                }
            }
        }
        return EMPTY;
    }

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


Question:
Transforms a project name into a valid Composer package name.

@param string $name The project name to transform

@return string The valid Composer package name

public function preCompile(Compiler $compiler)
    {
        $ir = $this->genIR($compiler);

        if (isset($ir['type']) && 'error' == $ir['type']) {
            throw new ParseException($ir['message'], $ir);
        }

        /**
         * Compilation context stores common objects required by compilation entities.
         */
        $compilationContext = new CompilationContext();

        /*
         * Set global compiler in the compilation context
         */
        $compilationContext->compiler = $compiler;

        /*
         * Set global config in the compilation context
         */
        $compilationContext->config = $this->config;

        /*
         * Set global logger in the compilation context
         */
        $compilationContext->logger = $this->logger;

        /*
         * Alias manager
         */
        $compilationContext->aliasManager = $this->aliasManager;

        $compilationContext->backend = $compiler->backend;

        /**
         * Traverse the top level statements looking for the namespace.
         */
        $namespace = null;

        foreach ($ir as $topStatement) {
            switch ($topStatement['type']) {
                case 'namespace':
                    if (null !== $namespace) {
                        throw new CompilerException('The namespace must be defined just one time', $topStatement);
                    }
                    $namespace = $topStatement['name'];
                    $this->namespace = $namespace;
                    if (!preg_match('/^[A-Z]/', $namespace)) {
                        throw new CompilerException(
                            "Namespace '{$namespace}' must be in camelized-form",
                            $topStatement
                        );
                    }
                    break;

                case 'cblock':
                    $this->headerCBlocks[] = $topStatement['value'];
                    break;

                case 'function':
                    $statements = null;
                    if (isset($topStatement['statements'])) {
                        $statements = new StatementsBlock($topStatement['statements']);
                    }

                    $parameters = null;
                    if (isset($topStatement['parameters'])) {
                        $parameters = new ClassMethodParameters($topStatement['parameters']);
                    }

                    $returnType = null;
                    if (isset($topStatement['return-type'])) {
                        $returnType = $topStatement['return-type'];
                    }

                    // Just do the precompilation of the function
                    $functionDefinition = new FunctionDefinition(
                        $namespace,
                        $topStatement['name'],
                        $parameters,
                        $statements,
                        $returnType,
                        $topStatement
                    );
                    $functionDefinition->preCompile($compilationContext);
                    $this->addFunction($compiler, $functionDefinition, $topStatement);
                    break;
            }
        }

        if (!$namespace) {
            throw new CompilerException('A namespace is required', isset($topStatement) ? $topStatement : null);
        }

        // Set namespace and flag as global, if before namespace declaration
        foreach ($this->functionDefinitions as $funcDef) {
            if (null == $funcDef->getNamespace()) {
                $funcDef->setGlobal(true);
                $funcDef->setNamespace($this->config->get('namespace'));
            }
        }

        $name = null;
        $class = false;
        $interface = false;
        $lastComment = null;

        foreach ($ir as $topStatement) {
            switch ($topStatement['type']) {
                case 'class':
                    if ($class || $interface) {
                        throw new CompilerException(
                            'More than one class/interface defined in the same file',
                            $topStatement
                        );
                    }
                    $class = true;
                    $name = $topStatement['name'];
                    $this->preCompileClass($compilationContext, $namespace, $topStatement, $lastComment);
                    $this->originalNode = $topStatement;
                    $lastComment = null;
                    break;

                case 'interface':
                    if ($class || $interface) {
                        throw new CompilerException(
                            'More than one class/interface defined in the same file',
                            $topStatement
                        );
                    }
                    $interface = true;
                    $name = $topStatement['name'];
                    $this->preCompileInterface($namespace, $topStatement, $lastComment);
                    $this->originalNode = $topStatement;
                    $lastComment = null;
                    break;

                case 'use':
                    if ($interface || $class) {
                        throw new CompilerException(
                            'Aliasing must be done before declaring any class or interface',
                            $topStatement
                        );
                    }
                    $this->aliasManager->add($topStatement);
                    break;

                case 'comment':
                    $lastComment = $topStatement;
                    break;
            }
        }

        if (!$class && !$interface) {
            throw new CompilerException(
                'Every file must contain at least a class or an interface',
                isset($topStatement) ? $topStatement : null
            );
        }

        if (!$this->external) {
            $expectedPath = strtolower(
                str_replace('\\', \DIRECTORY_SEPARATOR, $namespace).\DIRECTORY_SEPARATOR.$name.'.zep'
            );

            if (strtolower($this->filePath) != $expectedPath) {
                $className = $namespace.'\\'.$name;

                throw new CompilerException(
                    sprintf(
                        "Unexpected class name '%s' in file: '%s', expected: '%s'",
                        $className,
                        $this->filePath,
                        $expectedPath
                    )
                );
            }
        }

        if ($compilationContext->classDefinition) {
            if ($extendsClass = $compilationContext->classDefinition->getExtendsClass()) {
                $compiler->isClass($extendsClass);
            }
            if ($interfaces = $compilationContext->classDefinition->getImplementedInterfaces()) {
                foreach ($interfaces as $interface) {
                    $compiler->isInterface($interface);
                }
            }
        }

        $this->ir = $ir;
    }

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


Question: Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly.

def _sanitise(self):

        for k in self.__dict__:
            if isinstance(self.__dict__[k], np.float32):  # np.float32 has a broken __str__ method
                self.__dict__[k] = np.float64(self.__dict__[k])

def prt_tsv_dat(prt, data_nts, **kws):
    """"""
    sep = "\t" if 'sep' not in kws else kws['sep']
    fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt']
    if 'sort_by' in kws:
        data_nts = sorted(data_nts, key=kws['sort_by'])
    prt_if = kws['prt_if'] if 'prt_if' in kws else None
    prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields
    items = 0
    for nt_data_row in data_nts:
        if prt_if is None or prt_if(nt_data_row):
            if fld2fmt is not None:
                row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds]
                row_vals = _fmt_fields(row_fld_vals, fld2fmt)
            else:
                row_vals = [getattr(nt_data_row, fld) for fld in prt_flds]
            prt.write("{}\n".format(sep.join(str(d) for d in row_vals)))
            items += 1
    return items

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


Question: // SetHeaders sets a map of header fields in the mock response.

func (r *Response) SetHeaders(headers map[string]string) *Response {
	for key, value := range headers {
		r.Header.Add(key, value)
	}
	return r
}

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

        return $this;
    }

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


Question:
Match the next space bounded string
@param textProvider
@return true if matched

public boolean any(TextProvider textProvider)
    {
        clearLastToken(textProvider);
        clearLeadingSpaces(textProvider);
        mark(textProvider);
        if (m_debug)
			debug("testing",textProvider);
        StringBuilder sb = new StringBuilder();
        while (true)
        {
            char c = getNextChar(textProvider);

            if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0)
            {
            	break;
            }
            sb.append(c);
        }
        unmark(textProvider);
        String s = sb.toString().trim();
        if (s.length() == 0) return false;
        textProvider.setLastToken(s);
        debug(textProvider);
        return true;
    }

private void checkForEmptyIdentifier() {
    Character la = chars.lookahead(1);
    if (CharType.DOT.isMatchedBy(la) || CharType.PLUS.isMatchedBy(la)
        || CharType.EOL.isMatchedBy(la)) {
      throw new ParseException("Identifiers MUST NOT be empty", new UnexpectedCharacterException(la,
          chars.currentOffset(), CharType.DIGIT, CharType.LETTER, CharType.HYPHEN));
    }
  }

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


Question:
Return information about the name.
@return array

public function getPathInfo() {
    /** @var TokenNode $first */
    $first = $this->firstChild();
    $absolute = $first->getType() === T_NS_SEPARATOR;
    $relative = $first->getType() === T_NAMESPACE;
    $parts = $this->getParts();
    return [
      'absolute' => $absolute,
      'relative' => $relative,
      'qualified' => !$absolute && count($parts) > 1,
      'unqualified' => !$absolute && count($parts) === 1,
      'parts' => $parts,
    ];
  }

public function walk($callback, $output = null)
    {
        if ($output === null) {
            $output = clone $this;
            $output->exchangeArray([]);
        } elseif (is_string($output) and class_exists($output)) {
            $output = new $output();
        }

        foreach ($this as $key => $value) {
            $output[$key] = $callback($value, $key);
        }

        return $output;
    }

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


Question:
Calls deletePath() on each directory in the given list of directories to delete.
If moveToTrash is set, it will be moved to trash according to the file system trash policy.

public static void deleteDirectories(FileSystem fs, List<String> directoriesToDelete, boolean recursive, boolean moveToTrash) throws IOException {
    for (String directory : directoriesToDelete) {
      if (moveToTrash) {
        moveToTrash(fs, new Path(directory));
      } else {
        deletePath(fs, new Path(directory), recursive);
      }
    }
  }

public static function rrmdir($dir, $removeDir = false, $except = []) {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir . "/" . $object) == "dir") {
                        Terminal::rrmdir($dir . "/" . $object, $removeDir, $except);

                        if ($removeDir == true) {
                            rmdir($dir . "/" . $object . '/');
                        }
                    }
                    else {
                        if (!in_array($object, $except)) {
                            unlink($dir . "/" . $object);
                        }
                    }
                }
            }
            reset($objects);
        }
    }

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


Question:
Get the HAVING portion of the statement as a string.

@param  bool $usePlaceholders optional use ? placeholders, default true
@param  bool $includeText optional include 'HAVING' text, default true
@return string HAVING portion of the statement

public function getHavingString($usePlaceholders = true, $includeText = true)
    {
        $statement = $this->getCriteriaString($this->having, $usePlaceholders, $this->havingPlaceholderValues);

        if ($includeText && $statement) {
            $statement = "HAVING " . $statement;
        }

        return $statement;
    }

protected function seekTernaryElse(\Twig_TokenStream $tokens)
    {
        $i = 1;
        $depth = 0;
        $found = false;
        $token = null;

        while ($depth || !$found) {
            $token = $tokens->look($i);

            if (in_array($token->getType(), [\Twig_Token::BLOCK_END_TYPE, \Twig_Token::VAR_END_TYPE, \Twig_Token::INTERPOLATION_END_TYPE])) {
                return;
            }

            // End of hash value means end of short ternary (eg. "foo ? bar" syntax)
            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ',') {
                return;
            }

            if ($token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), ['(', '[', '{'])) {
                $depth++;
            }

            if ($depth && $token->getType() === \Twig_Token::PUNCTUATION_TYPE && in_array($token->getValue(), [')', ']', '}'])) {
                $depth--;
            }

            $found = $token->getType() === \Twig_Token::PUNCTUATION_TYPE && $token->getValue() === ':';
            $i++;
        }

        return $token;
    }

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


Question: Overload the `setExpanded` hook, so the counters are updated

function(ctx, flag, opts) {
		var tree = ctx.tree,
			node = ctx.node;
// Let the base implementation expand/collapse the node, then redraw the title
// after the animation has finished
		return this._super(ctx, flag, opts).always(function(){
			tree.nodeRenderTitle(ctx);
		});
	}

public function count()
    {
        if ($this->action() !== self::ACTION_READ) {
            return 0;
        }

        if (!$this->__resultSet) {
            $this->_execute();
        }

        if ($this->__resultSet) {
            return $this->__resultSet->total();
        }

        return 0;
    }

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


Question:
Builds an external (full qualified) URL for a repository path using the LinkUtil.getURL() method.

@param request the current request (domain host hint)
@param path    the repository path
@return the URL built in the context of the requested domain host

public static String externalUrl(SlingHttpServletRequest request, String path) {
        return LinkUtil.getAbsoluteUrl(request, LinkUtil.getUrl(request, path));
    }

def add_reference(self, subj: Node, val: str) -> None:

        match = FHIR_RESOURCE_RE.match(val)
        ref_uri_str = res_type = None
        if match:
            ref_uri_str = val if match.group(FHIR_RE_BASE) else (self._base_uri + urllib.parse.quote(val))
            res_type = match.group(FHIR_RE_RESOURCE)
        elif '://' in val:
            ref_uri_str = val
            res_type = "Resource"
        elif self._base_uri and not val.startswith('#') and not val.startswith('/'):
            ref_uri_str = self._base_uri + urllib.parse.quote(val)
            res_type = val.split('/', 1)[0] if '/' in val else "Resource"
        if ref_uri_str:
            ref_uri = URIRef(ref_uri_str)
            self.add(subj, FHIR.link, ref_uri)
            self.add(ref_uri, RDF.type, FHIR[res_type])

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


Question: // LocalDevices returns a map of the system's local devices.

func (d *driver) LocalDevices(
	ctx types.Context, opts types.Store) (*types.LocalDevices, error) {

	if ld, ok := context.LocalDevices(ctx); ok {
		return ld, nil
	}
	return nil, goof.New("missing local devices")
}

func (m HardwarePinMap) Add(pin Pin, names []string, modules []string) {
	m[pin] = &PinDef{pin, names, modules}
}

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


Question:
Get list value by path.
@param <T> list value type
@param clazz type of value
@param map subject
@param pathString nodes to walk in map
@return value

public static <T> Optional<List<T>> dotGetList(final Map map, final String pathString, final Class<T> clazz) {
        return dotGet(map, List.class, pathString).map(c -> (List<T>) c);
    }

private void visit(final ObjectGraphNode currentNode) {
		Object currentValue = currentNode.getValue();

		if (currentValue == null
				|| (currentValue instanceof java.lang.ref.SoftReference)
				|| currentNode.isPrimitive() || currentNode.isSimpleType()) {
			return;
		}

		if (isObjectVisited(currentNode)) {
			ObjectGraphNode ref = visitedNodes.get(currentValue);
			currentNode.setRefNode(ref);
			return;
		}

		markObjectVisited(currentNode);

		if (currentValue instanceof List) {
			// ArrayList's elementData is marked transient, and others may be as well, so we have to do this ourselves.
			visitList(currentNode);
		} else if (currentValue instanceof Map) {
			// HashMap's table is marked transient, and others may be as well, so we have to do this ourselves.
			visitMap(currentNode);
		} else if (currentValue instanceof ComponentModel) {
			// Special case for ComponentModel, so we can figure out if any fields are overridden
			visitComponentModel(currentNode);
		} else if (currentValue instanceof Field) {
			visitComplexType(currentNode);
			summariseNode(currentNode);
		} else if (currentValue.getClass().isArray()) {
			visitArray(currentNode);
		} else {
			visitComplexType(currentNode);
		}
	}

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


Question:
Rename a database within a server.

    When used with --force, an existing database with the same name as DEST is replaced, the original is renamed out of
    place in the form DEST_old_YYYYMMDD (unless --no-backup is specified).

def cmd_move(db=None):

    if db is None:
        db = connect()

    pg_move_extended(db, args.src, args.dest)

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

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

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

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

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

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


Question: // SetRouteResponseSelectionExpression sets the RouteResponseSelectionExpression field's value.

func (s *GetRouteOutput) SetRouteResponseSelectionExpression(v string) *GetRouteOutput {
	s.RouteResponseSelectionExpression = &v
	return s
}

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question: Get the Ranked Pair ranking

protected function getStats () : array
    {
        if (!$this->_StatsDone) :
            foreach ($this->_Stats['tally'] as &$Roundvalue) :
                foreach ($Roundvalue as $ArcKey => &$Arcvalue) :
                    foreach ($Arcvalue as $key => &$value) :
                        if ($key === 'from' || $key === 'to') :
                            $value = $this->_selfElection->getCandidateId($value, true);
                        endif;
                    endforeach;
                endforeach;
            endforeach;

            foreach ($this->_Stats['arcs'] as $ArcKey => &$Arcvalue) :
                foreach ($Arcvalue as $key => &$value) :
                    if ($key === 'from' || $key === 'to') :
                        $value = $this->_selfElection->getCandidateId($value, true);
                    endif;
                endforeach;
            endforeach;

            $this->_StatsDone = true;
        endif;

        return $this->_Stats;
    }

public static void write(final Iterable<HighScoringPair> hsps, final PrintWriter writer) {
        checkNotNull(hsps);
        checkNotNull(writer);
        for (HighScoringPair hsp : hsps) {
            writer.println(hsp.toString());
        }
    }

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


Question:
Determines if the exponent fits into this size of float.

@param $exponent int The exponent to check.
@return bool True if it fits, false otherwise.

public static function exponentFits($exponent)
    {
        // Determine if the exponent fits
        $max = floor((pow(2, static::getNumExponentBits()) - 1) / 2);
        $min = (-1 * $max) + 1;

        return (($exponent >= $min) && ($exponent <= $max));
    }

public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters'])) {
            return false;
        }

        if (1 != \count($expression['parameters'])) {
            throw new CompilerException("'globals_get' only accepts one parameter", $expression);
        }

        if ('string' != $expression['parameters'][0]['parameter']['type']) {
            throw new CompilerException("A string parameter is required for 'globals_get'", $expression);
        }

        $globalName = $expression['parameters'][0]['parameter']['value'];

        if (!$context->compiler->isExtensionGlobal($globalName)) {
            throw new CompilerException("Global '".$globalName."' cannot be read because it isn't defined", $expression);
        }

        $globalDefinition = $context->compiler->getExtensionGlobal($globalName);

        if (false !== strpos($globalName, '.')) {
            $parts = explode('.', $globalName);

            return new CompiledExpression($globalDefinition['type'], 'ZEPHIR_GLOBAL('.$parts[0].').'.$parts[1], $expression);
        }

        return new CompiledExpression($globalDefinition['type'], 'ZEPHIR_GLOBAL('.$globalName.')', $expression);
    }

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


Question: Returns a client token from Cerberus

def get_token(self):
        """"""
        signed_headers = self._get_v4_signed_headers()
        for header in self.HEADERS:
            signed_headers[header] = self.HEADERS[header]

        resp = post_with_retry(self.cerberus_url + '/v2/auth/sts-identity', headers=signed_headers)
        throw_if_bad_response(resp)

        token = resp.json()['client_token']
        iam_principal_arn = resp.json()['metadata']['aws_iam_principal_arn']
        if self.verbose:
            print('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn), file=sys.stderr)
        logger.info('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn))

        return token

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

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

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


Question:
Fetches product by id from database.

@param int $productId

@throws EntityNotFoundException

@return ProductInterface

public function fetchProduct($productId)
    {
        /** @var ProductInterface $product */
        $product = $this->getProductRepository()->find($productId);
        if (!$product) {
            throw new EntityNotFoundException($this->getProductRepository()->getClassName(), $productId);
        }

        return $product;
    }

public function findDuplicate(ItemEntity $item)
    {
        // get all names
        $names = [$item->getName()];
        foreach ($item->getNames() as $name) {
            $names[] = $name->getName();
        }

        // find from item main name
        $duplicate = $this->getEntityManager()->createQuery('
            SELECT
                i
            FROM
                AnimeDbCatalogBundle:Item i
            WHERE
                i.name IN (:names)
        ')
            ->setParameter(':names', $names)
            ->getResult();

        // find frim item other names
        $item_names = $this->getEntityManager()->createQuery('
            SELECT
                n
            FROM
                AnimeDbCatalogBundle:Name n
            WHERE
                n.name IN (:names)
            GROUP BY
                n.item
        ')
            ->setParameter(':names', $names)
            ->getResult();

        foreach ($item_names as $item_name) {
            // element has been added
            foreach ($duplicate as $item) {
                if ($item === $item_name->getItem()) {
                    continue 2;
                }
            }
            $duplicate[] = $item_name->getItem();
        }

        return $duplicate;
    }

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