function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_time_since_last_change = ET.SubElement(fcoe_intf_list, "fcoe-intf-time-since-last-change")
        fcoe_intf_time_since_last_change.text = kwargs.pop('fcoe_intf_time_since_last_change')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question:
// StringByTag returns the string value of an IndexEntry or an empty string if
// the tag is not found or has no value.

func (c IndexEntries) StringByTag(tag int) string {
	s := c.StringsByTag(tag)
	if s == nil || len(s) == 0 {
		return ""
	}
	return s[0]
}

function isNull(value, message, id) {
    if (message === void 0) { message = ''; }
    if (id === void 0) { id = ''; }
    if (this.enabled && value !== null) {
        throw ValueException.unexpectedValue(assertionTypes.IS_NULL, value, null, message, id);
    }
}

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


Question: // SetLicenseInfo sets the LicenseInfo field's value.

func (s *GetLayerVersionByArnOutput) SetLicenseInfo(v string) *GetLayerVersionByArnOutput {
	s.LicenseInfo = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
---------------------------------------------------------------------------------------------------------------------
tgi-core/lib/core/tgi-core-message.source.js

Constructor

function Message(type, contents) {
  if (false === (this instanceof Message)) throw new Error('new operator required');
  if ('undefined' == typeof type) throw new Error('message type required');
  if (!contains(Message.getTypes(), type)) throw new Error('Invalid message type: ' + type);
  this.type = type;
  this.contents = contents;
}

public function getHeader( $uid = '' )
	{
		$view = $this->getView();

		try
		{
			if( !isset( $this->view ) ) {
				$view = $this->view = $this->getObject()->addData( $view, $this->tags, $this->expire );
			}

			$html = '';
			foreach( $this->getSubClients() as $subclient ) {
				$html .= $subclient->setView( $view )->getHeader( $uid );
			}
			$view->selectHeader = $html;

			/** client/html/locale/select/standard/template-header
			 * Relative path to the HTML header template of the locale select client.
			 *
			 * The template file contains the HTML code and processing instructions
			 * to generate the HTML code that is inserted into the HTML page header
			 * of the rendered page in the frontend. The configuration string is the
			 * path to the template file relative to the templates directory (usually
			 * in client/html/templates).
			 *
			 * You can overwrite the template file configuration in extensions and
			 * provide alternative templates. These alternative templates should be
			 * named like the default one but with the string "standard" replaced by
			 * an unique name. You may use the name of your project for this. If
			 * you've implemented an alternative client class as well, "standard"
			 * should be replaced by the name of the new class.
			 *
			 * @param string Relative path to the template creating code for the HTML page head
			 * @since 2014.09
			 * @category Developer
			 * @see client/html/locale/select/standard/template-body
			 */
			$tplconf = 'client/html/locale/select/standard/template-header';
			$default = 'locale/select/header-standard';

			return $view->render( $view->config( $tplconf, $default ) );
		}
		catch( \Exception $e )
		{
			$this->logException( $e );
		}
	}

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


Question:
Look up the most recent errors of a workerType

        Return a list of the most recent errors encountered by a worker type

        This method gives output: ``v1/errors.json#``

        This method is ``experimental``

async def workerTypeErrors(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["workerTypeErrors"], *args, **kwargs)

def _read_file_header(self):
        """"""
        header = self.fileobj.readline()
        payload1 = self.fileobj.readline()
        payload2 = self.fileobj.readline()
        version, reserved, organisation = payload1.split(None, 2)
        self.fileobj.readline() # Lose the separator newline
        self.header_read = True
        # print "--------------------------------------------------"
        # print header,"\n", payload1, "\n", payload2,"\n"
        # print "--------------------------------------------------"
        if self.version and int(self.version) != version:
            raise IOError("Version mismatch. Requested version was '%s' but version in file was '%s'"%(self.version, version))

        if version == '1':
            url, ip_address, date, content_type, length = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 1
        elif version == '2':
            url, ip_address, date, content_type, result_code, checksum, location, offset, filename, length  = header.split()
            self.file_headers = {"ip_address" : ip_address,
                                 "date" : datetime.datetime.strptime(date, "%Y%m%d%H%M%S"),
                                 "org" : organisation}
            self.version = 2
        else:
            raise IOError("Unknown ARC version '%s'"%version)

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


Question:
Parses a component of a partial date.

@param component the date component.
@param padding the padding character.
@return the parsed value, may be null.

private boolean isValidPartialDateStringFormat(final String component, final char padding) {
		// Empty is not valid
		if (Util.empty(component)) {
			return false;
		}

		int length = component.length();

		// Check length YYYY, or YYYYMM, or YYYYMMDD
		if (length != YEAR_END && length != MONTH_END && length != DAY_END) {
			return false;
		}

		// Year - ???? or YYYY
		String year = component.substring(YEAR_START, YEAR_END);
		if (!isValidCharacters(year, padding) || !isValidYear(parseDateComponent(year, padding))) {
			return false;
		}

		// Month - ?? or MM
		if (component.length() >= MONTH_END) {
			String month = component.substring(MONTH_START, MONTH_END);
			if (!isValidCharacters(month, padding) || !isValidMonth(parseDateComponent(month,
					padding))) {
				return false;
			}
		}

		// Day - ?? or DD
		if (component.length() == DAY_END) {
			String day = component.substring(DAY_START, DAY_END);
			if (!isValidCharacters(day, padding) || !isValidDay(parseDateComponent(day, padding))) {
				return false;
			}
		}

		return true;
	}

def __generate(self):
        """"""
        base = []
        texted = []
        for pat in ALL_PATTERNS:
            data = pat.copy()
            data['pattern'] = data['pattern']
            data['right'] = True
            data['basekey'] = data['key']
            base.append(data)

            data = pat.copy()
            data['basekey'] = data['key']
            data['key'] += ':time_1'
            data['right'] = True
            data['pattern'] = data['pattern'] + Optional(Literal(",")).suppress() + BASE_TIME_PATTERNS['pat:time:minutes']
            data['time_format'] = '%H:%M'
            data['length'] = {'min' : data['length']['min'] + 5, 'max' : data['length']['max'] + 8}
            base.append(data)

            data = pat.copy()
            data['basekey'] = data['key']
            data['right'] = True
            data['key'] += ':time_2'
            data['pattern'] = data['pattern'] + Optional(oneOf([',', '|'])).suppress() + BASE_TIME_PATTERNS['pat:time:full']
            data['time_format'] = '%H:%M:%S'
            data['length'] = {'min' : data['length']['min'] + 9, 'max' : data['length']['max'] + 9}
            base.append(data)

        for pat in base:
            # Right
            data = pat.copy()
            data['key'] += ':t_right'
            data['pattern'] = lineStart + data['pattern'] +  Optional(oneOf([',', '|', ':', ')'])).suppress() + restOfLine.suppress()
            data['length'] = {'min' : data['length']['min'] + 1, 'max' : data['length']['max'] + 90}
            texted.append(data)

        base.extend(texted)
        self.patterns = base

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


Question: Setup arrays for platforms which do not support byte arrays

function setupTypedArray(name, fallback) {
  // check if TypedArray exists
  // typeof on Minefield and Chrome return function, typeof on Webkit returns object.
  if (typeof this[name] !== "function" && typeof this[name] !== "object") {
    // nope.. check if WebGLArray exists
    if (typeof this[fallback] === "function" && typeof this[fallback] !== "object") {
      this[name] = this[fallback];
    } else {
      // nope.. set as Native JS array
      this[name] = function(obj) {
        if (obj instanceof Array) {
          return obj;
        } else if (typeof obj === "number") {
          return new Array(obj);
        }
      };
    }
  }
}

public void set(BitArray ba) {
        if (ba.size != this.size)
            throw new IllegalArgumentException();
        for (int i = 0; i < this.data.length; ++i)
            this.data[i] = ba.data[i];
    }

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


Question: // SetPipelineId sets the PipelineId field's value.

func (s *GetPipelineDefinitionInput) SetPipelineId(v string) *GetPipelineDefinitionInput {
	s.PipelineId = &v
	return s
}

def pb_id(self, pb_id: str):
        """"""
        # FIXME(BMo) instead of creating the object to check if the PB exists
        #            use a method on PB List?
        # ProcessingBlock(pb_id)
        self.set_state(DevState.ON)
        self._pb_id = pb_id

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


Question:
<p>
The existing Amazon VPC prefixes advertised to the Direct Connect gateway.
</p>

@return The existing Amazon VPC prefixes advertised to the Direct Connect gateway.

public java.util.List<RouteFilterPrefix> getExistingAllowedPrefixesToDirectConnectGateway() {
        if (existingAllowedPrefixesToDirectConnectGateway == null) {
            existingAllowedPrefixesToDirectConnectGateway = new com.amazonaws.internal.SdkInternalList<RouteFilterPrefix>();
        }
        return existingAllowedPrefixesToDirectConnectGateway;
    }

def _launch_instance(self):

        self.running_instance_id = ipa_utils.generate_instance_name(
            'azure-ipa-test'
        )
        self.logger.debug('ID of instance: %s' % self.running_instance_id)
        self._set_default_resource_names()

        try:
            # Try block acts as a transaction. If an exception is raised
            # attempt to cleanup the resource group and all created resources.

            # Create resource group.
            self._create_resource_group(self.region, self.running_instance_id)

            if self.subnet_id:
                # Use existing vnet/subnet.
                subnet = self.network.subnets.get(
                    self.vnet_resource_group, self.vnet_name, self.subnet_id
                )
            else:
                self.subnet_id = ''.join([self.running_instance_id, '-subnet'])
                self.vnet_name = ''.join([self.running_instance_id, '-vnet'])

                # Create new vnet
                self._create_virtual_network(
                    self.region, self.running_instance_id, self.vnet_name
                )

                # Create new subnet in new vnet
                subnet = self._create_subnet(
                    self.running_instance_id, self.subnet_id, self.vnet_name
                )

            # Setup interface and public ip in resource group.
            public_ip = self._create_public_ip(
                self.public_ip_name, self.running_instance_id, self.region
            )
            interface = self._create_network_interface(
                self.ip_config_name, self.nic_name, public_ip, self.region,
                self.running_instance_id, subnet, self.accelerated_networking
            )

            # Get dictionary of VM parameters and create instance.
            vm_config = self._create_vm_config(interface)
            self._create_vm(vm_config)
        except Exception:
            try:
                self._terminate_instance()
            except Exception:
                pass
            raise
        else:
            # Ensure VM is in the running state.
            self._wait_on_instance('VM running', timeout=self.timeout)

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


Question:
Get all module slugs.

@return \Illuminate\Support\Collection

public function slugs()
    {
        $slugs = collect();

        $this->all()->each(function ($item, $key) use ($slugs) {
            $slugs->push(strtolower($item['slug']));
        });

        return $slugs;
    }

public function checkConnection()
    {
        $success = false;
        $message = '';
        $config  = $this->getPostConfiguration();

        try{
            $this->makeConnection($config);

            /**
             * Just trying to show tables with current connection
             */
            switch ($config['driver']) {
                case 'mysql':
                    $tables = Capsule::select('show tables');
                    break;

                case 'sqlite':
                    $tables = Capsule::select("SELECT * FROM sqlite_master WHERE type='table'");
                    break;

                case 'sqlsrv':
                    $tables = Capsule::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
                    break;

                case 'pgsql':
                    $tables = Capsule::select("SELECT * FROM pg_catalog.pg_tables");
                    break;
            }

            $success = true;
            $message = 'Successfully connected!';

        }catch(Exception $e){
            $success = false;
            $message = $e->getMessage();
        }

        Response::headers()->set('Content-Type', 'application/json');
        Response::setBody(json_encode(
            array(
                'success' => $success,
                'message' => $message,
                'config'  => $config
            )
        ));
    }

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


Question: // NewServer creates a new TabletServer based on the command line flags.

func NewServer(topoServer *topo.Server, alias topodatapb.TabletAlias) *TabletServer {
	return NewTabletServer(tabletenv.Config, topoServer, alias)
}

def start(self):
        """"""
        for i in range(self.min):
            self._threads.append(WorkerThread(self.server))
        for worker in self._threads:
            worker.setName("CP Server " + worker.getName())
            worker.start()
        for worker in self._threads:
            while not worker.ready:
                time.sleep(.1)

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


Question:
Calculate effective sample size

    Parameters
    ----------
    sim : chains
    n : int
        Parameter index starting from 0

def ess(sim, n):

    try:
        ess = _chains.effective_sample_size(sim, n)
    except (ValueError, ZeroDivisionError):
        ess = nan
    return ess

public function encodeParameter($type, $param)
    {
        if (!is_string($type)) {
            throw new InvalidArgumentException('The type to encodeParameter must be string.');
        }
        return $this->encodeParameters([$type], [$param]);
    }

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


Question:
List crons status

@return \Symfony\Component\HttpFoundation\Response

public function listAction()
    {
        $this->performAccessChecks();

        $crons = $this->cronService->listCronsStatus();
        $cronRows = array();

        foreach ($crons as $cron) {
            $cronRows[] = array(
                'alias' => $cron->getAlias(),
                'queued' => $cron instanceof SmileCron
                    ? ($cron->getQueued() ? $cron->getQueued()->format('d-m-Y H:i') : false)
                    : false,
                'started' => $cron instanceof SmileCron ? ($cron->getStarted()
                    ? $cron->getStarted()->format('d-m-Y H:i') : false)
                    : false,
                'ended' => $cron instanceof SmileCron ? ($cron->getEnded()
                    ? $cron->getEnded()->format('d-m-Y H:i') : false)
                    : false,
                'status' => $cron instanceof SmileCron ? $cron->getStatus() : false
            );
        }

        return $this->render('SmileEzUICronBundle:cron:tab/status/list.html.twig', [
            'datas' => $cronRows
        ]);
    }

public function success(Form $form) : void
    {
        if ($this->presenter->isAjax())
        {
            $values = $form->getValues();

            try
            {
                $redirect = NULL;
                $page = $this->pageRepository->findOneById($values->pageId);

                if ($this->redirectId)
                {
                    $redirect = $this->onPageRepository->findOneRedirectById($this->redirectId);
                }

                $this->onPageManager->saveRedirect($redirect, $page, $values->oldUrl);

                $form->reset();

                $this->presenter->notificationAjax(
                    'URL přesměrována',
                    'URL byla úspěšně přesměrována.',
                    'success',
                    FALSE
                );

                $this->onSave();
            }
            catch (DatabaseException $exception)
            {
                $this->presenter->notificationAjax(
                    'Chyba',
                    $exception->getMessage(),
                    'error'
                );
            }
        }
    }

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


Question:
{@inheritDoc}

Set the VFLib MCS software

@param reactant
@param product

@Override
    public void set(MolHandler reactant, MolHandler product) {
        mol1 = reactant.getMolecule();
        mol2 = product.getMolecule();
    }

def main():

    usage = "usage: %(prog)s [options] "
    description = "Merge a set of Fermi-LAT files."
    parser = argparse.ArgumentParser(usage=usage, description=description)

    parser.add_argument('-o', '--output', default=None, type=str,
                        help='Output file.')
    parser.add_argument('--clobber', default=False, action='store_true',
                        help='Overwrite output file.')
    parser.add_argument('files', nargs='+', default=None,
                        help='List of input files.')

    args = parser.parse_args()

    proj, f, hdu = fits_utils.read_projection_from_fits(args.files[0])
    if isinstance(proj, WCS):
        hdulist = merge_utils.merge_wcs_counts_cubes(args.files)
    elif isinstance(proj, HPX):
        hdulist = merge_utils.merge_hpx_counts_cubes(args.files)
    else:
        raise TypeError("Could not read projection from file %s" %
                        args.files[0])

    if args.output:
        hdulist.writeto(args.output, clobber=args.clobber, output_verify='silentfix')

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


Question: Get GO IDs header index for each user GO ID and corresponding parent GO IDs.

def _get_go2nthdridx(self, gos_all):
        """"""
        go2nthdridx = {}
        # NtHdrIdx Namedtuple fields:
        #   * format_txt: Used to determine the format when writing Excel cells
        #   * hdr_idx: Value printed in an Excel cell
        # shortcuts
        obj = GrouperInit.NtMaker(self)
        # Create go2nthdridx
        for goid in gos_all:
            go2nthdridx[goid] = obj.get_nt(goid)
        return go2nthdridx

func readUgen(r io.Reader) (*Ugen, error) {
	var (
		numInputs    int32
		numOutputs   int32
		specialIndex int16
		rate         int8
	)
	// read name
	name, err := readPstring(r)
	if err != nil {
		return nil, err
	}
	// read calculation rate
	if err := binary.Read(r, byteOrder, &rate); err != nil {
		return nil, err
	}
	// read number of inputs
	if err := binary.Read(r, byteOrder, &numInputs); err != nil {
		return nil, err
	}
	// read number of outputs
	if err := binary.Read(r, byteOrder, &numOutputs); err != nil {
		return nil, err
	}
	// read special index
	if err := binary.Read(r, byteOrder, &specialIndex); err != nil {
		return nil, err
	}
	var (
		inputs  = make([]UgenInput, numInputs)
		outputs = make([]Output, numOutputs)
	)
	// read inputs
	for i := 0; int32(i) < numInputs; i++ {
		in, err := readInput(r)
		if err != nil {
			return nil, err
		}
		inputs[i] = in
	}
	// read outputs
	for i := 0; int32(i) < numOutputs; i++ {
		out, err := readOutput(r)
		if err != nil {
			return nil, err
		}
		outputs[i] = out
	}
	return &Ugen{
		Name:         name.String(),
		Rate:         rate,
		SpecialIndex: specialIndex,
		Inputs:       inputs,
		Outputs:      outputs,
		NumOutputs:   int(numOutputs),
	}, nil
}

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


Question:
Get the guest's group, containing only the 'guests' group model.

@return \Flarum\Group\Group

public function getGroupsAttribute()
    {
        if (! isset($this->attributes['groups'])) {
            $this->attributes['groups'] = $this->relations['groups'] = Group::where('id', Group::GUEST_ID)->get();
        }

        return $this->attributes['groups'];
    }

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:
Button handler for the OK button.<p>

@param e the click event

@UiHandler("m_okButton")
    void onClickOk(ClickEvent e) {

        String propName = m_propertyNameField.getFormValueAsString();
        if (CmsStringUtil.isEmptyOrWhitespaceOnly(propName)) {
            m_propertyNameField.setErrorMessage(CmsPropertyDefinitionMessages.messageEmpty());
            return;
        }
        String normalizedName = propName.trim();
        if (!isValidName(normalizedName)) {
            m_propertyNameField.setErrorMessage(CmsPropertyDefinitionMessages.messageInvalidName());
            return;
        }
        if (m_existingPropertyNames.contains(normalizedName)) {
            m_propertyNameField.setErrorMessage(CmsPropertyDefinitionMessages.alreadyExists());
            return;
        }
        savePropertyDefinitionAndQuit(normalizedName);
    }

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question:
Utility class to determine if all items in the list of people have a displayName.

@param people list of personAttributes
@return true if all list items have an attribute displayName

private boolean allListItemsHaveDisplayName(List<IPersonAttributes> people) {
        for (IPersonAttributes person : people) {
            if (person.getAttributeValue("displayName") == null) {
                return false;
            }
        }
        return true;
    }

synchronized String[] dev_poll_status(final String dev_name) throws DevFailed {
        Util.out4.println("In dev_poll_status command");

        // Find the device
        final DeviceImpl dev = Util.instance().get_device_by_name(dev_name);

        final Vector poll_list = dev.get_poll_obj_list();
        final int nb_poll_obj = poll_list.size();

        // Return an empty sequence if nothing is polled for this device
        if (nb_poll_obj == 0) {
            return new String[0];
        }

        // Compute how many cmds and/or attributes are polled
        int nb_cmd = 0;
        for (int i = 0; i < nb_poll_obj; i++) {
            final PollObj poll_obj = (PollObj) poll_list.elementAt(i);
            if (poll_obj.get_type() == Tango_POLL_CMD) {
                nb_cmd++;
            }
        }

        // Allocate memory for returned strings
        final String[] ret = new String[nb_poll_obj];

        // Populate returned strings
        int cmd_ind = 0;
        int attr_ind = nb_cmd;
        String returned_info;

        for (int i = 0; i < nb_poll_obj; i++) {
            final PollObj poll_obj = (PollObj) poll_list.elementAt(i);
            // First, the name
            final int type = poll_obj.get_type();
            if (type == Tango_POLL_CMD) {
                returned_info = "Polled command name = ";
            } else {
                returned_info = "Polled attribute name = ";
            }
            returned_info += poll_obj.get_name();

            // Add update period
            returned_info += "\nPolling period (mS) = ";
            final int tmp = poll_obj.get_upd();
            returned_info = returned_info + tmp;

            // Add ring buffer depth
            returned_info += "\nPolling ring buffer depth = ";
            final int depth = dev.get_poll_ring_depth();
            if (depth == 0) {
                returned_info += Tango_DefaultPollRingDepth;
            } else {
                returned_info += depth;
            }

            // Add a message if the data ring is empty
            if (poll_obj.is_ring_empty() == true) {
                returned_info += "\nNo data recorded yet";
            } else {
                // Add needed time to execute last command
                returned_info += "\nTime needed for the last ";
                if (type == Tango_POLL_CMD) {
                    returned_info += "command execution (mS) = ";
                } else {
                    returned_info += "attribute reading (mS) = ";
                }
                returned_info += poll_obj.get_needed_time_i();

                // Add not updated since... info
                returned_info += "\nData not updated since ";
                final double since = poll_obj.get_last_insert_date_i();

                final long ctm = System.currentTimeMillis();
                final int tv_sec = (int) (ctm / 1000);
                final int tv_usec = (int) (ctm - 1000 * tv_sec) * 1000;

                final double now_d = tv_sec + (double) tv_usec / 1000000;
                final double diff_t = now_d - since;
                if (diff_t < 1.0) {
                    final int nb_msec = (int) (diff_t * 1000);
                    returned_info = returned_info + nb_msec + " mS";
                } else if (diff_t < 60.0) {
                    final int nb_sec = (int) diff_t;
                    final int nb_msec = (int) ((diff_t - nb_sec) * 1000);
                    returned_info = returned_info + nb_sec + " S and ";
                    returned_info = returned_info + nb_msec + " mS";
                } else {
                    final int nb_min = (int) (diff_t / 60);
                    final int nb_sec = (int) (diff_t - 60 * nb_min);
                    final int nb_msec = (int) ((diff_t - (int) diff_t) * 1000);

                    returned_info = returned_info + nb_min + " MN";

                    if (nb_sec != 0) {
                        returned_info = returned_info + " ," + nb_sec + " S";
                    }

                    if (nb_msec != 0) {
                        returned_info = returned_info + " and " + nb_msec + " mS";
                    }
                }

                // Add delta_t between last record(s)
                try {
                    returned_info += "\nDelta between last records (in mS) = ";
                    final double[] delta = poll_obj.get_delta_t_i(4);
                    for (int j = 0; j < delta.length; j++) {
                        final int nb_msec = (int) (delta[j] * 1000);
                        returned_info = returned_info + nb_msec;
                        if (j != delta.length - 1) {
                            returned_info = returned_info + ", ";
                        }
                    }
                } catch (final DevFailed e) {
                }

                // Add last polling exception fields (if any)
                if (poll_obj.is_last_an_error_i() == true) {
                    if (type == Tango_POLL_CMD) {
                        returned_info += "\nLast command execution FAILED :";
                    } else {
                        returned_info += "\nLast attribute read FAILED :";
                    }
                    final DevFailed ex = poll_obj.get_last_except_i();
                    returned_info += "\n\tReason = " + ex.errors[0].reason;
                    returned_info += "\n\tDesc = " + ex.errors[0].desc;
                    returned_info += "\n\tOrigin = " + ex.errors[0].origin;
                }
            }

            // Init. string in sequence
            if (type == Tango_POLL_CMD) {
                ret[cmd_ind] = returned_info;
                cmd_ind++;
            } else {
                ret[attr_ind] = returned_info;
                attr_ind++;
            }
        }
        return ret;
    }

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


Question:
// GetUniqueVolumeNameFromSpecWithPod returns a unique volume name with pod
// name included. This is useful to generate different names for different pods
// on same volume.

func GetUniqueVolumeNameFromSpecWithPod(
	podName types.UniquePodName, volumePlugin volume.VolumePlugin, volumeSpec *volume.Spec) v1.UniqueVolumeName {
	return v1.UniqueVolumeName(
		fmt.Sprintf("%s/%v-%s", volumePlugin.GetPluginName(), podName, volumeSpec.Name()))
}

func (p Packet) ValueNames() []string {
	r := make([]string, len(p.DataTypes))
	for i := range p.DataTypes {
		name := p.Name()
		var valueName string
		switch {
		case p.Plugin == "df" && i == 0:
			valueName = ""
		case p.Plugin == "memory" && i == 0:
			valueName = ""
		case p.Plugin == "interface" && i == 0:
			valueName = "tx"
		case p.Plugin == "interface" && i == 1:
			valueName = "rx"
		case p.Plugin == "load" && i == 0:
			valueName = "1"
		case p.Plugin == "load" && i == 1:
			valueName = "5"
		case p.Plugin == "load" && i == 2:
			valueName = "15"
		default:
			valueName = strconv.FormatInt(int64(i), 10)
		}
		if valueName == "" {
			r[i] = name
		} else {
			r[i] = fmt.Sprintf("%s_%s", name, valueName)
		}
	}
	return r
}

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


Question:
<p>
Converts a big number to a friendly text representation. Accepts values
ranging from thousands to googols. Uses BigDecimal.
</p>

@param value
Number to be converted
@return Friendly text representation of the given value

public static String spellBigNumber(final Number value)
    {
        BigDecimal v = new BigDecimal(value.toString());

        if (THOUSAND.compareTo(v.abs()) > 0)
            return value.toString();

        boolean isPlural = needPlural(v.unscaledValue().intValue());

        for (BigDecimal bigNum : bigDecExponents.keySet())
            if (bigNum.multiply(THOUSAND).compareTo(v.abs()) > 0)
                return context.get().formatMessage(
                        (isPlural) ? bigDecExponents.get(bigNum) + ".pl" : bigDecExponents.get(bigNum),
                        v.divide(bigNum));

        return value.toString();
    }

func (i *GetWAFRuleStatusesInput) formatFilters() map[string]string {
	input := i.Filters
	result := map[string]string{}
	pairings := map[string]interface{}{
		"filter[status]":           input.Status,
		"filter[rule][accuracy]":   input.Accuracy,
		"filter[rule][maturity]":   input.Maturity,
		"filter[rule][message]":    input.Message,
		"filter[rule][revision]":   input.Revision,
		"filter[rule][rule_id]":    input.RuleID,
		"filter[rule][tags]":       input.TagID,
		"filter[rule][tags][name]": input.TagName,
		"filter[rule][version]":    input.Version,
		"include":                  input.Tags,
		"page[size]":               input.MaxResults,
		"page[number]":             input.Page, // starts at 1, not 0
	}
	// NOTE: This setup means we will not be able to send the zero value
	// of any of these filters. It doesn't appear we would need to at present.
	for key, value := range pairings {
		switch t := reflect.TypeOf(value).String(); t {
		case "string":
			if value != "" {
				result[key] = value.(string)
			}
		case "int":
			if value != 0 {
				result[key] = strconv.Itoa(value.(int))
			}
		case "[]int":
			// convert ints to strings
			toStrings := []string{}
			values := value.([]int)
			for _, i := range values {
				toStrings = append(toStrings, strconv.Itoa(i))
			}
			// concat strings
			if len(values) > 0 {
				result[key] = strings.Join(toStrings, ",")
			}
		}
	}
	return result
}

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


Question: Return items, shape filtered by a dimension slice.

def _filtdim(items, shape, dim, nsl):
    """"""
    normshape = tuple(stop - start for start, stop in shape)
    nsl_type = type(nsl)
    newitems = list()
    # Number of groups
    num = reduce(operator.mul, normshape[:dim+1])
    # Size of each group
    size = len(items) // num
    # Size of the dimension
    n = normshape[dim]
    if nsl_type is int:
        for i in range(num):
            if i % n == nsl:
                newitems += items[size*i:size*(i+1)]
        # Collapse dimension
        newshape = shape[:dim] + shape[dim+1:]
    elif nsl_type is slice:
        for i in range(num):
            if nsl.start <= (i % n) < nsl.stop:
                newitems += items[size*i:size*(i+1)]
        # Reshape dimension
        offset = shape[dim][0]
        redim = (offset + nsl.start, offset + nsl.stop)
        newshape = shape[:dim] + (redim, ) + shape[dim+1:]
    # farray
    else:
        if nsl.size < clog2(n):
            fstr = "expected dim {} select to have >= {} bits, got {}"
            raise ValueError(fstr.format(dim, clog2(n), nsl.size))
        groups = [list() for _ in range(n)]
        for i in range(num):
            groups[i % n] += items[size*i:size*(i+1)]
        for muxins in zip(*groups):
            it = boolfunc.iter_terms(nsl._items)
            xs = [reduce(operator.and_, (muxin, ) + next(it))
                  for muxin in muxins]
            newitems.append(reduce(operator.or_, xs))
        # Collapse dimension
        newshape = shape[:dim] + shape[dim+1:]
    return newitems, newshape

def search(self, queryType, query=None, vendorSpecific=None, **kwargs):

        response = self.searchResponse(queryType, query, vendorSpecific, **kwargs)
        return self._read_dataone_type_response(response, 'ObjectList')

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


Question: // SetValueFrom sets the ValueFrom field's value.

func (s *Secret) SetValueFrom(v string) *Secret {
	s.ValueFrom = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question:
@param string $messageKey     The unique message key for the translation system.
@param string $defaultMessage The default message in English, if no translator is available.

@return void

private function addTranslatableError(string $messageKey, string $defaultMessage) : void
    {
        $message = $defaultMessage;

        if (null !== $translator = $this->form->getTranslator()) {
            $translatedMessage = $translator($messageKey);
            if ($translatedMessage !== null) {
                $message = $translatedMessage;
            }
        }

        $this->addError($message);
    }

def get_assessment_offered_mdata():
    """"""
    return {
        'level': {
            'element_label': {
                'text': 'level',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'accepts an osid.id.Id object',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_id_values': [''],
            'syntax': 'ID',
            'id_set': [],
        },
        'start_time': {
            'element_label': {
                'text': 'start time',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter a valid datetime object.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_date_time_values': [None],
            'syntax': 'DATETIME',
            'date_time_set': [],
        },
        'grade_system': {
            'element_label': {
                'text': 'grade system',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'accepts an osid.id.Id object',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_id_values': [''],
            'syntax': 'ID',
            'id_set': [],
        },
        'items_shuffled': {
            'element_label': {
                'text': 'items shuffled',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter either true or false.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_boolean_values': [None],
            'syntax': 'BOOLEAN',
        },
        'score_system': {
            'element_label': {
                'text': 'score system',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'accepts an osid.id.Id object',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_id_values': [''],
            'syntax': 'ID',
            'id_set': [],
        },
        'deadline': {
            'element_label': {
                'text': 'deadline',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter a valid datetime object.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_date_time_values': [None],
            'syntax': 'DATETIME',
            'date_time_set': [],
        },
        'duration': {
            'element_label': {
                'text': 'duration',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter a valid duration object.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_duration_values': [None],
            'syntax': 'DURATION',
            'date_time_set': [],
        },
        'assessment': {
            'element_label': {
                'text': 'assessment',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'accepts an osid.id.Id object',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_id_values': [''],
            'syntax': 'ID',
            'id_set': [],
        },
        'items_sequential': {
            'element_label': {
                'text': 'items sequential',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'instructions': {
                'text': 'enter either true or false.',
                'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
                'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
                'formatTypeId': str(DEFAULT_FORMAT_TYPE),
            },
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_boolean_values': [None],
            'syntax': 'BOOLEAN',
        },
    }

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


Question:
recv the next MAVLink message that matches the given condition
        type can be a string or a list of strings

def recv_match(self, condition=None, type=None, blocking=False, timeout=None):
        ''''''
        if type is not None and not isinstance(type, list):
            type = [type]
        start_time = time.time()
        while True:
            if timeout is not None:
                now = time.time()
                if now < start_time:
                    start_time = now # If an external process rolls back system time, we should not spin forever.
                if start_time + timeout < time.time():
                    return None
            m = self.recv_msg()
            if m is None:
                if blocking:
                    for hook in self.idle_hooks:
                        hook(self)
                    if timeout is None:
                        self.select(0.05)
                    else:
                        self.select(timeout/2)
                    continue
                return None
            if type is not None and not m.get_type() in type:
                continue
            if not evaluate_condition(condition, self.messages):
                continue
            return m

def send(self, command, payload):

        request = WorkRequest(command, payload)
        logging.info("Sending {} message to queue {}.".format(request.command, self.queue_name))
        # setting protocol to version 2 to be compatible with python2
        self.connection.send_durable_message(self.queue_name, pickle.dumps(request, protocol=2))
        logging.info("Sent {} message.".format(request.command, self.queue_name))

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


Question: Determine if the model has changed since the last `"change"` event. If you specify an attribute name, determine if that attribute has changed.

function(attr) {
      if (!this._hasComputed) this._computeChanges();
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    }

def modified?(doc)
      return true if metadata[doc.path]&.[](:forced)
      return true unless File.exist?(site.in_dest_dir(doc.path))
      modified, hash = file_mtime_of(doc.path), metadata[doc.path]
      return modified > hash[:last_modified] if hash && !hash[:dynamic] && hash[:seen_before]
      return hash[:seen_before] = true if hash && !hash[:seen_before]
      return dependencies_modified?(hash) if hash
      add(doc.path).update(seen_before: true)

      true
    end

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


Question:
/*
@see com.ibm.websphere.ssl.JSSEProvider#getCiphersForSecurityLevel(boolean,
java.lang.String)

@Override
    public String[] getCiphersForSecurityLevel(boolean isClient, String securityLevel) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "getCiphersForSecurityLevel: ", new Object[] { Boolean.valueOf(isClient), securityLevel });

        String[] supportedCiphers = null;

        if (isClient) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            supportedCiphers = factory.getSupportedCipherSuites();
        } else {
            SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            supportedCiphers = factory.getSupportedCipherSuites();
        }

        return Constants.adjustSupportedCiphersToSecurityLevel(supportedCiphers, securityLevel);
    }

function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  var params = {};
  if (typeof N == 'object') {
    params = N;
  } else {
    params.n = N;
    params.e = E;
    params.d = D;
    params.p = P;
    params.q = Q;
    params.dmp1 = DP;
    params.dmq1 = DQ;
    params.coeff = C;
  }
  if(params.n != null && params.e != null && params.n.length > 0 && params.e.length > 0) {
    this.n = parseBigInt(params.n,16);
    this.e = parseInt(params.e,16);
    this.d = parseBigInt(params.d,16);
    this.p = parseBigInt(params.p,16);
    this.q = parseBigInt(params.q,16);
    this.dmp1 = parseBigInt(params.dmp1,16);
    this.dmq1 = parseBigInt(params.dmq1,16);
    this.coeff = parseBigInt(params.coeff,16);
  }
  else
    console.log("Invalid RSA private key");
}

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


Question:
Loop through children and update list order (recursive)

@param $nav

private function updateIfNavHasChildren($nav)
    {
        if (isset($nav['children']) && count($nav['children']) > 0) {
            $children = $nav['children'];
            foreach ($children as $c => $child) {
                $row = $this->updateNavigationListOrder($child['id'], ($c + 1), $nav['id']);

                $this->updateIfNavHasChildren($child);
            }
        }
    }

public function build(): RequestChildNodesRequest
	{
		$instance = new RequestChildNodesRequest();
		if ($this->nodeId === null) {
			throw new BuilderException('Property [nodeId] is required.');
		}
		$instance->nodeId = $this->nodeId;
		$instance->depth = $this->depth;
		$instance->pierce = $this->pierce;
		return $instance;
	}

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


Question:
--- RegistryClientV1
Create a new Docker Registry V1 client for a particular repository.

...
@param opts.insecure {Boolean} Optional. Default false. Set to true
to *not* fail on an invalid or self-signed server certificate.
...

function RegistryClientV1(opts) {
    var self = this;
    assert.object(opts, 'opts');
    assert.string(opts.name, 'opts.name');
    assert.optionalObject(opts.log, 'opts.log');
    assert.optionalString(opts.username, 'opts.username');
    assert.optionalString(opts.password, 'opts.password');
    assert.optionalBool(opts.insecure, 'opts.insecure');
    assert.optionalString(opts.scheme, 'opts.scheme');
    // TODO: options to control the trust db for CA verification
    // TODO add passing through other restify options
    // Restify/Node HTTP client options.
    // opt.agent (optional, bool or object)
    assert.optionalString(opts.userAgent, 'opts.userAgent');
    // opts.proxy (optional, bool or object or string);

    this.log = opts.log
        ? opts.log.child({
                component: 'registry',
                serializers: restifyClients.bunyan.serializers
            })
        : bunyan.createLogger({
                name: 'registry',
                serializers: restifyClients.bunyan.serializers
            });

    this.insecure = Boolean(opts.insecure);
    this.repo = common.parseRepo(opts.name);
    if (opts.scheme) {
        this.repo.index.scheme = opts.scheme;
    } else if (common.isLocalhost(this.repo.index.name)) {
        // Per docker.git:registry/config.go#NewServiceConfig we special
        // case localhost to allow HTTP. Note that this lib doesn't do
        // the "try HTTPS, then fallback to HTTP if allowed" thing that
        // docker-docker does, we'll just prefer HTTP for localhost.
        this.repo.index.scheme = 'http';
    }

    if (opts.username && opts.password) {
        var buffer = new Buffer(opts.username + ':' + opts.password, 'utf8');
        this._authorization = 'Basic ' + buffer.toString('base64');
    }
    this._ensuredSession = false;
    this._cookieJar = new tough.CookieJar();

    this._indexUrl = common.urlFromIndex(this.repo.index);

    this._commonHttpClientOpts = {
        log: this.log,
        agent: opts.agent,
        proxy: opts.proxy,
        rejectUnauthorized: !this.insecure,
        userAgent: opts.userAgent || common.DEFAULT_USERAGENT
    };
    this._clientsToClose = [];

    Object.defineProperty(this, '_indexApi', {
        get: function () {
            if (self.__indexApi === undefined) {
                self.__indexApi = self._createClient('json', self._indexUrl);
            }
            return this.__indexApi;
        }
    });

    /*
     * The registry endpoint can vary. By default one can infer it from
     * the repo. E.g. "quay.io/foo" has a registry host of "quay.io". For
     * repos not specifying and index, e.g. "busybox" or "trentm/blah", the
     * default index is "index.docker.io", for which the default registry host
     * is registry-1.docker.io.
     *
     * Typically that is all you need. However two others things can happen:
     * - The `listRepoImgs` response can redirect to a totally different
     *   registry. E.g. Docker Hub does this for the "rhel7" image. And/or:
     * - The `listRepoImgs` can (typically does, always does?) include a
     *   X-Docker-Endpoints header with a registry host to use.
     *   See `_ensureSession` below.
     *
     * The properties below are to lazily determine and use the registry
     * URL after `_ensureSession` has been run to provide redirects and/or
     * endpoints.
     */
    Object.defineProperty(this, '_registryUrl', {
        get: function () {
            assert.ok(self._ensuredSession,
                'getting _registryUrl before session');
            if (self.__registryUrl === undefined) {
                if (self._endpoints && self._endpoints.length > 0) {
                    self.__registryUrl = self._endpoints[0];
                } else if (self.repo.index.official) {
                    self.__registryUrl = DEFAULT_REGISTRY_URL_V1;
                } else {
                    self.__registryUrl = common.urlFromIndex(self.repo.index);
                }
                self.log.trace({_registryUrl: self.__registryUrl},
                    'set _registryUrl');
            }
            return self.__registryUrl;
        }
    });
    Object.defineProperty(this, '_registryHost', {
        get: function () {
            if (self.__registryHost === undefined) {
                self.__registryHost = mod_url.parse(self._registryUrl).host;
            }
            return self.__registryHost;
        }
    });
    Object.defineProperty(this, '_registryApi', {
        get: function () {
            if (self.__registryApi === undefined) {
                self.__registryApi = self._createClient(
                    'json', self._registryUrl);
            }
            return self.__registryApi;
        }
    });
}

func Identity(cfg *config.Config) fx.Option {
	// PeerID

	cid := cfg.Identity.PeerID
	if cid == "" {
		return fx.Error(errors.New("identity was not set in config (was 'ipfs init' run?)"))
	}
	if len(cid) == 0 {
		return fx.Error(errors.New("no peer ID in config! (was 'ipfs init' run?)"))
	}

	id, err := peer.IDB58Decode(cid)
	if err != nil {
		return fx.Error(fmt.Errorf("peer ID invalid: %s", err))
	}

	// Private Key

	if cfg.Identity.PrivKey == "" {
		return fx.Options( // No PK (usually in tests)
			fx.Provide(PeerID(id)),
			fx.Provide(pstoremem.NewPeerstore),
		)
	}

	sk, err := cfg.Identity.DecodePrivateKey("passphrase todo!")
	if err != nil {
		return fx.Error(err)
	}

	return fx.Options( // Full identity
		fx.Provide(PeerID(id)),
		fx.Provide(PrivateKey(sk)),
		fx.Provide(pstoremem.NewPeerstore),

		fx.Invoke(libp2p.PstoreAddSelfKeys),
	)
}

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


Question: // gtk_text_tag_event

func newTextTag(tag *C.GtkTextTag) *TextTag { // TODO
	return &TextTag{
		GTextTag: tag,
		GObject:  glib.ObjectFromNative(unsafe.Pointer(tag)),
	}
}

def getc(self, block=True):
        """"""
        try:
            return self.cookedq.get(block)
        except gevent.queue.Empty:
            return ''

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


Question: Whether to log the supplied message based on the current filter if any

def include_message?(log)
      return true if @filter.nil?

      if @filter.is_a?(Regexp)
        !(@filter =~ log.name).nil?
      elsif @filter.is_a?(Proc)
        @filter.call(log) == true
      end
    end

func DefaultFilter(conf *yaml.Config) {
	for _, step := range conf.Pipeline {
		defaultStatus(step)
		defaultEvent(step)
	}
}

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


Question:
Delete the given Model

@param  $object
@return Payload

public function delete($object)
	{
		$deleted = $object->delete();

		if( ! $deleted)
		{
			return new Payload($object, 'not_deleted');
		}

		// Remove the deleted model from cache.
		Cache::tags($this->model->getTable())->flush($updated->getKey());

		return new Payload(null, 'deleted');
	}

func (c *Client) DeleteDomain(p *DeleteDomainParameter) (*Result, error) {
	obj, err := c.Request("deleteDomain", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Result), err
}

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


Question: reducing function complexity to keep code climate happy

function logOrThrow(error, result) {

            if (result) {
                self.log('connect-azuretables created table ' + self.table);
            }

            if (error) {
                throw ('failed to create table: ' + error);
            }
        }

func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool {
	// Reset the simple key on the next level.
	parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{})

	// Increase the flow level.
	parser.flow_level++
	return true
}

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


Question:
Get geolocation data for a given IP address
        If field is specified, get specific field as text
        Else get complete location data as JSON

def location(ip=None, key=None, field=None):
    '''
    '''

    if field and (field not in field_list):
        return 'Invalid field'

    if field:
        if ip:
            url = 'https://ipapi.co/{}/{}/'.format(ip, field)
        else:
            url = 'https://ipapi.co/{}/'.format(field)
    else:
        if ip:
            url = 'https://ipapi.co/{}/json/'.format(ip)
        else:
            url = 'https://ipapi.co/json/'

    if key or API_KEY:
        url = '{}?key={}'.format(url, (key or API_KEY))

    response = get(url, headers=headers)

    if field:
        return response.text
    else:
        return response.json()

public static function getRobotsTxtURL($url)
  {
    $url_parts = PHPCrawlerUtils::splitURL($url);
    $robots_txt_url = $url_parts["protocol"].$url_parts["host"].":".$url_parts["port"] . "/robots.txt";

    return $robots_txt_url;
  }

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


Question: // SetWriteHandler sets a chi router for a Writer.

func SetWriteHandler(r chi.Router, ops *WriteOperations) {
	handler := func(id string, w http.ResponseWriter, r *http.Request) {
		var reader io.Reader
		if fr, _, err := r.FormFile("file"); err != nil {
			defer r.Body.Close()
			reader = r.Body
		} else {
			defer fr.Close()
			reader = fr
		}
		p := pipe.New(reader)
		if err := ops.SetPipe(p, id); err != nil {
			http.Error(w, http.StatusText(500), 500)
		} else if err := p.Exec(); err != nil {
			http.Error(w, http.StatusText(500), 500)
		} else {
			data := &WriteResponse{id, p.TotalIn, p.TotalOut}

			if res, err := json.Marshal(data); err != nil {
				http.Error(w, http.StatusText(500), 500)
			} else {
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(201)
				if _, err = w.Write(res); err != nil {
					http.Error(w, http.StatusText(500), 500)
				}
			}
		}
	}

	generateID := func(w http.ResponseWriter, r *http.Request) {
		id := ksuid.New().String()
		handler(id, w, r)
	}

	extractID := func(w http.ResponseWriter, r *http.Request) {
		id := chi.URLParam(r, "id")
		handler(id, w, r)
	}

	r.Post("/", generateID)
	r.Put("/", generateID)
	r.Post("/{id}", extractID)
	r.Put("/{id}", extractID)
}

func New(ctx context.Context, next http.Handler, confCircuitBreaker config.CircuitBreaker, name string) (http.Handler, error) {
	expression := confCircuitBreaker.Expression

	logger := middlewares.GetLogger(ctx, name, typeName)
	logger.Debug("Creating middleware")
	logger.Debug("Setting up with expression: %s", expression)

	oxyCircuitBreaker, err := cbreaker.New(next, expression, createCircuitBreakerOptions(expression))
	if err != nil {
		return nil, err
	}
	return &circuitBreaker{
		circuitBreaker: oxyCircuitBreaker,
		name:           name,
	}, nil
}

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


Question:
For keyboard mode, processes key events.
@param keyCode the pressed key.
@return true if the key was successfully processed, false otherwise.

private boolean processKeyUp(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_TAB) {
            if(mInKbMode) {
                if (isTypedTimeFullyLegal()) {
                    finishKbMode(true);
                }
                return true;
            }
        } else if (keyCode == KeyEvent.KEYCODE_ENTER) {
            if (mInKbMode) {
                if (!isTypedTimeFullyLegal()) {
                    return true;
                }
                finishKbMode(false);
            }
            if (mCallback != null) {
                mCallback.onTimeSet(this,
                        mTimePicker.getHours(), mTimePicker.getMinutes(), mTimePicker.getSeconds());
            }
            dismiss();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DEL) {
            if (mInKbMode) {
                if (!mTypedTimes.isEmpty()) {
                    int deleted = deleteLastTypedKey();
                    String deletedKeyStr;
                    if (deleted == getAmOrPmKeyCode(AM)) {
                        deletedKeyStr = mAmText;
                    } else if (deleted == getAmOrPmKeyCode(PM)) {
                        deletedKeyStr = mPmText;
                    } else {
                        deletedKeyStr = String.format(mLocale, "%d", getValFromKeyCode(deleted));
                    }
                    Utils.tryAccessibilityAnnounce(mTimePicker,
                            String.format(mDeletedKeyFormat, deletedKeyStr));
                    updateDisplay(true);
                }
            }
        } else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1
                || keyCode == KeyEvent.KEYCODE_2 || keyCode == KeyEvent.KEYCODE_3
                || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5
                || keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7
                || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9
                || (!mIs24HourMode &&
                        (keyCode == getAmOrPmKeyCode(AM) || keyCode == getAmOrPmKeyCode(PM)))) {
            if (!mInKbMode) {
                if (mTimePicker == null) {
                    // Something's wrong, because time picker should definitely not be null.
                    Log.e(TAG, "Unable to initiate keyboard mode, TimePicker was null.");
                    return true;
                }
                mTypedTimes.clear();
                tryStartingKbMode(keyCode);
                return true;
            }
            // We're already in keyboard mode.
            if (addKeyIfLegal(keyCode)) {
                updateDisplay(false);
            }
            return true;
        }
        return false;
    }

public void translateAndSetInterestOps(int ops, SelectionKeyImpl sk) {
        int newOps = 0;

        if ((ops & SelectionKey.OP_READ) != 0)
            newOps |= PollArrayWrapper.POLLIN;
        if ((ops & SelectionKey.OP_WRITE) != 0)
            newOps |= PollArrayWrapper.POLLOUT;
        if ((ops & SelectionKey.OP_CONNECT) != 0)
            newOps |= PollArrayWrapper.POLLIN;
        sk.selector.putEventOps(sk, newOps);
    }

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


Question: sends header to allow the browser to cache the response a given time

public function setCacheable($minutes)
    {
        if ($minutes <= 0) {
            $this->setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
            $this->setHeader('Expires', '-1');
            $this->setHeader('Pragma', 'no-cache');
        } else {
            $this->setHeader('Expires', gmdate('D, d M Y H:i:s', time() + $minutes * 60) . ' GMT', true);
            $this->setHeader('Cache-Control', 'max-age=' . $minutes * 60, true);
            $this->setHeader('Pragma', 'public', true);
        }
    }

@Override
    public void setHeader(String name, String value) {
        this._getHttpServletResponse().setHeader(name, value);
    }

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


Question:
Set the value of $key. If $key is the name of a relation, the
relation will associated with this entity.

@param string $key   The name of the key to set.
@param mixed  $value The value to set.

public function setRaw($key, $value)
    {
        if (isset(static::$relations[$key])) {
            return $this->associateRelation($key, $value);
        }

        //apply the modified flag if the key is one of the fields and
        //the value has changed
        if (in_array($key, static::$fields) && $value !== $this->getRaw($key)) {
            $this->modified[$key] = true;
        }
        $this->values[$key] = $value;
    }

public function updateTable($meta, ...$args)
    {
        $meta = !$meta instanceof Meta ? $this->mapper->getMeta($meta) : $meta;
        if (!$meta->canUpdate) {
            throw new Exception("Meta {$meta->id} prohibits update");
        }

        $query = Query\Update::fromParamArgs($args);
        if (!$query->set) {
            throw new \InvalidArgumentException("Query missing 'set' values");
        }

        list ($sql, $params, $setProps, $whereProps) = $query->buildQuery($meta);
        if ($setProps) {
            $params = $this->mapper->formatParams($meta, $setProps, $params);
        }
        if ($whereProps) {
            $params = $this->mapper->formatParams($meta, $whereProps, $params);
        }

        return $this->getConnector()->exec($sql, $params);
    }

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


Question: // writeTxOut serializes a wire.TxOut struct into the passed io.Writer stream.

func writeTxOut(w io.Writer, txo *wire.TxOut) error {
	var scratch [8]byte

	binary.BigEndian.PutUint64(scratch[:], uint64(txo.Value))
	if _, err := w.Write(scratch[:]); err != nil {
		return err
	}

	if err := wire.WriteVarBytes(w, 0, txo.PkScript); err != nil {
		return err
	}

	return nil
}

func (p DebugPrinter) WebsocketRead(typ int, content []byte, closeCode int) {
	b := &bytes.Buffer{}
	fmt.Fprintf(b, "<- Received: %s", wsMessageTypeName(typ))
	if typ == websocket.CloseMessage {
		fmt.Fprintf(b, " (%d)", closeCode)
	}
	fmt.Fprint(b, "\n")
	if len(content) > 0 {
		if typ == websocket.BinaryMessage {
			fmt.Fprintf(b, "%v\n", content)
		} else {
			fmt.Fprintf(b, "%s\n", content)
		}
	}
	fmt.Fprintf(b, "\n")
	p.logger.Logf(b.String())
}

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


Question:
This ensures all incoming ExternalCacheFragments have not been
invalidated.

@param incomingList The unfiltered list of ExternalCacheFragments.
@return The filtered list of ExternalCacheFragments.

public ArrayList filterExternalCacheFragmentList(String cacheName, ArrayList incomingList) {
		InvalidationTableList invalidationTableList = getInvalidationTableList(cacheName);
		try {
			invalidationTableList.readWriteLock.readLock().lock();
			Iterator it = incomingList.iterator();
			while (it.hasNext()) {
				ExternalInvalidation externalCacheFragment = (ExternalInvalidation) it.next();

				if (null == internalFilterExternalCacheFragment(cacheName, invalidationTableList, externalCacheFragment)) {
					if (tc.isDebugEnabled()) {
						Tr.debug(tc, "filterExternalCacheFragmentList(): Filtered OUT cacheName=" + cacheName + " uri=" + externalCacheFragment.getUri());
					}
					it.remove();
				}
			}
			return incomingList;

		} finally {
			invalidationTableList.readWriteLock.readLock().unlock();
		}
	}

function(packedValue)
    {

        var result;

        var t = typeof(packedValue);
        if (t == "number" || t == "string" || t == "boolean" || packedValue == null || packedValue == undefined)
        {
            result = this.handleError(packedValue);
        }
        else if (packedValue instanceof Array)
        {
            result = [];
            for (var i = 0; i < packedValue.length; i++)
            {
                result[i] = this.deserialize(packedValue[i]);
            }
        }
        else if (t == "object")
        {
            for(var i = 0; i < packedValue.newTypes.length; i++)
            {
                this.addTypeDataToCache(packedValue.newTypes[i]);
            }
            for (var aRefID in packedValue.newRefs)
            {
                this.createProxy(aRefID, packedValue.newRefs[aRefID]);
            }
            if (packedValue.type == FABridge.TYPE_PRIMITIVE)
            {
                result = packedValue.value;
            }
            else if (packedValue.type == FABridge.TYPE_ASFUNCTION)
            {
                result = this.getFunctionProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ASINSTANCE)
            {
                result = this.getProxy(packedValue.value);
            }
            else if (packedValue.type == FABridge.TYPE_ANONYMOUS)
            {
                result = packedValue.value;
            }
        }
        return result;
    }

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


Question: // SetStatus sets the Status field's value.

func (s *UpdateAccessKeyInput) SetStatus(v string) *UpdateAccessKeyInput {
	s.Status = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: end nestedClassesOf(...)

public static ClassInclusion classInIncludes(final String registryKey,final String classSimpleName){
		return new ClassInclusion(){
			@Override
			public Class<?>[] propose(){
				LinkedList<Class<?>>resultList = new LinkedList<Class<?>>();
				for(Class<?>clazz:ParserRegistry.getClassesIn(registryKey)){
					if(clazz.isAssignableFrom(ThirdPartyParseable.class)
							&& clazz.getSimpleName().contentEquals(classSimpleName)
							&&Modifier.isAbstract(clazz.getModifiers()))resultList.add(clazz);
					}//end for(...)
				return resultList.toArray(new Class[]{});
				}//end propose()
			};
		}

def append(self, node):
        """"""
        if node.parent == self.key and not self.elapsed_time:
            self.children.append(node)
        else:
            # Recursive call
            for child in self.children:
                if not child.elapsed_time:
                    child.append(node)

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


Question:
Checks is mbean with given domain and class required by
this configuration.

@param domainName name of mbean domain
@param className class name of mbean
@return true  - configuration require to add this mbean as producer.
false - mbean should be skipped.

public boolean isMBeanRequired(final String domainName, final String className) {

        if(domains == null || domains.length == 0)
            return true; // No domain configuration set. All domains should pass

        for(MBeanProducerDomainConfig domainConfig : domains)
            if(domainConfig.getName().equalsIgnoreCase(domainName)) {
                // Domain was found in configuration. Now checking mbean class.
                return ArrayUtils.contains(domainConfig.getClasses(), className);

        }

        // mbean with given domain and class is not required by configuration
        return false;

    }

synchronized void start(Properties properties) throws Throwable {
        String serverMode = CanalController.getProperty(properties, CanalConstants.CANAL_SERVER_MODE);
        if (serverMode.equalsIgnoreCase("kafka")) {
            canalMQProducer = new CanalKafkaProducer();
        } else if (serverMode.equalsIgnoreCase("rocketmq")) {
            canalMQProducer = new CanalRocketMQProducer();
        }

        if (canalMQProducer != null) {
            // disable netty
            System.setProperty(CanalConstants.CANAL_WITHOUT_NETTY, "true");
            String autoScan = CanalController.getProperty(properties, CanalConstants.CANAL_AUTO_SCAN);
            // 设置为raw避免ByteString->Entry的二次解析
            System.setProperty("canal.instance.memory.rawEntry", "false");
            if ("true".equals(autoScan)) {
                String rootDir = CanalController.getProperty(properties, CanalConstants.CANAL_CONF_DIR);
                if (StringUtils.isEmpty(rootDir)) {
                    rootDir = "../conf";
                }
                File rootdir = new File(rootDir);
                if (rootdir.exists()) {
                    File[] instanceDirs = rootdir.listFiles(new FileFilter() {

                        public boolean accept(File pathname) {
                            String filename = pathname.getName();
                            return pathname.isDirectory() && !"spring".equalsIgnoreCase(filename) &&
                                    !"metrics".equalsIgnoreCase(filename);
                        }
                    });
                    if (instanceDirs != null && instanceDirs.length > 0) {
                        List<String> instances = Lists.transform(Arrays.asList(instanceDirs),
                            new Function<File, String>() {

                                @Override
                                public String apply(File instanceDir) {
                                    return instanceDir.getName();
                                }
                            });
                        System.setProperty(CanalConstants.CANAL_DESTINATIONS, Joiner.on(",").join(instances));
                    }
                }
            } else {
                String destinations = CanalController.getProperty(properties, CanalConstants.CANAL_DESTINATIONS);
                System.setProperty(CanalConstants.CANAL_DESTINATIONS, destinations);
            }
        }

        logger.info("## start the canal server.");
        controller = new CanalController(properties);
        controller.start();
        logger.info("## the canal server is running now ......");
        shutdownThread = new Thread() {

            public void run() {
                try {
                    logger.info("## stop the canal server");
                    controller.stop();
                    CanalLauncher.running = false;
                } catch (Throwable e) {
                    logger.warn("##something goes wrong when stopping canal Server:", e);
                } finally {
                    logger.info("## canal server is down.");
                }
            }

        };
        Runtime.getRuntime().addShutdownHook(shutdownThread);

        if (canalMQProducer != null) {
            canalMQStarter = new CanalMQStarter(canalMQProducer);
            MQProperties mqProperties = buildMQProperties(properties);
            canalMQStarter.start(mqProperties);
            controller.setCanalMQStarter(canalMQStarter);
        }
    }

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


Question:
Función que envía un mensaje a un ID de sesión de una web

@param $mes
@param $text
@param $to

private function sendWebMessage($mes, $text, $to) {
        // Esto no haría falta :S
        $mes['text'] = $text;

        $pusher = $this->container->get('gos_web_socket.wamp.pusher');
        $pusher->push($mes, 'session_topic', ['idSession' => $to]);

        /*
        $pusher->push([
            'data' => $data,
            'text' => $text
        ], 'session_topic', ['idSession' => $to]);
        */

        return true;
    }

private function addHtmlMessage($type, $html = null, $css_selector = null)
    {
        return $this->add($type, array(
            'value' => $html,
            'selector' => $css_selector,
        ));
    }

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


Question:
Formats a message using the I18N, or simple strtr if `\Yii::getApp()` is not available.
@param string $message
@param array $params
@since 2.0.12
@return string

public function formatMessage($message, $params)
    {
        $i18n = Yii::get('i18n', null, false);
        if (isset($i18n)) {
            return $i18n->format($message, $params);
        }

        return I18N::substitute($message, $params);
    }

public function callResult($id, $data = array()) {
        return $this->send(json_encode(array(WAMP::MSG_CALL_RESULT, $id, $data)));
    }

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


Question:
Update the major info.

@param Title $title
@param EventType $eventType
@param Location $location
@param CalendarInterface $calendar
@param Theme|null $theme

public function updateMajorInfo(
        Title $title,
        EventType $eventType,
        Location $location,
        CalendarInterface $calendar,
        Theme $theme = null
    ) {
        $this->apply(new MajorInfoUpdated($this->eventId, $title, $eventType, $location, $calendar, $theme));
    }

public function populateUpdateFields($data) {

        $data['id']                 = $this->request->input('id');
        $data['user_id']            = $this->request->input('user_id');
        $data['priority_id']        = $this->request->input('priority_id');

        if (isset($data['from_email_address'])) {
            $data['from_email_address'] = $this->request->input('from_email_address');
        }

        if (isset($data['from_name'])) {
            $data['from_name']          = $this->request->input('from_name');
        }

        if (isset($data['to_email_address'])) {
            $data['to_email_address']   = $this->request->input('to_email_address');
        }

        if (isset($data['to_name'] )) {
            $data['to_name']            = $this->request->input('to_name');
        }

        $data['priority_id']        = $this->request->input('priority_id');
        $data['archived']           = $this->request->input('archived');
        $data['updated_at']         = Carbon::now();
        $data['updated_by']         = Auth::user()->id;

        return $data;
    }

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


Question:
/*
execute request coming from the servlet engine in a separate thread or not

public boolean exeRequestAsync() {
	if (asyncReqHandle == null) asyncReqHandle = Caster.toBoolean(SystemUtil.getSystemPropOrEnvVar("lucee.async.request.handle", null), Boolean.FALSE);
	return asyncReqHandle;
    }

public <T> CompletableFuture<T> submit(Query<T> query) {
    State state = state();
    if (state == State.CLOSED || state == State.EXPIRED) {
      return Futures.exceptionalFuture(new ClosedSessionException("session closed"));
    }
    return submitter.submit(query);
  }

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


Question:
Removes the specified string from this set if it is present.
The set will not contain the specified string once the call
returns.
@param s the string to be removed
@return this object, for chaining

public final UnicodeSet remove(CharSequence s) {
        int cp = getSingleCP(s);
        if (cp < 0) {
            strings.remove(s.toString());
            pat = null;
        } else {
            remove(cp, cp);
        }
        return this;
    }

def _get_SEQRES_sequences(self):
        ''''''

        pdb_id = self.get_pdb_id()
        SEQRES_lines = self.parsed_lines["SEQRES"]

        modified_residue_mapping_3 = self.modified_residue_mapping_3
        # I commented this out since we do not need it for my current test cases
        #for k, v in self.modified_residues.iteritems():
        #    assert(v['modified_residue'] not in modified_residues)
        #    modified_residues[v['modified_residue']] = v['original_residue_3']

        for x in range(0, len(SEQRES_lines)):
            assert(SEQRES_lines[x][7:10].strip().isdigit())

        if not SEQRES_lines:
            #colortext.warning("WARNING: No SEQRES records were found. Kyle is trying to handle this gracefully, but Shane may need to fix it")
            return

        seqres_chain_order = []
        SEQRES_lines = [line[11:].rstrip() for line in SEQRES_lines] # we cannot strip the left characters as some cases e.g. 2MBP are missing chain identifiers

        # Collect all residues for all chains, remembering the chain order
        chain_tokens = {}
        for line in SEQRES_lines:
            chainID = line[0]
            if missing_chain_ids.get(self.pdb_id):
                chainID = missing_chain_ids[self.pdb_id]
            if chainID not in seqres_chain_order:
                seqres_chain_order.append(chainID)
            chain_tokens[chainID] = chain_tokens.get(chainID, [])
            chain_tokens[chainID].extend(line[6:].strip().split())

        sequences = {}
        self.chain_types = {}

        canonical_acid_types = set(residue_type_3to1_map.keys())
        canonical_acid_types.remove('UNK')
        assert(len(canonical_acid_types) == 20)

        for chain_id, tokens in chain_tokens.iteritems():

            # Determine whether the chain is DNA, RNA, or a protein chain
            # 1H38 is a good test for this - it contains DNA (chains E and G and repeated by H, K, N, J, M, P), RNA (chain F, repeated by I, L, O) and protein (chain D, repeated by A,B,C) sequences
            # 1ZC8 is similar but also has examples of DU
            # 4IHY has examples of DI (I is inosine)
            # 2GRB has RNA examples of I and U
            # 1LRP has protein chains with only CA atoms
            # This will throw an exception when a non-canonical is found which is not listed in basics.py. In that case, the list in basics.py should be updated.

            chain_type = None
            set_of_tokens = set(tokens)
            if (set_of_tokens.union(all_recognized_dna) == all_recognized_dna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'DNA'
            elif (set_of_tokens.union(all_recognized_rna) == all_recognized_rna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'RNA'
            elif len(set_of_tokens) == 1 and 'UNK' in set_of_tokens:
                chain_type = 'Unknown'
            elif not(set_of_tokens.intersection(canonical_acid_types)):
                # Zero canonical residues may imply a ligand or a heterogen chain
                chain_type = PDB._determine_heterogen_chain_type(set_of_tokens)
            else:
                assert(len(set(tokens).intersection(dna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                chain_type = 'Protein'
                if not self.chain_atoms.get(chain_id):
                    # possible for biological unit files
                    continue
                if self.chain_atoms[chain_id] == set(['CA']):
                    chain_type = 'Protein skeleton'

            # Get the sequence, mapping non-canonicals to the appropriate letter
            self.chain_types[chain_id] = chain_type

            sequence = []
            if chain_type == 'DNA':
                for r in tokens:
                    if dna_nucleotides_2to1_map.get(r):
                        sequence.append(dna_nucleotides_2to1_map[r])
                    else:
                        if non_canonical_dna.get(r):
                            sequence.append(non_canonical_dna[r])
                        else:
                            raise Exception("Unknown DNA residue %s." % r)
            elif chain_type == 'RNA':
                for r in tokens:
                    if r in rna_nucleotides:
                        sequence.append(r)
                    else:
                        if non_canonical_rna.get(r):
                            sequence.append(non_canonical_rna[r])
                        else:
                            raise Exception("Unknown RNA residue %s." % r)
            else:
                token_counter = 0
                for r in tokens:
                    token_counter += 1
                    if residue_type_3to1_map.get(r):
                        sequence.append(residue_type_3to1_map[r])
                    else:

                        if self.modified_residue_mapping_3.get(r):
                            sequence.append(residue_type_3to1_map[self.modified_residue_mapping_3.get(r)])
                        elif non_canonical_amino_acids.get(r):
                            #print('Mapping non-canonical residue %s to %s.' % (r, non_canonical_amino_acids[r]))
                            #print(SEQRES_lines)
                            #print(line)
                            sequence.append(non_canonical_amino_acids[r])
                        elif r == 'UNK':
                            continue
                        # Skip these residues
                        elif r == 'ACE' and token_counter == 1:
                            # Always allow ACE as the first residue of a chain
                            sequence.append('X')
                        elif r == 'ACE' and pdb_id in cases_with_ACE_residues_we_can_ignore:
                            sequence.append('X')
                            #continue
                        # End of skipped residues
                        else:
                            #print(modified_residue_mapping_3)
                            if modified_residue_mapping_3.get(r):
                                if modified_residue_mapping_3[r] == 'UNK':
                                    sequence.append('X')
                                else:
                                    assert(modified_residue_mapping_3[r] in residue_types_3)
                                    sequence.append(residue_type_3to1_map[modified_residue_mapping_3[r]])
                            else:
                                raise Exception("Unknown protein residue %s in chain %s." % (r, chain_id))
            sequences[chain_id] = "".join(sequence)

        self.seqres_chain_order = seqres_chain_order

        # Create Sequence objects for the SEQRES sequences
        for chain_id, sequence in sequences.iteritems():
            self.seqres_sequences[chain_id] = Sequence.from_sequence(chain_id, sequence, self.chain_types[chain_id])

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


Question:
Adds a Flash Message to the Flash Message Queue

@param FlashMessage $flashMessage

public function addFlashMessage(FlashMessage $flashMessage)
    {
        $flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
        $flashMessageQueue = $flashMessageService->getMessageQueueByIdentifier($this->messageQueueByIdentifier);
        $flashMessageQueue->enqueue($flashMessage);
    }

function(threadId, callback) {
                if (threadId) {
                    var tempSendQueue = [];

                    for (var i = 0; i < chatSendQueue.length; i++) {
                        if (chatSendQueue[i].threadId == threadId) {
                            tempSendQueue.push(chatSendQueue[i]);
                        }
                    }
                    callback && callback(tempSendQueue);
                }
                else {
                    callback && callback(chatSendQueue);
                }
            }

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


Question:
Reset all the internal variables to be able to send out a new email.

@return $this

public function reset()
    {
        $this->_to = [];
        $this->_from = [];
        $this->_sender = [];
        $this->_replyTo = [];
        $this->_readReceipt = [];
        $this->_returnPath = [];
        $this->_cc = [];
        $this->_bcc = [];
        $this->_messageId = true;
        $this->_subject = '';
        $this->_headers = [];
        $this->_textMessage = '';
        $this->_htmlMessage = '';
        $this->_message = [];
        $this->_emailFormat = 'text';
        $this->_transport = null;
        $this->_priority = null;
        $this->charset = 'utf-8';
        $this->headerCharset = null;
        $this->transferEncoding = null;
        $this->_attachments = [];
        $this->_profile = [];
        $this->_emailPattern = self::EMAIL_PATTERN;

        $this->viewBuilder()->setLayout('default');
        $this->viewBuilder()->setTemplate('');
        $this->viewBuilder()->setClassName('Cake\View\View');
        $this->viewVars = [];
        $this->viewBuilder()->setTheme(false);
        $this->viewBuilder()->setHelpers(['Html'], false);

        return $this;
    }

def _sendMsg(self, type, msg):

        if self.ALERT_STATUS and type in self.ALERT_TYPES:
            self._configMailer()
            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)

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


Question: /* Sets a bit, expanding the set size if necessary */

func (b *OpenBitSet) Set(index int64) {
	wordNum := b.expandingWordNum(index)
	bitmask := int64(1) << uint64(index&0x3f)
	b.bits[wordNum] |= bitmask
}

public static <T> boolean addAll(Collection<T> target, Iterator<? extends T> iterator) {
        Preconditions.checkArgumentNotNull(target, "target");
        boolean modified = false;
        while (iterator.hasNext()) {
            modified |= target.add(iterator.next());
        }
        return modified;
    }

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


Question: Get the directed edges from GO term to GO term.

def get_edges(self):
        """"""
        edge_from_to = []
        for parent, children in self.p_from_cs.items():
            for child in children:
                edge_from_to.append((child, parent))
        for parent, children in self.c_from_ps.items():
            for child in children:
                edge_from_to.append((child, parent))
        return edge_from_to

private function walkEdge(string $s, int $i, int $start, int $end): int
    {
        $text = $this->getS();
        for ($k = $start; $k <= $end && $i < strlen($s); $k++, $i++) {
            if ($text{$k} !== $s{$i}) {
                return -1;
            }
        }
        if (strlen($s) === $i) {
            return $k > $end ? 2 : 1;
        }
        return 0;
    }

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


Question: Add new typedef for both data and code.

def _typedef_both(t, base=0, item=0, leng=None, refs=None, kind=_kind_static, heap=False):
    '''
    '''
    v = _Typedef(base=_basicsize(t, base=base), item=_itemsize(t, item),
                 refs=refs, leng=leng,
                 both=True, kind=kind, type=t)
    v.save(t, base=base, heap=heap)
    return v

def record(self):
        # type: () -> bytes
        '''

        '''
        if not self._initialized:
            raise pycdlibexception.PyCdlibInternalError('El Torito Entry not yet initialized')

        return struct.pack(self.FMT, self.boot_indicator, self.boot_media_type,
                           self.load_segment, self.system_type, 0,
                           self.sector_count, self.load_rba,
                           self.selection_criteria_type,
                           self.selection_criteria)

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


Question:
Set read order

@param int $pValue
@return PHPExcel_Style_Alignment

public function setReadorder($pValue = 0)
    {
        if ($pValue < 0 || $pValue > 2) {
            $pValue = 0;
        }
        if ($this->isSupervisor) {
            $styleArray = $this->getStyleArray(array('readorder' => $pValue));
            $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray);
        } else {
            $this->readorder = $pValue;
        }
        return $this;
    }

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

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


Question:
@param AbstractModel $model

@return array

public function prepareCacheData(AbstractModel $model)
    {
        /**
         * @todo change MySQLTableData to a usecase based one
         */
        $tableData  = clone $this->tableData;
        $reflection = new \ReflectionClass($model);
        $tableData->setTableName($this->parseTableName($reflection));

        return [
            'tableData'    => $tableData,
            'reflection'   => new \ReflectionClass($model),
            'relationList' => $this->extractRelations($reflection),
        ];
    }

public function submit($options = [])
    {
        if (is_string($options)) {
            $options = ['value' => $options];
        }

        if (!Arr::has($options, 'type')) {
            Arr::set($options, 'type', 'submit');
        }

        $input = new Input($this->expression('input'), $options);

        return $input;
    }

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


Question:
Apply attributes to an HTML element.

@param  {Element} el         Target element.
@param  {Object=} attributes Element attributes to be applied.
@private
@function setElAttributes

function setElAttributes(el, attributes) {
  Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
    var attrValue = attributes[attrName];

    if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
      el.removeAttribute(attrName);
    } else {
      el.setAttribute(attrName, attrValue === true ? '' : attrValue);
    }
  });
}

function getBucket(path, name, parent){

		// Does it already exist?
		var id = prefix + path.replace(/\W/g,''),
			tab = doc.getElementById(id),
			label = doc.getElementById("label"+id);

		// Network
		var network = path.replace(/\:.*/, '');

		// Set current path
		if(!label&&name){
			label = doc.createElement('a');
			label.innerHTML = name;
			label.id = "label"+id;
			if(parent){
				label.setAttribute('data-parent', parent);
			}
			label.onclick = function(){
				getBucket(path, name, parent);
			};
			path_el.appendChild(label);
		}

		if(!tab){

			// create a new tab
			tab = doc.createElement('ul');
			tab.id = id;
			tab.innerHTML = "";
			body_el.appendChild(tab);

			// Remove loading
			var span = tab.getElementsByTagName('span')[0];

			// Login
			hello.login(network, function(auth){

				if(!auth||auth.error){
					span.setAttribute('data-message', "Signin failed, try again");
					span.setAttribute('data-animate', false);
					span.onclick = function(){
						tab.parentNode.removeChild(tab);
						getBucket(path, name, parent);
					};
					return;
				}

				span.setAttribute('data-message', "Loading files");

				// API
				hello.api(path, function(r){
					span.parentNode.removeChild(span);

					// Add files to the tab
					for(var i=0;i<r.data.length;i++){
						ref.push( new fileRef(r.data[i], network, tab) );
					}
				});
			});

		}

		// Hide the others
		// LISTS
		var a = body_el.children;
		for(var i=0;i=0;--i){
			if(parent&&a[i].id === "label"+parent){
				//parent = a[i].getAttribute('data-parent');
				a[i].style.display = "inline-block";
			}
			else if(a[i].id === "label"+id){
				a[i].style.display = "inline-block";
			}
			else{
				a[i].style.display = "none";
			}
		}

		// Update global
		current_folder = path;

		current_bucket = tab;

		current_network = network;

		// show this
		tab.style.display = 'block';

		// Update the upload btn
		upload_btn.innerHTML = name?"Upload to " + name.replace(/^[a-z]/,function(r){return r.toUpperCase();}):'Upload';
	}

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