Question:
// getAPI returns the API that supplies methods
// required to execute this command.

func (c *diffCommand) getAPI() (DiffCommandAPI, error) {
	if c.api != nil {
		return c.api, nil
	}
	api, err := c.NewAPIRoot()
	if err != nil {
		return nil, errors.Annotate(err, "opening API connection")
	}
	client := modelgeneration.NewClient(api)
	return client, nil
}

def search_dependencies(self):

        result = [self.module.name]
        #First we look at the explicit use references from this module and all
        #its dependencies until the chain terminates.
        stack = self.needs
        while len(stack) > 0:
            module = stack.pop()
            if module in result:
                continue

            self.parent.load_dependency(module, True, True, False)
            if module in self.parent.modules:
                for dep in self.parent.modules[module].needs:
                    modname = dep.split(".")[0]
                    if modname not in result:
                        result.append(modname)
                    if modname not in stack:
                        stack.append(modname)

        #Add any incidentals from the automatic construction of code. These can be from
        #executables that use special precision types without importing them or from
        #derived types. Same applies to the local members of this module.
        for ekey, anexec in list(self.executables.items()):
            for dep in anexec.search_dependencies():
                if dep is not None and dep not in result:
                    result.append(dep)

        for member in list(self.members.values()):
            dep = member.dependency()
            if dep is not None and dep not in result:
                result.append(dep)

        return result

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


Question: // ProcessConfigMsg returns ProcessConfigMsgVal, ConfigSeqVal, ProcessConfigMsgErr

func (mcs *ConsenterSupport) ProcessConfigMsg(env *cb.Envelope) (*cb.Envelope, uint64, error) {
	return mcs.ProcessConfigMsgVal, mcs.ConfigSeqVal, mcs.ProcessConfigMsgErr
}

func (c *initCmd) initKeyId() error {
	if k := c.keyId; k != "" {
		return nil
	}
	if k := os.Getenv("GPGKEY"); k != "" {
		c.keyId = k
		return nil
	}

	k, err := jsonsign.KeyIdFromRing(c.secretRing)
	if err != nil {
		hint := "You can set --gpgkey=<pubid> or the GPGKEY env var to select which key ID to use.\n"
		return fmt.Errorf("No suitable gpg key was found in %v: %v.\n%v", c.secretRing, err, hint)
	}
	c.keyId = k
	log.Printf("Re-using identity with keyId %q found in file %s", c.keyId, c.secretRing)
	return nil
}

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


Question:
Frees the memory for the array with the given handle.

        Args:
          handle: The handle of the array whose memory should be freed. This
            handle must come from the _create_array method.

def _free_array(self, handle: int):

        with self._lock:
            if self._arrays[handle] is not None:
                self._arrays[handle] = None
                self._count -= 1

def main():

    parser = argparse.ArgumentParser(
        description='A pipeline that generates analysis pipelines.')
    parser.add_argument('input', nargs='?',
                   help='A valid metapipe configuration file.')
    parser.add_argument('-o', '--output',
                   help='An output destination. If none is provided, the '
                   'results will be printed to stdout.',
                   default=sys.stdout)
    parser.add_argument('-t', '--temp',
                   help='A desired metapipe binary file. This is used to store '
                   'temp data between generation and execution. '
                   '(Default: "%(default)s")', default='.metapipe')
    parser.add_argument('-s', '--shell',
                   help='The path to the shell to be used when executing the '
                   'pipeline. (Default: "%(default)s)"',
                   default='/bin/bash')
    parser.add_argument('-r', '--run',
                   help='Run the pipeline as soon as it\'s ready.',
                   action='store_true')
    parser.add_argument('-n', '--name',
                   help='A name for the pipeline.',
                   default='')
    parser.add_argument('-j', '--job-type',
                   help='The destination for calculations (i.e. local, a PBS '
                   'queue on a cluster, etc).\nOptions: {}. '
                   '(Default: "%(default)s)"'.format(JOB_TYPES.keys()),
                   default='local')
    parser.add_argument('-p', '--max-jobs',
                   help='The maximum number of concurrent jobs allowed. '
                   'Defaults to maximum available cores.',
                   default=None)
    parser.add_argument('--report-type',
                   help='The output report type. By default metapipe will '
                   'print updates to the console. \nOptions: {}. '
                   '(Default: "%(default)s)"'.format(QUEUE_TYPES.keys()),
                   default='text')
    parser.add_argument('-v','--version',
                    help='Displays the current version of the application.',
                    action='store_true')
    args = parser.parse_args()

    if args.version:
        print('Version: {}'.format(__version__))
        sys.exit(0)

    try:
        with open(args.input) as f:
            config = f.read()
    except IOError:
        print('No valid config file found.')
        return -1

    run(config, args.max_jobs, args.output, args.job_type, args.report_type,
        args.shell, args.temp, args.run)

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


Question:
See if there is a number (all digits)
@param textProvider
@return true if matched

public boolean number(TextProvider textProvider)

    {
        clearLastToken(textProvider);
        clearLeadingSpaces(textProvider);
        mark(textProvider);
        if (m_debug)
	        debug("testing",textProvider);
        StringBuilder sb = new StringBuilder();
        boolean hasDecimal = false;
        while (true)
        {
            char c = getNextChar(textProvider);
            if (c == 'L')
            {
                remark(textProvider);
                sb.append(c);
                break;
            }
            if (c == 'D')
            {
                remark(textProvider);
                sb.append(c);
                break;
            }
            if (c == 'F')
            {
                remark(textProvider);
                sb.append(c);
                break;
            }
            if (!Character.isDigit(c) && c != '.')
            {
                break;
            }
            if (c == '.')
            {
                if (hasDecimal)
                {
                    break;
                }
                else
                {
                    hasDecimal = true;
                }
            }
            remark(textProvider);
            sb.append(c);
        }
        reset(textProvider); // removes last char
        String s = sb.toString().trim();
        if (s.length() == 0) return false;
        textProvider.setLastToken(s);
        debug(textProvider);
        return true;
    }

protected void init(String str) {
	int len = str.length();
	text = new char[len];
	lcText = new char[len];

	for (int i = 0; i < len; i++) {
	    char c = str.charAt(i);
	    text[i] = c;
	    if (c == '\n' || c == '\r' || c == '\t') {
		lcText[i] = ' ';
	    }
	    else lcText[i] = ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) ? c : Character.toLowerCase(c);
	}
    }

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


Question:
Migrate up

@return void

public function up()
    {
        $table = $this->table('users');
        $table->addColumn('timezone', 'string', ['limit' => 255, 'null' => false, 'default' => 'Europe/Berlin', 'after' => 'email']);
        $table->update();

        $this->clearModelCache();
    }

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

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


Question:
Get values of fields.

@param $qr_fields
@param $qr_values
@return bool

protected function getfieldsvalues(&$qr_fields, &$qr_values) {
		$qr_fields = array();
		$qr_values = array();
		parent::getfieldsvalues($qr_fields, $qr_values);

		if (empty($this->{$this->parentKeyName})) {
			$qr_fields[] = '`' . $this->parentKeyName . '`';
			$qr_values[] = 'NULL';
		} else {
			$qr_fields[] = '`' . $this->parentKeyName . '`';
			$qr_values[] = $this->{$this->parentKeyName};
		}

		$qr_fields[] = '`' . $this->leftKeyName . '`';
		$qr_values[] = $this->{$this->leftKeyName};
		$qr_fields[] = '`' . $this->rightKeyName . '`';
		$qr_values[] = $this->{$this->rightKeyName};
		$qr_fields[] = '`' . $this->levelKeyName . '`';
		$qr_values[] = $this->{$this->levelKeyName};
		$qr_fields[] = '`' . $this->groupKeyName . '`';
		$qr_values[] = $this->{$this->groupKeyName};
		return true;
	}

public function execute($row = null)
    {
        if ($row) {
            if ((! isset($row['grs_id_user'])) &&
                    isset($row['grs_ssn']) &&
                    $this->targetModel instanceof \Gems_Model_RespondentModel &&
                    $this->targetModel->hashSsn !== \Gems_Model_RespondentModel::SSN_HIDE) {

                if (\Gems_Model_RespondentModel::SSN_HASH === $this->targetModel->hashSsn) {
                    $search = $this->targetModel->saveSSN($row['grs_ssn']);
                } else {
                    $search = $row['grs_ssn'];
                }

                $sql = 'SELECT grs_id_user FROM gems__respondents WHERE grs_ssn = ?';
                $id  = $this->db->fetchOne($sql, $search);

                // Check for change in patient ID
                if ($id) {
                    if (isset($row['gr2o_id_organization']) &&
                            $this->targetModel instanceof \MUtil_Model_DatabaseModelAbstract) {

                        $sql = 'SELECT gr2o_patient_nr
                                FROM gems__respondent2org
                                WHERE gr2o_id_user = ? AND gr2o_id_organization = ?';

                        $patientId = $this->db->fetchOne($sql, array($id, $row['gr2o_id_organization']));

                        if ($patientId) {
                            // Change the patient number
                            $copyId       = $this->targetModel->getKeyCopyName('gr2o_patient_nr');
                            $row[$copyId] = $patientId;
                        }
                    }

                    $row['grs_id_user']  = $id;
                    $row['gr2o_id_user'] = $id;
                }
            }

            parent::execute($row);
        }
    }

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


Question:
Gets a challenge token from the server and stores for future requests
@access private
@param  string $username VTiger user name
@return boolean Returns false in case of failure

private function passChallenge($username)
    {
        $getdata = [
            'operation' => 'getchallenge',
            'username'  => $username
        ];
        $result = $this->sendHttpRequest($getdata, 'GET');

        if (!is_array($result) || !isset($result[ 'token' ])) {
            return false;
        }

        $this->serviceExpireTime = $result[ 'expireTime' ];
        $this->serviceToken = $result[ 'token' ];

        return true;
    }

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

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

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

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


Question:
Creates VTK render window with an interactor.

    :param actors: list of VTK actors
    :type actors: list, tuple
    :param callbacks: callback functions for registering custom events
    :type callbacks: dict

def create_render_window(actors, callbacks, **kwargs):

    # Get keyword arguments
    figure_size = kwargs.get('figure_size', (800, 600))
    camera_position = kwargs.get('camera_position', (0, 0, 100))

    # Find camera focal point
    center_points = []
    for actor in actors:
        center_points.append(actor.GetCenter())
    camera_focal_point = linalg.vector_mean(*center_points)

    # Create camera
    camera = vtk.vtkCamera()
    camera.SetPosition(*camera_position)
    camera.SetFocalPoint(*camera_focal_point)

    # Create renderer
    renderer = vtk.vtkRenderer()
    renderer.SetActiveCamera(camera)
    renderer.SetBackground(1.0, 1.0, 1.0)

    # Add actors to the scene
    for actor in actors:
        renderer.AddActor(actor)

    # Render window
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window.SetSize(*figure_size)

    # Render window interactor
    window_interactor = vtk.vtkRenderWindowInteractor()
    window_interactor.SetRenderWindow(render_window)

    # Add event observers
    for cb in callbacks:
        window_interactor.AddObserver(cb, callbacks[cb][0], callbacks[cb][1])  # cb name, cb function ref, cb priority

    # Render actors
    render_window.Render()

    # Set window name after render() is called
    render_window.SetWindowName("geomdl")

    # Use trackball camera
    interactor_style = vtk.vtkInteractorStyleTrackballCamera()
    window_interactor.SetInteractorStyle(interactor_style)

    # Start interactor
    window_interactor.Start()

    # Return window interactor instance
    return window_interactor

public function set_model( $model )
    {
        // Check that the required arguments are provided.
        foreach( $this->required_arguments() as $key )
        {
            if ( !isset($model[$key]) )
            {
                throw new \RuntimeException('The required argument "'.$key.'" was not provided for '.get_called_class());
            }
        }

        // Assign the name of the component as the id if no id was specified
        if( !isset($model['id']) && isset($model['name']) )
        {
            $model['id'] = $model['name'];
        }

        // A name must be specified when a component has a visibility condition
        if( isset($model['show']) && !isset($model['name']) )
        {
            throw new \RuntimeException('Components with a visibility condition (a "show" argument) must have a name');
        }

        $this->model = array_merge( $this->default_model(), $model );
    }

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


Question:
get the autoRemoved property of the service instance.
@return true by default

public boolean getAutoRemoved(){
        Map<String, String> meta = getMetadata();
        if (meta!=null&&meta.containsKey("autoRemoved")){
            return !"false".equals(meta.get("autoRemoved"));
        }
        return true;
    }

public static function removeType($type)
    {
        if (!static::hasType($type)) {
            throw TypeException::typeDoesNotExist($type);
        }

        if (isset(static::$mappedTypeInstances[$type])) {
            unset(static::$mappedTypeInstances[$type]);
        }

        unset(static::$mappedTypeClasses[$type]);
    }

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


Question:
Read security list packet send from server to client
        @param data: Stream that contains well formed packet

def recvSecurityList(self, data):

        securityList = []
        while data.dataLen() > 0:
            securityElement = UInt8()
            data.readType(securityElement)
            securityList.append(securityElement)
        #select high security level
        for s in securityList:
            if s.value in [SecurityType.NONE, SecurityType.VNC] and s > self._securityLevel:
                self._securityLevel = s
                break
        #send back security level choosen
        self.send(self._securityLevel)
        if self._securityLevel.value == SecurityType.VNC:
            self.expect(16, self.recvVNCChallenge)
        else:
            self.expect(4, self.recvSecurityResult)

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question: Merge two dictionaries and return the result

def merge_dicts(dict1, dict2):

    tmp = dict1.copy()
    tmp.update(dict2)
    return tmp

def append(self, key, item):

        with self._lock:
            if key in self._dict:
                self._dict[key].append(item)
            else:
                self._dict[key] = [item]

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


Question:
Adds a resource to the set the set of resources.

@param string|array $config

public function insert($config)
    {
        if (is_string($config)) {
            $config = array('name' => $config);
        }

        $config = new AnConfig($config);

        if (empty($config->link) && !empty($this->_resources)) {
            $name = AnInflector::singularize($this->main()->getName());
            $config->link = array('child' => $name.'_id','parent' => 'id');
        }

        $config->append(array(
            'columns' => $this->_store->getColumns($config->name),
        ));

        $resource = new AnDomainResource($config);
        $this->_resources[$resource->getAlias()] = $resource;

        return $this;
    }

public function getChildren(ConfigurationInterface $configuration)
    {
        $children = [];

        foreach ($this->configurations as $child) {
            if ($child->getParentId() === $configuration->getResourceId()) {
                $children[$child->getResourceName()] = $child;
            }
        }

        return $children;
    }

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


Question: create zmq sockets

def create_sockets(self):
        """"""

        ports = self.ports

        context = zmq.Context()
        poller = zmq.Poller()

        # Socket to handle init data
        rep = context.socket(zmq.REP)
        # this was inconsequent: here REQ is for the client, we reply with REP.
        # PULL and PUB is seen from here, not from the client.
        # Is now renamed to PUSH and SUB: everything is seen from outside.
        if "REQ" in ports:
            rep.bind(
                "tcp://*:{port}".format(port=ports["REQ"])
            )
        else:
            ports["REQ"] = rep.bind_to_random_port(
                "tcp://*"
            )

        pull = context.socket(zmq.PULL)
        if "PUSH" in ports:
            pull.bind(
                "tcp://*:{port}".format(port=ports["PUSH"])
            )
        else:
            ports["PUSH"] = pull.bind_to_random_port(
                "tcp://*"
            )

        # for sending model messages
        pub = context.socket(zmq.PUB)
        if "SUB" in ports:
            pub.bind(
                "tcp://*:{port}".format(port=ports["SUB"])
            )
        else:
            ports["SUB"] = pub.bind_to_random_port(
                "tcp://*"
            )

        poller.register(rep, zmq.POLLIN)
        poller.register(pull, zmq.POLLIN)

        sockets = dict(
            poller=poller,
            rep=rep,
            pull=pull,
            pub=pub
        )
        return sockets

def connect_channels(self, channels):
        """"""
        self.log.info(f"Connecting to channels...")
        for chan in channels:
            chan.connect(self.sock)
            self.log.info(f"\t{chan.channel}")

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


Question:
Edit a location in the chat.
@return EditMessageLiveLocation                New EditMessageLiveLocation.

public function editMessageLiveLocationReply(): EditMessageLiveLocation
	{
		$m = $this->bot->editMessageLiveLocation();
		$this->setReplyMarkup($m, false);
		return $m;
	}

def status_message(bucket_name, state)
      message = ['', "Bucket s3://#{bucket_name} #{state}"]
      message << "Config dir #{config_dir} #{state}"

      state = 'complete' if state == 'created'
      message << "Config #{state}"

      message.join("\n")
    end

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


Question:
verifyWithExtra driver.

@param $inputs

@return array

public function verifyWithExtra($inputs)
    {
        $result = $this->restCall('PaymentVerificationWithExtra.json', $inputs);

        if ($result['Status'] == 100 || $result['Status'] == 101) {
            return ['Status' => 'success', 'RefID' => $result['RefID']];
        } else {
            return ['Status' => 'error', 'error' => $result['Status']];
        }
    }

public function addParticipation($testIdentifier, $variationIdentifier)
    {
        Assert::string($testIdentifier, 'Test identifier must be a string');
        Assert::string($variationIdentifier, 'Variation name must be a string');

        $this->participations[$testIdentifier] = $variationIdentifier;
    }

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


Question:
Recover user information, by getting the email for the reset pass form
@method POST
@url /v1/recover

@return Response

public function recover() : Response
    {
        //if the user submited the form and passes the security check then we start checking
        $email = $this->request->getPost('email', 'email');

        $validation = new Validation();
        $validation->add('email', new PresenceOf(['message' => _('The email is required.')]));
        $validation->add('email', new EmailValidator(['message' => _('The email is invalid.')]));

        $messages = $validation->validate($this->request->getPost());
        if (count($messages)) {
            foreach ($messages as $message) {
                throw new Exception($message);
            }
        }

        /**
         * check if the user email exist
         * if it does creat the user activation key to send
         * send the user email
         *
         * if it doesnt existe then send the erro msg
         */
        if ($recoverUser = Users::getByEmail($email)) {
            $recoverUser->user_activation_forgot = $recoverUser->generateActivationKey();
            $recoverUser->update();

            $message = _('Please check your email inbox to complete the password recovery.');
            $this->sendEmail($recoverUser, 'recover');
        } else {
            $message = _('There is no account registered with that email.');
        }

        return $this->response($message);
    }

private void addPostParams(final Request request) {
        if (friendlyName != null) {
            request.addPostParam("FriendlyName", friendlyName);
        }

        if (domainName != null) {
            request.addPostParam("DomainName", domainName);
        }

        if (disasterRecoveryUrl != null) {
            request.addPostParam("DisasterRecoveryUrl", disasterRecoveryUrl.toString());
        }

        if (disasterRecoveryMethod != null) {
            request.addPostParam("DisasterRecoveryMethod", disasterRecoveryMethod.toString());
        }

        if (recording != null) {
            request.addPostParam("Recording", recording.toString());
        }

        if (secure != null) {
            request.addPostParam("Secure", secure.toString());
        }

        if (cnamLookupEnabled != null) {
            request.addPostParam("CnamLookupEnabled", cnamLookupEnabled.toString());
        }
    }

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


Question:
// Files reads and returns a slice of names from the given directory
// relative to the root of Context c.

func (c Context) Files(name string) ([]string, error) {
	dir, err := c.Root.Open(path.Clean(name))
	if err != nil {
		return nil, err
	}
	defer dir.Close()

	stat, err := dir.Stat()
	if err != nil {
		return nil, err
	}
	if !stat.IsDir() {
		return nil, fmt.Errorf("%v is not a directory", name)
	}

	dirInfo, err := dir.Readdir(0)
	if err != nil {
		return nil, err
	}

	names := make([]string, len(dirInfo))
	for i, fileInfo := range dirInfo {
		names[i] = fileInfo.Name()
	}

	return names, nil
}

def _ScanFileSystem(self, scan_node, base_path_specs):

    if not scan_node or not scan_node.path_spec:
      raise errors.ScannerError('Invalid or missing file system scan node.')

    base_path_specs.append(scan_node.path_spec)

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


Question:
Checks to see if a slug is available. If the slug is already being used
        this method returns False.  Otherwise, return True.

def is_slug_available(self, slug, **kwargs):

        try:
            self.get(slug=slug, **kwargs)
            return False
        except self.model.DoesNotExist:
            return True

public function create()
    {
        // Is this user allowed to do this?
        if (!$this->repository->isUserAllowed('create'))
        {
            Session::flash('status_code', 400 );
            $message = "You are not allowed to create ".$this->table_type_plural;
            Session::flash('message', $message);
            return view('formhandling::warnings/' . config('lasallecmsadmin.admin_template_name') . '/user_not_allowed', [
                'package_title'        => $this->package_title,
                'table_type_plural'    => $this->table_type_plural,
                'table_type_singular'  => $this->table_type_singular,
                'resource_route_name'  => $this->resource_route_name,
                'HTMLHelper'           => HTMLHelper::class,
            ]);
        }

        return view('formhandling::lookuptables/' . config('lasallecmsadmin.admin_template_name') . '/create', [
            'package_title'        => $this->package_title,
            'table_type_plural'    => $this->table_type_plural,
            'table_type_singular'  => $this->table_type_singular,
            'resource_route_name'  => $this->resource_route_name,
            'DatesHelper'          => DatesHelper::class,
            'HTMLHelper'           => HTMLHelper::class,
        ]);
    }

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


Question:
Публикация ресурса\Закрытие доступа

@param   boolean $publish TRUE открыть доступ, FALSE закрыть доступ

@return  \Arhitector\Yandex\Disk\Resource\Closed|\Arhitector\Yandex\Disk\Resource\Opened

public function setPublish($publish = true)
	{
		$request = 'resources/unpublish';

		if ($publish)
		{
			$request = 'resources/publish';
		}

		$response = $this->client->send(new Request($this->uri->withPath($this->uri->getPath().$request)
			->withQuery(http_build_query([
				'path' => $this->getPath()
			], null, '&')), 'PUT'));

		if ($response->getStatusCode() == 200)
		{
			$this->setContents([]);

			if ($publish && $this->has('public_key'))
			{
				return $this->client->getPublishResource($this->get('public_key'));
			}
		}

		return $this;
	}

func DeployResources(args DeployResourcesArgs) (ids map[string]string, err error) {
	d := deployUploader{
		applicationID: args.ApplicationID,
		chID:          args.CharmID,
		csMac:         args.CharmStoreMacaroon,
		client:        args.Client,
		resources:     args.ResourcesMeta,
		osOpen:        func(s string) (ReadSeekCloser, error) { return os.Open(s) },
		osStat:        func(s string) error { _, err := os.Stat(s); return err },
	}

	ids, err = d.upload(args.ResourceValues, args.Revisions)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ids, nil
}

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


Question: // SetTimedMetadataInsertion sets the TimedMetadataInsertion field's value.

func (s *JobSettings) SetTimedMetadataInsertion(v *TimedMetadataInsertion) *JobSettings {
	s.TimedMetadataInsertion = v
	return s
}

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question: // E sets z to the mathematical constant e and returns z.

func E(z *decimal.Big) *decimal.Big {
	ctx := decimal.Context{Precision: precision(z)}
	if ctx.Precision <= constPrec {
		return ctx.Set(z, _E)
	}

	ctx.Precision += 5
	var (
		sum  = z.SetUint64(2)
		fac  = new(decimal.Big).SetUint64(1)
		term = new(decimal.Big)
		prev = new(decimal.Big)
	)

	for i := uint64(2); sum.Cmp(prev) != 0; i++ {
		// Use term as our intermediate storage for our factorial. SetUint64
		// should be marginally faster than ctx.Add(incr, incr, one), but either
		// the costly call to Quo makes it difficult to notice.
		term.SetUint64(i)
		ctx.Mul(fac, fac, term)
		ctx.Quo(term, one, fac)
		prev.Copy(sum)
		ctx.Add(sum, sum, term)
	}

	ctx.Precision -= 5
	return ctx.Set(z, sum)
}

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question:
Read a string that's up to 2**32 bytes, the encoding
isn't specified in the AMQP spec, so just return it as
a plain PHP string.

@return string
@throws \Exception

public function readLongstr()
    {
        $this->_bitcount = $this->_bits = 0;
        $slen = $this->readPhpInt();
        if ($slen < 0) {
            throw new \Exception("Strings longer than supported on this platform");
        }
        return $this->_rawread($slen);
    }

public function getLastMessage()
    {
        $filename = $this->getTempFilename();

        if (file_exists($filename)) {
            $result = unserialize(file_get_contents($filename));
        } else {
            throw new Swift_IoException('No last message found in "' . $filename . '" - did you call send()?');
        }

        return $result;
    }

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


Question:
Returns a module instance by its name.

@param string $name Module name.
@return object Module instance.

private function getModule($name)
    {
        if (!$this->moduleContainer->hasModule($name)) {
            throw new Exception(sprintf('«%s» module is not available.', $name));
        }

        $module = $this->moduleContainer->getModule($name);

        return $module;
    }

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question:
// SubmitLongMsg sends a long message (more than 140 bytes)
// and returns and updates the given sm with the response status.
// It returns the same sm object.

func (t *Transmitter) SubmitLongMsg(sm *ShortMessage) ([]ShortMessage, error) {
	maxLen := 133 // 140-7 (UDH with 2 byte reference number)
	switch sm.Text.(type) {
	case pdutext.GSM7:
		maxLen = 152 // to avoid an escape character being split between payloads
		break
	case pdutext.GSM7Packed:
		maxLen = 132 // to avoid an escape character being split between payloads
		break
	case pdutext.UCS2:
		maxLen = 132 // to avoid a character being split between payloads
		break
	}
	rawMsg := sm.Text.Encode()
	countParts := int((len(rawMsg)-1)/maxLen) + 1

	parts := make([]ShortMessage, 0, countParts)

	t.rMutex.Lock()
	rn := uint16(t.r.Intn(0xFFFF))
	t.rMutex.Unlock()
	UDHHeader := make([]byte, 7)
	UDHHeader[0] = 0x06              // length of user data header
	UDHHeader[1] = 0x08              // information element identifier, CSMS 16 bit reference number
	UDHHeader[2] = 0x04              // length of remaining header
	UDHHeader[3] = uint8(rn >> 8)    // most significant byte of the reference number
	UDHHeader[4] = uint8(rn)         // least significant byte of the reference number
	UDHHeader[5] = uint8(countParts) // total number of message parts
	for i := 0; i < countParts; i++ {
		UDHHeader[6] = uint8(i + 1) // current message part
		p := pdu.NewSubmitSM(sm.TLVFields)
		f := p.Fields()
		f.Set(pdufield.SourceAddr, sm.Src)
		f.Set(pdufield.DestinationAddr, sm.Dst)
		if i != countParts-1 {
			f.Set(pdufield.ShortMessage, pdutext.Raw(append(UDHHeader, rawMsg[i*maxLen:(i+1)*maxLen]...)))
		} else {
			f.Set(pdufield.ShortMessage, pdutext.Raw(append(UDHHeader, rawMsg[i*maxLen:]...)))
		}
		f.Set(pdufield.RegisteredDelivery, uint8(sm.Register))
		if sm.Validity != time.Duration(0) {
			f.Set(pdufield.ValidityPeriod, convertValidity(sm.Validity))
		}
		f.Set(pdufield.ServiceType, sm.ServiceType)
		f.Set(pdufield.SourceAddrTON, sm.SourceAddrTON)
		f.Set(pdufield.SourceAddrNPI, sm.SourceAddrNPI)
		f.Set(pdufield.DestAddrTON, sm.DestAddrTON)
		f.Set(pdufield.DestAddrNPI, sm.DestAddrNPI)
		f.Set(pdufield.ESMClass, 0x40)
		f.Set(pdufield.ProtocolID, sm.ProtocolID)
		f.Set(pdufield.PriorityFlag, sm.PriorityFlag)
		f.Set(pdufield.ScheduleDeliveryTime, sm.ScheduleDeliveryTime)
		f.Set(pdufield.ReplaceIfPresentFlag, sm.ReplaceIfPresentFlag)
		f.Set(pdufield.SMDefaultMsgID, sm.SMDefaultMsgID)
		f.Set(pdufield.DataCoding, uint8(sm.Text.Type()))
		resp, err := t.do(p)
		if err != nil {
			return nil, err
		}
		sm.resp.Lock()
		sm.resp.p = resp.PDU
		sm.resp.Unlock()
		if resp.PDU == nil {
			return parts, fmt.Errorf("unexpected empty PDU")
		}
		if id := resp.PDU.Header().ID; id != pdu.SubmitSMRespID {
			return parts, fmt.Errorf("unexpected PDU ID: %s", id)
		}
		if s := resp.PDU.Header().Status; s != 0 {
			return parts, s
		}
		if resp.Err != nil {
			return parts, resp.Err
		}
		parts = append(parts, *sm)
	}
	return parts, nil
}

def create(self, sid):

        data = values.of({'Sid': sid, })

        payload = self._version.create(
            'POST',
            self._uri,
            data=data,
        )

        return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], )

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


Question:
替换指定名称数据

@param string $name 名称
@param string $value 值
@param int $status 状态
@return bool

public static function replaceByName($name, $value, $status)
    {
        $obj = static::find()
            ->findByName($name)
            ->one();
        if (!$obj) {
            $obj = new static();
        }
        $obj->setAttributes([
            'name' => $name,
            'value' => $value,
            'status' => $status,
        ]);

        return $obj->save();
    }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question:
Permission to consult ACCOUNTS registration information.

@param bool $manage_account_info

@throws \Moip\Exceptions\InvalidArgumentException

@return \Moip\Auth\Connect $this

public function setManageAccountInfo($manage_account_info)
    {
        if (!is_bool($manage_account_info)) {
            throw new InvalidArgumentException('$manage_account_info deve ser boolean, foi passado '.gettype($manage_account_info));
        }

        if ($manage_account_info === true) {
            $this->setScope(self::MANAGE_ACCOUNT_INFO);
        }

        return $this;
    }

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

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


Question:
Creates data provider instance with search query applied

@param array $params

@return ActiveDataProvider

public function search($params)
    {
        $query = Lang::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'default' => $this->default,
            'date_update' => $this->date_update,
            'date_create' => $this->date_create,
        ]);

        $query->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'local', $this->local])
            ->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }

public function setHost($host)
	{
		//Use the provided host or use the default
		if (empty($host))
		{
			throw new Apache_Solr_InvalidArgumentException('Host parameter is empty');
		}
		else
		{
			$this->_host = $host;
		}

		if ($this->_urlsInited)
		{
			$this->_initUrls();
		}
	}

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


Question: Constructs a JbcSrcJavaValue based on the Expression.

static JbcSrcJavaValue of(Expression expr, JbcSrcValueErrorReporter reporter) {
    if (expr instanceof SoyExpression) {
      return new JbcSrcJavaValue(
          expr,
          /* method= */ null,
          /* allowedType= */ ((SoyExpression) expr).soyType(),
          /* constantNull= */ false,
          /* error= */ false,
          reporter);
    }
    return new JbcSrcJavaValue(
        expr,
        /* method= */ null,
        /* allowedType= */ null,
        /* constantNull= */ false,
        /* error= */ false,
        reporter);
  }

@Nonnull
	public static <T1, T2> LBiObjFltPredicate<T1, T2> biObjFltPredicateFrom(Consumer<LBiObjFltPredicateBuilder<T1, T2>> buildingFunction) {
		LBiObjFltPredicateBuilder builder = new LBiObjFltPredicateBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

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


Question: ****** string validation ******

function (v, p) {
      if (typeof v !== 'string')
        return true;
      var pattern, modifiers;
      if (typeof p === 'string')
        pattern=p;
      else {
        pattern=p[0];
        modifiers=p[1];
      }
      var regex = new RegExp(pattern, modifiers);
      return regex.test(v);
    }

private function parseRequiredValue($name, array $input)
    {
        if (isset($input[$name])) {
            return $input[$name];
        }

        throw new Exception(sprintf("'%s' is required.", $name));
    }

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


Question: // Configure NSX.

func (api *SystemAPI) ConfigureNsx(nsxConfigSpec *NsxConfigurationSpec) (task *Task, err error) {
	body, err := json.Marshal(nsxConfigSpec)
	if err != nil {
		return
	}

	res, err := api.client.restClient.Post(
		api.getEndpointUrl("configure-nsx"),
		"application/json",
		bytes.NewReader(body),
		api.client.options.TokenOptions)
	if err != nil {
		return
	}
	defer res.Body.Close()

	task, err = getTask(getError(res))
	return
}

public static xen_health_monitor[] get_filtered(nitro_service service, String filter) throws Exception
	{
		xen_health_monitor obj = new xen_health_monitor();
		options option = new options();
		option.set_filter(filter);
		xen_health_monitor[] response = (xen_health_monitor[]) obj.getfiltered(service, option);
		return response;
	}

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


Question:
Sets the active point to a new node, edge, length tripple.

@param node
@param edge
@param length

void setPosition(Node<T, S> node, Edge<T, S> edge, int length) {
        activeNode = node;
        activeEdge = edge;
        activeLength = length;
    }

def create_node(**kwargs):
    '''

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

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

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

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

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

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

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

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

    return {}

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


Question:
Flash only some of the input to the session.

@param  {*} keys

function (keys) {
            keys = Array.isArray(keys) ? keys : {};

            return self.input.flash('except', keys);
        }

public function getParameter( $parameter )
    {

        self::isParameterAllowed( $parameter );

        $value = $this->query(new Raw("SHOW {$parameter}"))->fetch( Result::FETCH_SINGLE );

        return ( $value === 'true' or $value === 'false' )
            ? \Bond\boolval( $value )
            : $value;

    }

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


Question:
Callback for the incoming data from the stream

@private

function handleIncomingMessage(data) {
		var message;
		reader.parse(data, initPending);
		initPending = false;
		while (!reader.isEmpty()) {
			message = reader.pop();
			// console.log("IN MESSAGE: " + inspect(message));
			// Check if there are listeners attached to the event
			// otherwise falls back to the default handler
			if (that.listeners(message.verb).length) {
				handlers[message.verb](message);
			} else {
				defHandlers[message.verb].call(that, message);
			}
		}
	}

func (s *syntheticByteStream) Read(p []byte) (int, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	start := s.offset
	end := start + int64(len(p))
	var err error
	if end >= s.size {
		err = io.EOF
		end = s.size
	}

	for idx := start; idx < end; idx++ {
		p[idx-start] = s.factory(idx)
	}

	s.offset = end

	return int(end - start), err
}

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


Question:
Convert all rows of the ResultSet to a Map. The keys of the Map are property names transformed from column names.
@param rs	the result set
@return	A list of Map representations of all the rows in the result set
@throws SQLException

public List<Map<String, Object>> convertAllToMaps(ResultSet rs) throws SQLException{
		return convertAllToMaps(rs, null);
	}

@Override
	protected List<OUT> executeOnCollections(List<IN1> inputData1, List<IN2> inputData2, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception {
		CrossFunction<IN1, IN2, OUT> function = this.userFunction.getUserCodeObject();

		FunctionUtils.setFunctionRuntimeContext(function, ctx);
		FunctionUtils.openFunction(function, this.parameters);

		ArrayList<OUT> result = new ArrayList<OUT>(inputData1.size() * inputData2.size());

		TypeSerializer<IN1> inSerializer1 = getOperatorInfo().getFirstInputType().createSerializer(executionConfig);
		TypeSerializer<IN2> inSerializer2 = getOperatorInfo().getSecondInputType().createSerializer(executionConfig);
		TypeSerializer<OUT> outSerializer = getOperatorInfo().getOutputType().createSerializer(executionConfig);

		for (IN1 element1 : inputData1) {
			for (IN2 element2 : inputData2) {
				IN1 copy1 = inSerializer1.copy(element1);
				IN2 copy2 = inSerializer2.copy(element2);
				OUT o = function.cross(copy1, copy2);
				result.add(outSerializer.copy(o));
			}
		}

		FunctionUtils.closeFunction(function);
		return result;
	}

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


Question:
Generates a textarea
@param  array $options
@param  string $currentValue (Optional)
@return string

protected function generateTextarea($options, $currentValue = null)
    {
        $value = is_null($currentValue) ? $options['value'] : $currentValue;

        unset($options['value']);
        unset($options["type"]);

        return sprintf('<textarea %s>%s</textarea>', $this->arrayToHtmlAttributes($options), stripslashes($value));
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
删除自定义(个性化)菜单

@since 0.0.1
@return {boolean}
@example \Yii::$app->wechat->deleteMenu();

public function deleteMenu() {
		$data = $this->getData('/cgi-bin/menu/delete', [
			'access_token' => $this->getAccessToken(),
		]);

		return $this->errcode == 0 && WechatMenu::deleteAll(['appid' => $this->app->appid]);
	}

func (menu *Menu) HandleReply(reply CommandResponse) {

	for k, v := range menu.WaitingResponses {
		if v.ID != reply.ID {
			continue
		}
		Log.Print("MENU(", menu.TargetID, ")::Handling Reply", reply)
		removeAt := func(k int) {
			if len(menu.WaitingResponses) > 1 {
				menu.WaitingResponses = menu.WaitingResponses[:k+copy(menu.WaitingResponses[k:], menu.WaitingResponses[k+1:])]
			} else {
				menu.WaitingResponses = []*Command{}
			}
		}
		defer removeAt(k)

		if menu.TargetID == 0 && v.Action == "create" {
			//Assume we have a reply to action:create
			if reply.Result.TargetID != 0 {
				menu.TargetID = reply.Result.TargetID
				Log.Print("Received TargetID", "\nSetting Ready State")
				menu.Ready = true
			}
			for i, _ := range menu.CommandQueue {
				menu.CommandQueue[i].TargetID = menu.TargetID
				menu.Send(menu.CommandQueue[i])
			}
			// Reinitialize empty command queue, and allow gc.
			menu.CommandQueue = []*Command{}
			return
		}

		if v.Action == "call" && v.Method == "set_application_menu" {
			Log.Print("Received reply to set_application_menu", "Setting Menu Displayed to True")
			menu.setDisplayed(true)
		}

	}
}

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


Question:
@param string $template
@param Address|Address[] $recipients
@param Address|null $sender

@return self

public static function create(string $template, $recipients, Address $sender = null)
    {
        $email = new static($template);

        $recipients = is_array($recipients) ? $recipients : [$recipients];
        foreach ($recipients as $recipient) {
            $email->addRecipient($recipient);
        }

        if (null !== $sender) {
            $email->setSender($sender);
        }

        return $email;
    }

func (s *BatchPutMessageInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "BatchPutMessageInput"}
	if s.ChannelName == nil {
		invalidParams.Add(request.NewErrParamRequired("ChannelName"))
	}
	if s.ChannelName != nil && len(*s.ChannelName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ChannelName", 1))
	}
	if s.Messages == nil {
		invalidParams.Add(request.NewErrParamRequired("Messages"))
	}
	if s.Messages != nil {
		for i, v := range s.Messages {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Messages", i), err.(request.ErrInvalidParams))
			}
		}
	}

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

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


Question: A method that takes the ShellCheck summary and parses any violations found

def parse_files(shellcheck_summary)
      shellcheck_summary.each do |element|
        file = element[:file]
        @files.add(file)
        level = element[:level]

        message = format_violation(file, element)

        if level == 'error'
          @error_count += 1
          fail(message, sticky: false)
        else
          if level == 'warning'
            @warning_count += 1
          elsif level == 'info'
            @info_count += 1
          else
            @style_count += 1
          end
          warn(message, sticky: false)
        end
      end
    end

func (psh PartSetHeader) ValidateBasic() error {
	if psh.Total < 0 {
		return errors.New("Negative Total")
	}
	// Hash can be empty in case of POLBlockID.PartsHeader in Proposal.
	if err := ValidateHash(psh.Hash); err != nil {
		return errors.Wrap(err, "Wrong Hash")
	}
	return nil
}

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


Question: Collect (and optionally limit) all unique pivot values.

function pivotKeys(key, limit, pulse) {
  var map = {},
      list = [];

  pulse.visit(pulse.SOURCE, function(t) {
    var k = key(t);
    if (!map[k]) {
      map[k] = 1;
      list.push(k);
    }
  });

  // TODO? Move this comparator to vega-util?
  list.sort(function(u, v) {
    return (u<v||u==null) && v!=null ? -1
      : (u>v||v==null) && u!=null ? 1
      : ((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))!==u && v===v ? -1
      : v!==v && u===u ? 1 : 0;
  });

  return limit ? list.slice(0, limit) : list;
}

public ProjectModel getByName(String name)
    {
        return getUnique(getQuery().getRawTraversal().has(ProjectModel.NAME, name));
    }

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


Question:
Get current upload chunk as string
@return string Chunk body

public function getChunkString()
    {
        if (!$this->curChunkSize) {
            return false;
        }
        $chunk = $this->read($this->curChunkSize);
        $this->curChunkSize = null;
        return $chunk;
    }

public function writeTextualData($key, $value)
    {
        $this->buffer->startChunk("tEXt");
        $this->buffer->writeString($key);
        $this->buffer->writeUInt8(0);
        $this->buffer->writeString($value);
        $this->buffer->endChunk();
    }

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


Question:
Build a sanitized, authenticated metadata hash for the given request

 @param [Hash] metadata A base metadata hash to build from
 @return [Hash] The compiled metadata hash that is ready to be transported over the wire

def build_metadata(metadata = {})
      unless opts[:password].empty?
        username = opts.fetch(:username, 'grpc').to_s
        username = username.empty? ? '' : "#{username}:"
        auth_string = Base64.encode64("#{username}#{opts[:password]}")
        metadata[:authorization] = "Basic #{auth_string}".tr("\n", '')
      end
      metadata
    end

def read_meta(self, **kwargs):
        '''

        '''
        # TODO Try to rewrite the code to be more logical
        # The reason the equivalent statement is not in the read_data method
        # above is because self.readdata_kwargs are passed
        # as **kwargs to the read_data function.
        if 'channel_naming' in self.readdata_kwargs:
            kwargs['channel_naming'] = self.readdata_kwargs['channel_naming']
        meta = parse_fcs(self.datafile,
                         reformat_meta=True,
                         meta_data_only=True, **kwargs)
        return meta

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


Question:
// processEvents pulls messages off the inboundEvents channel.
// Takes the events which were pulled off the bus, converts them to Event, and
// places onto the parsedEvents channel.

func processEvents(inboundEvents chan []byte, parsedEvents chan *Event) {
	go func(inboundEvents chan []byte, parsedEvents chan *Event) {
		for event := range inboundEvents {
			var e Event
			json.Unmarshal(event, &e)
			parsedEvents <- &e
		}
	}(inboundEvents, parsedEvents)
}

func (fw *Firewaller) startMachine(tag names.MachineTag) error {
	machined := &machineData{
		fw:           fw,
		tag:          tag,
		unitds:       make(map[names.UnitTag]*unitData),
		ingressRules: make([]network.IngressRule, 0),
		definedPorts: make(map[names.UnitTag]portRanges),
	}
	m, err := machined.machine()
	if params.IsCodeNotFound(err) {
		logger.Debugf("not watching %q", tag)
		return nil
	} else if err != nil {
		return errors.Annotate(err, "cannot watch machine units")
	}
	manual, err := m.IsManual()
	if err != nil {
		return errors.Trace(err)
	}
	if manual {
		// Don't track manual machines, we can't change their ports.
		logger.Debugf("not watching manual %q", tag)
		return nil
	}
	unitw, err := m.WatchUnits()
	if err != nil {
		return errors.Trace(err)
	}
	// XXX(fwereade): this is the best of a bunch of bad options. We've started
	// the watch, so we're responsible for it; but we (probably?) need to do this
	// little dance below to update the machined data on the fw loop goroutine,
	// whence it's usually accessed, before we start the machined watchLoop
	// below. That catacomb *should* be the only one responsible -- and it *is*
	// responsible -- but having it in the main fw catacomb as well does no harm,
	// and greatly simplifies the code below (which would otherwise have to
	// manage unitw lifetime and errors manually).
	if err := fw.catacomb.Add(unitw); err != nil {
		return errors.Trace(err)
	}
	select {
	case <-fw.catacomb.Dying():
		return fw.catacomb.ErrDying()
	case change, ok := <-unitw.Changes():
		if !ok {
			return errors.New("machine units watcher closed")
		}
		fw.machineds[tag] = machined
		err = fw.unitsChanged(&unitsChange{machined, change})
		if err != nil {
			delete(fw.machineds, tag)
			return errors.Annotatef(err, "cannot respond to units changes for %q", tag)
		}
	}

	err = catacomb.Invoke(catacomb.Plan{
		Site: &machined.catacomb,
		Work: func() error {
			return machined.watchLoop(unitw)
		},
	})
	if err != nil {
		delete(fw.machineds, tag)
		return errors.Trace(err)
	}

	// register the machined with the firewaller's catacomb.
	err = fw.catacomb.Add(machined)
	if err == nil {
		logger.Debugf("started watching %q", tag)
	}
	return err
}

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


Question: // handleZeroArgs handles the case where there are no positional args.

func (c *configCommand) handleZeroArgs() error {
	// If reset is empty we're getting configuration
	if len(c.reset) == 0 {
		c.action = c.getConfig
	}
	// Otherwise we're going to reset args.
	return nil
}

protected function getParameter(string $name)
    {
        if (!$this->container->has('parameter_bag')) {
            throw new ServiceNotFoundException('parameter_bag', null, null, [], sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', \get_class($this)));
        }

        return $this->container->get('parameter_bag')->get($name);
    }

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


Question:
Возвращает клиентский сервис OAuth 2.0.

@return \Steein\SDK\Authentication\OAuth2Client

public function getOAuth2Client()
    {
        if (!$this->oAuth2Client instanceof OAuth2Client) {
            $app = $this->getApp();
            $client = $this->getClient();
            $this->oAuth2Client = new OAuth2Client($app, $client, $this->getDefaultApiVersion());
        }

        return $this->oAuth2Client;
    }

def get_sdk_download_stream(self, rest_api_id,
                                api_gateway_stage=DEFAULT_STAGE_NAME,
                                sdk_type='javascript'):
        # type: (str, str, str) -> file

        response = self._client('apigateway').get_sdk(
            restApiId=rest_api_id, stageName=api_gateway_stage,
            sdkType=sdk_type)
        return response['body']

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


Question: UnitType Parsing

function parse(text) {
  const compCount = U.countComponents(text);
  if (!compCount) {
    return; // undefined
  }

  const len = text.length,
    components = new Array(compCount);

  let multiplier = 1,
    pos = 0,
    nextComp = 0;

  //console.log(`parsing unit ${text}:`);
  while (pos < len) {
    let ch = text.charCodeAt(pos);

    if (ch === U.slash) {
      multiplier *= -1;
      pos++;
    } else if (ch === U.asterisk) {
      pos++;
    }

    let s = pos;
    for (; pos < len; pos++) {
      ch = text.charCodeAt(pos);

      if (!U.isLetter(ch)) {
        break;
      }
    }

    const name = text.substring(s, pos);
    const unitType = bySid[name];
    if (!unitType) {
      throw new Error(`Unknown unit type "${name}" in "${text}"`);
    }

    if (pos < len && text.charCodeAt(pos) === U.caret) {
      pos++;
    }

    s = pos;
    if (pos < len && text.charCodeAt(pos) === U.minus) {
      pos++;
    }

    while (pos < len && U.isDigit(text.charCodeAt(pos))) {
      pos++;
    }

    const degreeText = text.substring(s, pos);

    let degree;
    if (!degreeText.length) {
      degree = 1;
    } else {
      degree = Number.parseInt(degreeText);
      if (isNaN(degree)) {
        throw new Error(`Illegal degree "${degreeText}" in "${text}"`);
      }
    }

    degree *= multiplier;

    let ci = 0;
    for (; ci < nextComp; ci++) {
      const comp = components[ci];

      if (comp.unitType === unitType) {
        comp.degree += degree;
        break;
      }
    }

    if (ci >= nextComp) {
      components[nextComp++] = new UnitTypeDegree(unitType, degree);
    }

    //console.log(` + ${name} ==> ${degree}`);
  }

  components.length = nextComp;
  return parseComponents(components);
}

public ProxyDataSourceBuilder logSlowQueryByJUL(long thresholdTime, TimeUnit timeUnit) {
        return logSlowQueryByJUL(thresholdTime, timeUnit, null, null);
    }

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


Question: Get an **insert** message.

def insert(collection_name, docs, check_keys, safe, last_error_args):

    data = __ZERO
    data += bson._make_c_string(collection_name)
    bson_data = "".join([bson.BSON.encode(doc, check_keys) for doc in docs])
    if not bson_data:
        raise InvalidOperation("cannot do an empty bulk insert")
    data += bson_data
    if safe:
        (_, insert_message) = __pack_message(2002, data)
        (request_id, error_message) = __last_error(last_error_args)
        return (request_id, insert_message + error_message)
    else:
        return __pack_message(2002, data)

func StringsEqual(expected string, other string, errMsg string) error {
	if expected != other {
		if errMsg == "" {
			errMsg = fmt.Sprintf("expected %s found %s", expected, other)
		}
		return NewViolation(errMsg)
	}
	return nil
}

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


Question: // verticalScroll moves the cursor position vertically

func verticalScroll(state *Peco, l *BasicLayout, p PagingRequest) bool {
	// Before we move, on which line were we located?
	loc := state.Location()
	lineBefore := loc.LineNumber()
	lineno := lineBefore

	if pdebug.Enabled {
		defer func() {
			pdebug.Printf("currentLine changed from %d -> %d", lineBefore, state.Location().LineNumber())
		}()
	}

	buf := state.CurrentLineBuffer()
	lcur := buf.Size()

	defer func() {
		for _, lno := range []int{lineBefore, loc.LineNumber()} {
			if oldLine, err := buf.LineAt(lno); err == nil {
				oldLine.SetDirty(true)
			}
		}
	}()

	lpp := l.linesPerPage()
	if l.list.sortTopDown {
		switch p.Type() {
		case ToLineAbove:
			lineno--
		case ToLineBelow:
			lineno++
		case ToScrollPageDown:
			lineno += lpp
			if loc.Page() == loc.MaxPage()-1 && lcur < lineno && (lcur-lineBefore) < lpp {
				lineno = lcur - 1
			}
		case ToScrollPageUp:
			lineno -= lpp
		case ToLineInPage:
			lineno = loc.PerPage()*(loc.Page()-1) + p.(JumpToLineRequest).Line()
		case ToScrollFirstItem:
			lineno = 0
		case ToScrollLastItem:
			lineno = lcur - 1
		}
	} else {
		switch p.Type() {
		case ToLineAbove:
			lineno++
		case ToLineBelow:
			lineno--
		case ToScrollPageDown:
			lineno -= lpp
		case ToScrollPageUp:
			lineno += lpp
		case ToLineInPage:
			lineno = loc.PerPage()*(loc.Page()-1) - p.(JumpToLineRequest).Line()
		}
	}

	if lineno < 0 {
		if lcur > 0 {
			// Go to last page, if possible
			lineno = lcur - 1
		} else {
			lineno = 0
		}
	} else if lcur > 0 && lineno >= lcur {
		lineno = 0
	}

	// XXX DO NOT RETURN UNTIL YOU SET THE LINE NUMBER HERE
	loc.SetLineNumber(lineno)

	// if we were in range mode, we need to do stuff. otherwise
	// just bail out
	r := state.SelectionRangeStart()
	if !r.Valid() {
		return true
	}

	sel := state.Selection()
	if l.list.sortTopDown {
		if loc.LineNumber() < r.Value() {
			for lineno := loc.LineNumber(); lineno <= r.Value(); lineno++ {
				if line, err := buf.LineAt(lineno); err == nil {
					sel.Add(line)
				}
			}
			switch {
			case r.Value() <= lineBefore:
				for lineno := r.Value(); lineno <= lcur && lineno < lineBefore; lineno++ {
					if line, err := buf.LineAt(lineno); err == nil {
						sel.Remove(line)
					}
				}
			case lineBefore < loc.LineNumber():
				for lineno := lineBefore; lineno < loc.LineNumber(); lineno++ {
					if line, err := buf.LineAt(lineno); err == nil {
						sel.Remove(line)
					}
				}
			}
		} else {
			for lineno := r.Value(); lineno <= lcur && lineno <= loc.LineNumber(); lineno++ {
				if line, err := buf.LineAt(lineno); err == nil {
					sel.Add(line)
				}
			}

			switch {
			case lineBefore <= r.Value():
				for lineno := lineBefore; lineno < r.Value(); lineno++ {
					if line, err := buf.LineAt(lineno); err == nil {
						sel.Remove(line)
					}
				}
			case loc.LineNumber() < lineBefore:
				for lineno := loc.LineNumber(); lineno <= lineBefore; lineno++ {
					if line, err := buf.LineAt(lineno); err == nil {
						sel.Remove(line)
					}
				}
			}
		}
	}

	return true
}

function scrollMagicUndefined() {
    var error = "ScrollMagic is not available. Either the bower package is missing or your app is in Fastboot Mode.";

    function throwError() {
      throw Error(error);
    }

    this.Scene = throwError();
    this.Controller = throwError();

    throwError();
  }

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


Question:
Get Branch

@return array<GitHubBranch>

public function getBranch($owner, $repo, $branch)
	{
		$data = array();

		return $this->client->request("/repos/$owner/$repo/branches/$branch", 'GET', $data, 200, 'GitHubBranch', true);
	}

func (i *Index) Chart(name string) (*repo.ChartVersion, error) {
	c, ok := i.charts[name]
	if !ok {
		return nil, errors.New("no such chart")
	}
	return c, nil
}

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


Question:
Gets the context-relative URL to a web page.
Parameters should already be URL encoded but not yet XML encoded.

public String getURL(WebPage page, Object optParam) throws IOException, SQLException {
		List<String> finishedParams=new SortedArrayList<>();
		StringBuilder SB = new StringBuilder();
		SB.append(page.getURLPath());
		boolean alreadyAppended=appendParams(SB, optParam, finishedParams, false);
		alreadyAppended=appendParams(SB, page.getURLParams(this), finishedParams, alreadyAppended);

		/*alreadyAppended=*/appendSettings(finishedParams, alreadyAppended, SB);

		return SB.toString();
	}

public static function EscapeHtmlUri( $item )
	{
		if ( $item instanceof Undefined )
		    return "";

	    $value = $item . "";
	    $result = "";

	    for ( $i = 0; $i < strlen( $value ); $i++ )
	    {
			$num = ord( $value[ $i ] );

		    if ( $num >= 0x20 && $num < 0x7f )
			   $result .= chr( $num );
		    else
		    {
			   $num2 = $num / 0x10;
			   $num3 = $num % 0x10;
			   $ch =   $num2 >= 10 ? chr( 0x41 + ( $num2 - 10 ) ) : chr( 0x30 + $num2 );
			   $ch2 =  $num3 >= 10 ? chr( 0x41 + ( $num3 - 10 ) ) : chr( 0x30 + $num3 );
			   $result .= '%';
			   $result .= $ch;
			   $result .= $ch2;
		    }
		}
		return $result;
	}

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


Question:
//------------------------------------------------------------
// Validator methods

func (gv *Validator) Validator() validator.Validator {
	address := gv.PublicKey.GetAddress()
	return validator.Validator{
		Address:   &address,
		PublicKey: gv.PublicKey,
		Power:     uint64(gv.Amount),
	}
}

protected static function isValidSetter(\ReflectionClass &$reflection, $name)
	{
		if (!$reflection->hasMethod($name))
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: no setter %s.', $reflection->getName(), $name)
			);
		}
		$setter = $reflection->getMethod($name);
		if (!$setter->isPublic())
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s is not public.', $reflection->getName(), $name)
			);
		}
		if ($setter->getNumberOfParameters() < 1)
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s should accept at least one parameter.', $reflection->getName(), $name)
			);
		}
		if ($setter->getNumberOfRequiredParameters() > 1)
		{
			throw new \LogicException(
				sprintf('Invalid metadata for %s: setter %s requires too many parameters.', $reflection->getName(), $name)
			);
		}
		return true;
	}

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


Question:
Read out a file, using syntax highlighting if detected.

        Lines and linespans are supported by adding '#L12' or '#L12-14' etc to the end of the filename.

async def jsk_cat(self, ctx: commands.Context, argument: str):

        match = self.__cat_line_regex.search(argument)

        if not match:  # should never happen
            return await ctx.send("Couldn't parse this input.")

        path = match.group(1)

        line_span = None

        if match.group(2):
            start = int(match.group(2))
            line_span = (start, int(match.group(3) or start))

        if not os.path.exists(path) or os.path.isdir(path):
            return await ctx.send(f"`{path}`: No file by that name.")

        size = os.path.getsize(path)

        if size <= 0:
            return await ctx.send(f"`{path}`: Cowardly refusing to read a file with no size stat"
                                  f" (it may be empty, endless or inaccessible).")

        if size > 50 * (1024 ** 2):
            return await ctx.send(f"`{path}`: Cowardly refusing to read a file >50MB.")

        try:
            with open(path, "rb") as file:
                paginator = WrappedFilePaginator(file, line_span=line_span, max_size=1985)
        except UnicodeDecodeError:
            return await ctx.send(f"`{path}`: Couldn't determine the encoding of this file.")
        except ValueError as exc:
            return await ctx.send(f"`{path}`: Couldn't read this file, {exc}")

        interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author)
        await interface.send_to(ctx)

public function run(string $file, Node $node): array
    {
        $hints = [];
        $case_conds = [];

        foreach ($node->children as $case) {
            $cond = $case->children['cond'];
            foreach ($case_conds as $case_cond) {
                if ($this->isEqualsWithoutLineno($case_cond, $cond)) {
                    $hints[] = new Hint(
                        self::HINT_TYPE,
                        self::HINT_MESSAGE,
                        $file,
                        $case->lineno,
                        self::HINT_LINK
                    );
                }
            }
            $case_conds[] = $cond;
        }

        return $hints;
    }

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


Question:
Returns new collection without the given field names

@param string[] $names
@return ApacheSolrFacetCollection

public function exclude(array $names)
    {
        $filtered = clone $this;
        foreach ($names as $name) {
            unset($filtered[$name]);
        }
        return $filtered;
    }

public List<Object> getParameters() {
        List<Object> parameters = new ArrayList<Object>(getValues());
        if( this.dateValues != null && ! this.dateValues.isEmpty() ) {
           parameters.addAll(this.dateValues);
        }
        if( parameters.isEmpty() ) {
            return parameters;
        }
        return parameters;
    }

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


Question: function to calculate points on an circle about dec,dip with angle alpha

def circ(dec, dip, alpha):

    rad = old_div(np.pi, 180.)
    D_out, I_out = [], []
    dec, dip, alpha = dec * rad, dip * rad, alpha * rad
    dec1 = dec + old_div(np.pi, 2.)
    isign = 1
    if dip != 0:
        isign = (old_div(abs(dip), dip))
    dip1 = (dip - isign * (old_div(np.pi, 2.)))
    t = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    v = [0, 0, 0]
    t[0][2] = np.cos(dec) * np.cos(dip)
    t[1][2] = np.sin(dec) * np.cos(dip)
    t[2][2] = np.sin(dip)
    t[0][1] = np.cos(dec) * np.cos(dip1)
    t[1][1] = np.sin(dec) * np.cos(dip1)
    t[2][1] = np.sin(dip1)
    t[0][0] = np.cos(dec1)
    t[1][0] = np.sin(dec1)
    t[2][0] = 0
    for i in range(101):
        psi = float(i) * np.pi / 50.
        v[0] = np.sin(alpha) * np.cos(psi)
        v[1] = np.sin(alpha) * np.sin(psi)
        v[2] = np.sqrt(abs(1. - v[0]**2 - v[1]**2))
        elli = [0, 0, 0]
        for j in range(3):
            for k in range(3):
                elli[j] = elli[j] + t[j][k] * v[k]
        Dir = cart2dir(elli)
        D_out.append(Dir[0])
        I_out.append(Dir[1])
    return D_out, I_out

def get_param(self):

        cycle_progress = self.event_index / self.cycle_size
        return self.start_value + ((self.end_value - self.start_value) / 2) * (1 - math.cos(math.pi * cycle_progress))

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


Question:
@EXT\Route("/roles/list", name="platform_roles_list")
@EXT\Template("ClarolineCoreBundle:Administration/Roles:roleList.html.twig")

@return array

public function roleListAction()
    {
        $roles = $this->roleManager->getAllPlatformRoles();
        $counts = [];

        foreach ($roles as $role) {
            $counts[$role->getName()] = $this->roleManager->countUsersByRoleIncludingGroup($role);
        }

        return array('roles' => $roles, 'counts' => $counts);
    }

public function showAction($folderId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Folder $folder */
        $folder = $em->getRepository('VictoireMediaBundle:Folder')->getFolder($folderId);
        $folders = $em->getRepository('VictoireMediaBundle:Folder')->getAllFolders();

        $sub = new Folder();
        $sub->setParent($folder);
        $subForm = $this->createForm(FolderType::class, $sub, ['folder' => $sub]);
        $editForm = $this->createForm(FolderType::class, $folder, ['folder' => $folder]);

        return $this->render('@VictoireMedia/Folder/show.html.twig', [
            'mediamanager' => $this->get('victoire_media.media_manager'),
            'subform'      => $subForm->createView(),
            'editform'     => $editForm->createView(),
            'folder'       => $folder,
            'folders'      => $folders,
        ]);
    }

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


Question: // SetContentType sets the ContentType field's value.

func (s *InvokeEndpointInput) SetContentType(v string) *InvokeEndpointInput {
	s.ContentType = &v
	return s
}

public <T> Message body(T body, Charset charset) {
        messageWriter.writeBody(body, charset);
        return this;
    }

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


Question:
Define your route model bindings, pattern filters, etc.

@param  \Illuminate\Routing\Router  $router
@return void

public function boot(Router $router)
	{
		//============
		//== ASSETS ==
		//============
		$this->loadViewsFrom(__DIR__.'/../resources/views', static::PACKAGE_NAME);
		$this->loadViewsFrom(__DIR__.'/../resources/admin_views', static::PACKAGE_NAME . '_admin');

		$this->loadTranslationsFrom('/', 'common');

		$this->publishes([
			__DIR__.'/../database/migrations/' => database_path('/migrations')
		], 'migrations');

		$this->publishes([
			__DIR__.'/../assets/' => public_path('vendor/common'),
		], 'public');

		$this->publishes([
			__DIR__.'/../config/' . static::PACKAGE_NAME . '.php' => config_path('neonbug/' . static::PACKAGE_NAME . '.php'),
		]);

		//============
		//== ROUTES ==
		//============
		$language = App::make('Language');
		$locale = ($language == null ? Config::get('app.default_locale') : $language->locale);

		$admin_language = App::make('AdminLanguage');
		$admin_locale = ($admin_language == null ? Config::get('app.admin_default_locale') : $admin_language->locale);

		View::composer('common::admin', function($view) use ($router)
		{
			$menu_items = [];

			$routes = $router->getRoutes();
			foreach ($routes as $route)
			{
				if (stripos($route->getName(), '::admin::') !== false)
				{
					if (!in_array('admin.menu', $route->middleware())) continue;
					if (!in_array('GET', $route->getMethods())) continue; //only list routes for GET
					if (sizeof($route->parameterNames()) > 0) continue;

					//check for required role
					$action = $route->getAction();
					if (!array_key_exists('role', $action)) continue;

					$required_role = $action['role'];
					if ($required_role != '*')
					{
						$roles = Auth::user()->roles;
						$has_role = false;
						foreach ($roles as $role)
						{
							if ($role->id_role == 'admin' || /* admin has access to everything */
								$role->id_role == $required_role)
							{
								$has_role = true;
								break;
							}
						}
						if (!$has_role) continue;
					}

					//transform the route into menu item
					$arr = explode('::', $route->getName());
					if (!array_key_exists($arr[0], $menu_items))
					{
						$menu_items[$arr[0]] = [
							'title' => $arr[0],
							'icon' => (array_key_exists('menu.icon', $route->getAction()) ?
								$route->getAction()['menu.icon'] : 'arrow right'),
							'weight' => (array_key_exists('weight', $route->getAction()) ?
								$route->getAction()['weight'] : 5),
							'items' => []
						];
					}
					$menu_items[$arr[0]]['items'][] = [
						'route' => $route->getName(),
						'title' => $arr[2]
					];
				}
			}

			$view->menu_items = array_values($menu_items);

			$view->compact_admin_menu = Config::get('app.compact_admin_menu', false);

			usort($view->menu_items, function($a, $b) {
				if ($a['weight'] < $b['weight']) return -1;
				if ($a['weight'] > $b['weight']) return 1;
				return 0;
			});

			$view->withEncryptedCsrfToken(Crypt::encrypt(csrf_token()));
			$view->withUser(Auth::user());
		});

		view()->share('formatter', App::make('\Neonbug\Common\Helpers\FormatterHelper'));

		//admin
		$router->get('admin', function() { return redirect(route('admin-home')); });
		$router->group(['prefix' => $admin_locale . '/admin'], function($router)
		{
			$auth_controller = '\Neonbug\Common\Http\Controllers\Auth\AuthController';

			$router->get('login',  ['as' => 'admin-login',  'uses' => $auth_controller . '@getLogin']);
			$router->post('login', [                        'uses' => $auth_controller . '@postLogin']);
			$router->get('logout', ['as' => 'admin-logout', 'uses' => $auth_controller . '@getLogout']);

			$router->post('check-token', ['as' => 'admin-check-token', function() {
				return [ 'success' => true, 'token' => csrf_token() ];
			}]);
			$router->get('token', ['as' => 'admin-token', function() {
				return [ 'token' => csrf_token(), 'encrypted_token' => Crypt::encrypt(csrf_token()) ];
			}]);
		});

		$router->group(['prefix' => $admin_locale . '/admin', 'middleware' => ['auth.admin']], function($router)
		{
			$router->group(['role' => '*'], function($router) {
				$router->get('/', ['as' => 'admin-home',
					'uses' => '\Neonbug\Common\Http\Controllers\AdminController@index']);
				$router->get('/dashboard/analytics-data', ['as' => 'admin-dashboard-analytics-data',
					'uses' => '\Neonbug\Common\Http\Controllers\AdminController@getAnalyticsData']);
			});
		});

		//============
		//== EVENTS ==
		//============
		Event::subscribe('\Neonbug\Common\Handlers\Events\DropdownEventHandler');
		Event::subscribe('\Neonbug\Common\Handlers\Events\OrdEventHandler');
		Event::subscribe('\Neonbug\Common\Handlers\Events\PasswordHashEventHandler');
		Event::subscribe('\Neonbug\Common\Handlers\Events\SlugEventHandler');

		parent::boot($router);
	}

func (s *GetRouteOutput) SetRequestModels(v map[string]*string) *GetRouteOutput {
	s.RequestModels = v
	return s
}

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


Question:
Constructs a ExecutionContextContext

        :returns: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext
        :rtype: twilio.rest.studio.v1.flow.execution.execution_context.ExecutionContextContext

def get(self):

        return ExecutionContextContext(
            self._version,
            flow_sid=self._solution['flow_sid'],
            execution_sid=self._solution['execution_sid'],
        )

public void marshall(EC2InstanceDetails eC2InstanceDetails, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(eC2InstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getInstanceType(), INSTANCETYPE_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getPlatform(), PLATFORM_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getTenancy(), TENANCY_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(eC2InstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: //NewImage 回复图片消息

func NewImage(mediaID string) *Image {
	image := new(Image)
	image.Image.MediaID = mediaID
	return image
}

public function preview()
	{
		$strPreview = '

' . $this->label . '

';

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

 Articletitle2

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

		$strPreview .= '

Change selection

' . $this->description . '

';

		return $strPreview;
	}

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


Question:
Returns a message in the appropriate language.
@access private
@return string

private function Lang($key) {
    if(count($this->language) < 1) {
      $this->SetLanguage('en'); // set the default language
    }

    if(isset($this->language[$key])) {
      return $this->language[$key];
    } else {
      return 'Language string failed to load: ' . $key;
    }
  }

protected function detectLanguage($lang, $request)
    {
        $lang = $this->setLanguagInSession($lang);

        $this->sessionValues = $_SESSION[self::SESSION_PARAMETER_LANGUAGE_COMPONENT];

        $this->checkForceRedirect($lang, $request);
    }

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


Question: gets a reference to the machines object

def machines(self):
        """"""
        if self._resources is None:
            self.__init()
        if "machines" in self._resources:
            url = self._url + "/machines"
            return _machines.Machines(url,
                                      securityHandler=self._securityHandler,
                                      initialize=False,
                                      proxy_url=self._proxy_url,
                                      proxy_port=self._proxy_port)
        else:
            return None

public static xen_health_monitor[] get_filtered(nitro_service service, String filter) throws Exception
	{
		xen_health_monitor obj = new xen_health_monitor();
		options option = new options();
		option.set_filter(filter);
		xen_health_monitor[] response = (xen_health_monitor[]) obj.getfiltered(service, option);
		return response;
	}

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


Question:
Simple router which will map exact url pathname to a callback
@returns {ExactPath}
@constructor

function ExactPath() {

  /**
   * Uri to action::method mapping
   * @type {Object}
   */
  var mapping = {};

  /**
   * Resolve uri
   * @param request
   * @returns {*}
   */
  this.resolve = function (request) {
    var uri = request.url.split('?')[0];

    if (mapping[request.method] && mapping[request.method][uri]) {
      return decode.call(this, mapping[request.method][uri]);
    }
    return null;
  };

  /**
   * Add a route mapping
   * @param method
   * @param uri
   * @param callback
   * @returns {ExactPath}
   */
  this.addRoute = function (method, uri, callback) {
    method = method.toUpperCase();
    if (!mapping[method]) {
      mapping[method] = {};
    }
    mapping[method][uri] = callback;
    return this;
  };

  /**
   * Add route mapping for get http method
   * @param uri
   * @param callback
   * @returns {ExactPath}
   */
  this.get = function (uri, callback) {
    return this.addRoute('GET', uri, callback);
  };

  /**
   * Add route mapping for post http method
   * @param uri
   * @param callback
   * @returns {ExactPath}
   */
  this.post = function (uri, callback) {
    return this.addRoute('POST', uri, callback);
  };

  /**
   * Add route mapping for put http method
   * @param uri
   * @param callback
   * @returns {ExactPath}
   */
  this.put = function (uri, callback) {
    return this.addRoute('PUT', uri, callback);
  };

  /**
   * Add route mapping for delete http method
   * @param uri
   * @param callback
   * @returns {ExactPath}
   */
  this.delete = function (uri, callback) {
    return this.addRoute('DELETE', uri, callback);
  };

  return this;

  /**
   * Decode callback
   * @param callback
   * @returns {*}
   */
  function decode(callback) {
    if (typeof callback == 'function') {
      return callback;
    } else {
      var split = callback.split('::');
      var action = split[0];
      var method = split[1] || 'index';
      return {
        action: action,
        method: method,
        arguments: []
      };
    }
  }
}

public function get($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('GET', $pattern, $handler, $requirements, $defaults);
    }

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


Question:
This function returns the file info from the request data.

@param   inputData
The input data
@return  The file info

@Override
    protected FileInfo getFileInfoFromInputDataImpl(HTTPRequest inputData)
    {
        //get content
        Map<String,ContentPart<?>> contentPartsMap=this.getContentPartsAsMap(inputData);

        //get file info
        FileInfo fileInfo=null;
        ContentPart<?> contentPart=contentPartsMap.get(this.fileContentParameter);
        if(contentPart==null)
        {
            throw new FaxException("File info not provided.");
        }
        ContentPartType contentPartType=contentPart.getType();
        switch(contentPartType)
        {
            case FILE:
                File file=(File)contentPart.getContent();
                fileInfo=new FileInfo(file);
                break;
            case BINARY:
                byte[] data=(byte[])contentPart.getContent();

                //get file name
                String fileName=this.getContentPartAsString(contentPartsMap,this.fileNameParameter);

                fileInfo=new FileInfo(fileName,data);
                break;
            default:
                throw new FaxException("Unsupported content part type: "+contentPartType);
        }

        return fileInfo;
    }

public function output($image_type = null, $quality = null)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));

        $this->save(null, $image_type, $quality);
    }

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


Question:
Returns version of application

@return null|Version

private function getVersion(): ?Version
    {
        // Oops, unknown/empty path of a file who contains version
        if (empty($this->versionFilePath)) {
            throw EmptyVersionFilePathException::create();
        }

        // Oops, not readable/accessible file who contains version
        if (!is_readable($this->versionFilePath)) {
            throw UnreadableVersionFileException::create($this->versionFilePath);
        }

        $contents = file_get_contents($this->versionFilePath);

        return Version::fromString($contents);
    }

public function setVersionMapping(PropertyMetadata $mapping)
    {
        if ($mapping->type !== Type::INT && $mapping->type !== Type::DATE) {
            throw LockException::invalidVersionAttributeType($mapping->type);
        }

        $this->isVersioned      = true;
        $this->versionAttribute = $mapping->name;
    }

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


Question: InternalPureXbase.g:913:1: ruleOpSingleAssign returns [AntlrDatatypeRuleToken current=new AntlrDatatypeRuleToken()] : kw= '=' ;

public final AntlrDatatypeRuleToken ruleOpSingleAssign() throws RecognitionException {
        AntlrDatatypeRuleToken current = new AntlrDatatypeRuleToken();

        Token kw=null;

        	enterRule();

        try {
            // InternalPureXbase.g:919:2: (kw= '=' )
            // InternalPureXbase.g:920:2: kw= '='
            {
            kw=(Token)match(input,20,FOLLOW_2); if (state.failed) return current;
            if ( state.backtracking==0 ) {

              		current.merge(kw);
              		newLeafNode(kw, grammarAccess.getOpSingleAssignAccess().getEqualsSignKeyword());

            }

            }

            if ( state.backtracking==0 ) {

              	leaveRule();

            }
        }

            catch (RecognitionException re) {
                recover(input,re);
                appendSkippedTokens();
            }
        finally {
        }
        return current;
    }

protected function registerClassAliases()
    {
        $serviceAliases = [
            \Dingo\Api\Http\Request::class => \Dingo\Api\Contract\Http\Request::class,
            'api.dispatcher' => \Dingo\Api\Dispatcher::class,
            'api.http.validator' => \Dingo\Api\Http\RequestValidator::class,
            'api.http.response' => \Dingo\Api\Http\Response\Factory::class,
            'api.router' => \Dingo\Api\Routing\Router::class,
            'api.router.adapter' => \Dingo\Api\Contract\Routing\Adapter::class,
            'api.auth' => \Dingo\Api\Auth\Auth::class,
            'api.limiting' => \Dingo\Api\Http\RateLimit\Handler::class,
            'api.transformer' => \Dingo\Api\Transformer\Factory::class,
            'api.url' => \Dingo\Api\Routing\UrlGenerator::class,
            'api.exception' => [\Dingo\Api\Exception\Handler::class, \Dingo\Api\Contract\Debug\ExceptionHandler::class],
        ];

        foreach ($serviceAliases as $key => $aliases) {
            foreach ((array) $aliases as $alias) {
                $this->app->alias($key, $alias);
            }
        }
    }

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


Question: // SetClientList sets the ClientList field's value.

func (s *UpdateNFSFileShareInput) SetClientList(v []*string) *UpdateNFSFileShareInput {
	s.ClientList = v
	return s
}

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

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

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


Question:
Set the Byte field which indicates the subtype of the message.

@param value The Byte value of the Message SubType field

final void setSubtype(Byte value) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "setSubtype", value);
        jmo.setField(JsHdrAccess.SUBTYPE, value);
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "setSubtype");
    }

String getLiteralPrefix() {

        switch (type) {

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

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

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

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

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

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

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

            default :
                return null;
        }
    }

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