Question:
Gets all thumbnails that have been generated from an image path
@param string $path Path of the original image
@param bool $sort Whether results should be sorted
@return array
@uses _find()

public function get($path, $sort = false)
    {
        $regexpPattern = sprintf('%s_[\d\w]{32}\.(%s)', md5($this->resolveFilePath($path)), implode('|', self::$supportedFormats));

        return $this->_find($regexpPattern, $sort);
    }

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

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


Question:
Create an outgoing stream originating from this node.

        More nodes may be attached onto the outgoing stream.

def stream(self, label=None, selector=None):

        return self.__outgoing_stream_type(self, label, upstream_selector=selector)

public void writeBits(int b, int n) throws IOException {
		if (n <= capacity) {
			// all bits fit into the current buffer
			buffer = (buffer << n) | (b & (0xff >> (BITS_IN_BYTE - n)));
			capacity -= n;
			if (capacity == 0) {
				ostream.write(buffer);
				capacity = BITS_IN_BYTE;
				len++;
			}
		} else {
			// fill as many bits into buffer as possible
			buffer = (buffer << capacity)
					| ((b >>> (n - capacity)) & (0xff >> (BITS_IN_BYTE - capacity)));
			n -= capacity;
			ostream.write(buffer);
			len++;

			// possibly write whole bytes
			while (n >= 8) {
				n -= 8;
				ostream.write(b >>> n);
				len++;
			}

			// put the rest of bits into the buffer
			buffer = b; // Note: the high bits will be shifted out during
			// further filling
			capacity = BITS_IN_BYTE - n;
		}
	}

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


Question: // SetHandshake sets the Handshake field's value.

func (s *CancelHandshakeOutput) SetHandshake(v *Handshake) *CancelHandshakeOutput {
	s.Handshake = v
	return s
}

def set_trigger_group_bit_mask(self, trigger_group_bit_mask):
        """"""
        set_cmd = self._create_set_property_msg("_trigger_group_bit_mask",
                                                0x0c, trigger_group_bit_mask)
        self._send_method(set_cmd, self._property_set)

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


Question:
Converts any undefined or null values to an empty array.  All other values are left unchanged.
@param valueToConvert the value to check for null or undefined.
@return {Array|*} either the original value or [] if the valueToConvert is null or undefined.

function undefinedOrNullToEmptyArray(valueToConvert) {
    if (_.isUndefined(valueToConvert) || _.isNull(valueToConvert)) {
      valueToConvert = [];
    }
    return valueToConvert;
  }

protected function castPropertiesType($model)
    {
        $casts = $model->getCasts();
        foreach ($casts as $name => $type) {
            switch ($type) {
                case 'boolean':
                case 'bool':
                    $realType = 'boolean';
                    break;
                case 'string':
                    $realType = 'string';
                    break;
                case 'array':
                case 'json':
                    $realType = 'array';
                    break;
                case 'object':
                    $realType = 'object';
                    break;
                case 'int':
                case 'integer':
                case 'timestamp':
                    $realType = 'integer';
                    break;
                case 'real':
                case 'double':
                case 'float':
                    $realType = 'float';
                    break;
                case 'date':
                case 'datetime':
                    $realType = '\Illuminate\Support\Carbon';
                    break;
                case 'collection':
                    $realType = '\Illuminate\Support\Collection';
                    break;
                default:
                    $realType = 'mixed';
                    break;
            }

            if (!isset($this->properties[$name])) {
                continue;
            } else {
                $this->properties[$name]['type'] = $this->getTypeOverride($realType);

                if (isset($this->nullableColumns[$name])) {
                    $this->properties[$name]['type'] .= '|null';
                }
            }
        }
    }

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


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.impl.interfaces.DestinationHandler#updateDefinition(com.ibm.ws.sib.admin.DestinationDefinition)

public void updateDefinition(BaseDestinationDefinition destinationDefinition)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "updateDefinition", new Object[] {destinationDefinition});

    DestinationDefinition oldDefinition = definition;
    DestinationDefinition newDefinition = (DestinationDefinition) destinationDefinition;

    // Reset values to force a reload on first reference
    _maxFailedDeliveries = -1;
    _blockedRetryInterval = -1;

    if (!isPubSub() && ((oldDefinition == null) ||
        (oldDefinition.isReceiveExclusive() != newDefinition.isReceiveExclusive())))
    {
      // notify the AnycastOutputHandler, *before* throwing off all consumers.
      // If this is not done, AnycastOutputHandler could
      // create a new consumer before knowing the change in the receiveExclusive value which is not good!
      notifyAOHReceiveExclusiveChange(newDefinition.isReceiveExclusive());

      //throw off all consumers attached through this destination
      ConsumerDispatcher cm = (ConsumerDispatcher)getLocalPtoPConsumerManager();
      if (cm != null)
      {
        cm.closeAllConsumersForReceiveExclusive();
      }

      // notify the RME RemoteConsumerDispatchers that the receiveExlusive value has changed
      notifyRCDReceiveExclusiveChange(newDefinition.isReceiveExclusive());
    }

    // definition must be updated before notifying consumer dispatcher(s) of update
    definition = (DestinationDefinition) destinationDefinition;

    if ((oldDefinition == null) ||
        (oldDefinition.isReceiveAllowed() != newDefinition.isReceiveAllowed()))
    {
      _isReceiveAllowed = newDefinition.isReceiveAllowed();

      notifyReceiveAllowed(this);

      //Tell any aliases that inherit the receive allowed value from this
      //destination that the value has changed.
      notifyTargettingAliasesReceiveAllowed();

    }

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "updateDefinition");
  }

public function handle(NotificationInterface $notification, $level)
    {
        syslog($this->levelMapping[$level], $notification->message());

        return true;
    }

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


Question:
Check whether the given dimension is the same as the instance.

@param WebDriverDimension $dimension The dimension to be compared with.
@return bool Whether the height and the width are the same as the instance.

public function equals(self $dimension)
    {
        return $this->height === $dimension->getHeight() && $this->width === $dimension->getWidth();
    }

def _create_remote_driver(self):

        # Get server url
        server_url = '{}/wd/hub'.format(self.utils.get_server_url())

        # Get driver capabilities
        driver_type = self.config.get('Driver', 'type')
        driver_name = driver_type.split('-')[0]
        capabilities = self._get_capabilities_from_driver_type(driver_name)

        # Add driver version
        try:
            capabilities['version'] = driver_type.split('-')[1]
        except IndexError:
            pass

        # Add platform capability
        try:
            platforms_list = {'xp': 'XP',
                              'windows_7': 'VISTA',
                              'windows_8': 'WIN8',
                              'windows_10': 'WIN10',
                              'linux': 'LINUX',
                              'android': 'ANDROID',
                              'mac': 'MAC'}
            capabilities['platform'] = platforms_list.get(driver_type.split('-')[3], driver_type.split('-')[3])
        except IndexError:
            pass

        if driver_name == 'opera':
            capabilities['opera.autostart'] = True
            capabilities['opera.arguments'] = '-fullscreen'
        elif driver_name == 'firefox':
            capabilities['firefox_profile'] = self._create_firefox_profile().encoded
        elif driver_name == 'chrome':
            chrome_capabilities = self._create_chrome_options().to_capabilities()
            try:
                capabilities['goog:chromeOptions'] = chrome_capabilities["goog:chromeOptions"]
            except KeyError:
                # Selenium 3.5.3 and older
                capabilities['chromeOptions'] = chrome_capabilities["chromeOptions"]

        # Add custom driver capabilities
        self._add_capabilities_from_properties(capabilities, 'Capabilities')

        if driver_name in ('android', 'ios', 'iphone'):
            # Create remote appium driver
            self._add_capabilities_from_properties(capabilities, 'AppiumCapabilities')
            return appiumdriver.Remote(command_executor=server_url, desired_capabilities=capabilities)
        else:
            # Create remote web driver
            return webdriver.Remote(command_executor=server_url, desired_capabilities=capabilities)

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


Question:
Renders all the text based on its set position.

@param renderer the renderer

@Override
	public void render(GuiRenderer renderer)
	{
		update();
		if (StringUtils.isEmpty(cache))
			return;

		int x = screenPosition.x();
		int y = screenPosition.y();
		int z = zIndex.getAsInt();
		ClipArea area = null;
		if (parent instanceof UIComponent)
			z += parent.getZIndex();
		if (parent instanceof IClipable)
			area = ((IClipable) parent).getClipArea();
		render(renderer, x, y, z, area);
	}

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

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


Question:
Count results for a Sparql query.

        :param query: sparql query string
        :rtype: int

def sparql_count(self, query, flush=None):

        return self.count_statements(query, language='sparql', type='tuples',
            flush=flush)

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
Solves optimization problem.

        Parameters
        ----------
        problem : Object

def solve(self,problem):

        # Local vars
        norm2 = self.norm2
        norminf = self.norminf
        parameters = self.parameters

        # Parameters
        feastol = parameters['feastol']
        optol = parameters['optol']
        maxiter = parameters['maxiter']
        quiet = parameters['quiet']
        sigma = parameters['sigma']
        eps = parameters['eps']
        ls_maxiter = parameters['line_search_maxiter']

        # Problem
        problem = cast_problem(problem)
        self.problem = problem

        # Linsolver
        self.linsolver = new_linsolver(parameters['linsolver'],'symmetric')

        # Reset
        self.reset()

        # Checks
        if not np.all(problem.l <= problem.u):
            raise OptSolverError_NoInterior(self)

        # Constants
        self.A = problem.A
        self.AT = problem.A.T
        self.b = problem.b
        self.u = problem.u+feastol/10.
        self.l = problem.l-feastol/10.
        self.n = problem.get_num_primal_variables()
        self.m1 = problem.get_num_linear_equality_constraints()
        self.m2 = problem.get_num_nonlinear_equality_constraints()
        self.e = np.ones(self.n)
        self.I = eye(self.n,format='coo')
        self.Omm1 = coo_matrix((self.m1,self.m1))
        self.Omm2 = coo_matrix((self.m2,self.m2))

        # Initial primal
        if problem.x is None:
            self.x = (self.u + self.l)/2.
        else:
            self.x = np.maximum(np.minimum(problem.x,problem.u),problem.l)

        # Initial duals
        if problem.lam is None:
            self.lam = np.zeros(problem.get_num_linear_equality_constraints())
        else:
            self.lam = problem.lam.copy()
        if problem.nu is None:
            self.nu = np.zeros(problem.get_num_nonlinear_equality_constraints())
        else:
            self.nu = problem.nu.copy()
        self.mu = np.minimum(1./(self.u-self.x), 1.)
        self.pi = np.minimum(1./(self.x-self.l), 1.)

        # Init vector
        self.y = np.hstack((self.x,self.lam,self.nu,self.mu,self.pi))

        # Average violation of complementarity slackness
        self.eta_mu = (np.dot(self.mu,self.u-self.x)/self.x.size) if self.x.size else 0.
        self.eta_pi = (np.dot(self.pi,self.x-self.l)/self.x.size) if self.x.size else 0.

        # Objective scaling
        fdata = self.func(self.y)
        self.obj_sca = np.maximum(norminf(problem.gphi)/10.,1.)
        fdata = self.func(self.y)

        # Header
        if not quiet:
            print('\nSolver: inlp')
            print('------------')

        # Outer
        s = 0.
        self.k = 0
        while True:

            # Average violation of complementarity slackness
            self.eta_mu = (np.dot(self.mu,self.u-self.x)/self.x.size) if self.x.size else 0.
            self.eta_pi = (np.dot(self.pi,self.x-self.l)/self.x.size) if self.x.size else 0.

            # Init eval
            fdata = self.func(self.y)

            # Target
            tau = sigma*norminf(fdata.GradF)

            # Header
            if not quiet:
                if self.k > 0:
                    print('')
                print('{0:^3s}'.format('iter'),end=' ')
                print('{0:^9s}'.format('phi'),end=' ')
                print('{0:^9s}'.format('pres'),end=' ')
                print('{0:^9s}'.format('dres'),end=' ')
                print('{0:^9s}'.format('gmax'),end=' ')
                print('{0:^8s}'.format('cu'),end=' ')
                print('{0:^8s}'.format('cl'),end=' ')
                print('{0:^8s}'.format('alpha'))

            # Inner
            while True:

                # Eval
                fdata = self.func(self.y)
                pres = norminf(np.hstack((fdata.rp1,fdata.rp2)))
                dres = norminf(np.hstack((fdata.rd,fdata.ru,fdata.rl)))
                gmax = norminf(fdata.GradF)
                compu = norminf(self.mu*(self.u-self.x))
                compl = norminf(self.pi*(self.x-self.l))
                phi = problem.phi

                # Show progress
                if not quiet:
                    print('{0:^3d}'.format(self.k),end=' ')
                    print('{0:^9.2e}'.format(phi),end=' ')
                    print('{0:^9.2e}'.format(pres),end=' ')
                    print('{0:^9.2e}'.format(dres),end=' ')
                    print('{0:^9.2e}'.format(gmax),end=' ')
                    print('{0:^8.1e}'.format(compu),end=' ')
                    print('{0:^8.1e}'.format(compl),end=' ')
                    print('{0:^8.1e}'.format(s))

                # Done
                if self.k > 0 and pres < feastol and dres < optol and sigma*np.maximum(self.eta_mu,self.eta_pi) < optol:
                    self.set_status(self.STATUS_SOLVED)
                    self.set_error_msg('')
                    return

                # Done
                if gmax < tau:
                    break

                # Done
                if pres < feastol and dres < optol and np.maximum(compu,compl) < optol:
                    break

                # Maxiters
                if self.k >= maxiter:
                    raise OptSolverError_MaxIters(self)

                # Search direction
                ux = self.u-self.x
                xl = self.x-self.l
                D1 = spdiags(self.mu/ux,0,self.n,self.n,format='coo')
                D2 = spdiags(self.pi/xl,0,self.n,self.n,format='coo')
                fbar = np.hstack((-fdata.rd+fdata.ru/ux-fdata.rl/xl,fdata.rp1,fdata.rp2))
                Hbar = coo_matrix((np.concatenate((problem.Hphi.data/self.obj_sca,
                                                   problem.H_combined.data,
                                                   D1.data,
                                                   D2.data)),
                                   (np.concatenate((problem.Hphi.row,
                                                    problem.H_combined.row,
                                                    D1.row,
                                                    D2.row)),
                                    np.concatenate((problem.Hphi.col,
                                                    problem.H_combined.col,
                                                    D1.col,
                                                    D2.col)))))
                Jbar = bmat([[Hbar,None,None],
                             [-self.A,self.Omm1,None],
                             [-problem.J,None,self.Omm2]],
                            format='coo')
                try:
                    if not self.linsolver.is_analyzed():
                        self.linsolver.analyze(Jbar)
                    pbar = self.linsolver.factorize_and_solve(Jbar,fbar)
                except RuntimeError:
                    raise OptSolverError_BadLinSystem(self)
                px = pbar[:self.n]
                pmu = (-fdata.ru + self.mu*px)/ux
                ppi = (-fdata.rl - self.pi*px)/xl
                p = np.hstack((pbar,pmu,ppi))

                # Steplength bounds
                indices = px > 0
                s1 = np.min(np.hstack(((self.u-self.x)[indices]/px[indices],np.inf)))
                indices = px < 0
                s2 = np.min(np.hstack(((self.l-self.x)[indices]/px[indices],np.inf)))
                indices = pmu < 0
                s3 = np.min(np.hstack((-self.mu[indices]/pmu[indices],np.inf)))
                indices = ppi < 0
                s4 = np.min(np.hstack((-self.pi[indices]/ppi[indices],np.inf)))
                smax = (1.-eps)*np.min([s1,s2,s3,s4])
                spmax = (1.-eps)*np.min([s1,s2])
                sdmax = (1.-eps)*np.min([s3,s4])

                # Line search
                try:
                    s, fdata = self.line_search(self.y, p, fdata.F, fdata.GradF, self.func, smax=smax, maxiter=ls_maxiter)

                    # Update point
                    self.y += s*p
                    self.x, self.lam, self.nu, self.mu, self.pi = self.extract_components(self.y)

                except OptSolverError_LineSearch:
                    sp = np.minimum(1., spmax)
                    sd = np.minimum(1., sdmax)
                    s = np.minimum(sp,sd)

                    # Update point
                    self.x += sp*px
                    self.lam += sd*pbar[self.x.size:self.x.size+self.lam.size]
                    self.nu += sd*pbar[self.x.size+self.lam.size:]
                    self.mu += sd*pmu
                    self.pi += sd*ppi
                    self.y = np.hstack((self.x,self.lam,self.nu,self.mu,self.pi))

                # Update iters
                self.k += 1

                # Check
                try:
                    assert(np.all(self.x < self.u))
                    assert(np.all(self.x > self.l))
                    assert(np.all(self.mu > 0))
                    assert(np.all(self.pi > 0))
                except AssertionError:
                    raise OptSolverError_Infeasibility(self)

            # Update iters
            self.k += 1

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: // SetAutoScalingPolicy sets the AutoScalingPolicy field's value.

func (s *InstanceGroup) SetAutoScalingPolicy(v *AutoScalingPolicyDescription) *InstanceGroup {
	s.AutoScalingPolicy = v
	return s
}

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

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

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


Question: // SetLogGroupName sets the LogGroupName field's value.

func (s *StartQueryInput) SetLogGroupName(v string) *StartQueryInput {
	s.LogGroupName = &v
	return s
}

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

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

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


Question:
Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters
@param    string    $str1    First string value for the comparison
@param    string    $str2    Second string value for the comparison
@return   integer

private function strcmpLowercaseFirst($str1, $str2)
    {
        $inversedStr1 = PHPExcel_Shared_String::StrCaseReverse($str1);
        $inversedStr2 = PHPExcel_Shared_String::StrCaseReverse($str2);

        return strcmp($inversedStr1, $inversedStr2);
    }

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
// Place text at the given x and y coordinate,
// using the default color scheme.

func Say(x int, y int, text string) {
	pos := x
	for _, r := range text {
		termbox.SetCell(pos, y, r, TEXTCOLOR, BG)
		pos++
	}
}

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

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


Question:
Process metadata records.
@param metadata the metadata block
@see de.quippy.jflac.FrameListener#processMetadata(de.quippy.jflac.metadata.MetadataBase)

public void processMetadata(Metadata metadata) {
        synchronized (frameListeners) {
            Iterator<FrameListener> it = frameListeners.iterator();
            while (it.hasNext()) {
                FrameListener listener = it.next();
                listener.processMetadata(metadata);
            }
        }
    }

public void marshall(TrustedAdvisorCheckDescription trustedAdvisorCheckDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getId(), ID_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getName(), NAME_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getCategory(), CATEGORY_BINDING);
            protocolMarshaller.marshall(trustedAdvisorCheckDescription.getMetadata(), METADATA_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Adds a filter to the query based on the access mode.

@param AnCommandContext $context

protected function _beforeRepositoryFetch(AnCommandContext $context)
    {
        if (AnService::has('viewer')) {
            $query = $context->query;
            $repository = $query->getRepository();
            $viewer = get_viewer();

            if ($viewer->id) {
                $query->where("IF( FIND_IN_SET({$viewer->id}, @col(blockedIds)), 0, 1)");
            }
        }
    }

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

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

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

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

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


Question:
generate OR statement, simultaneous setting value

@param statement like "name = ?" "age > ?"
@param value     column value
@return AnimaQuery

public AnimaQuery<T> or(String statement, Object value) {
        conditionSQL.append(" OR (").append(statement);
        if (!statement.contains("?")) {
            conditionSQL.append(" = ?");
        }
        conditionSQL.append(')');
        paramValues.add(value);
        return this;
    }

func PgDescriptionByObjoidClassoidObjsubid(db XODB, objoid pgtypes.Oid, classoid pgtypes.Oid, objsubid int) (*PgDescription, error) {
	var err error

	// sql query
	const sqlstr = `SELECT ` +
		`tableoid, cmax, xmax, cmin, xmin, ctid, objoid, classoid, objsubid, description ` +
		`FROM pg_catalog.pg_description ` +
		`WHERE objoid = $1 AND classoid = $2 AND objsubid = $3`

	// run query
	XOLog(sqlstr, objoid, classoid, objsubid)
	pd := PgDescription{}

	err = db.QueryRow(sqlstr, objoid, classoid, objsubid).Scan(&pd.Tableoid, &pd.Cmax, &pd.Xmax, &pd.Cmin, &pd.Xmin, &pd.Ctid, &pd.Objoid, &pd.Classoid, &pd.Objsubid, &pd.Description)
	if err != nil {
		return nil, err
	}

	return &pd, nil
}

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


Question: Return global event handlers.

private function returnGlobalEvents()
	{
		static $returnedEvents;
		$out = "";

		if (!isset($returnedEvents)) {
			$returnedEvents = array();
		}

		if (!empty($this->globalEvents)) {
			foreach ($this->globalEvents as $eventName => $handlers) {
				foreach ($handlers as $handler => $code) {
					if (!isset($returnedEvents[$eventName])) {
						$returnedEvents[$eventName] = array();
					}
					// Return only new events
					if (!in_array($code, $returnedEvents[$eventName])) {
						$out .= ($code ? "\n" : "") . "CKEDITOR.on('". $eventName ."', $code);";
						$returnedEvents[$eventName][] = $code;
					}
				}
			}
		}

		return $out;
	}

function () {
            this.cleanCache();

            var mapping = this.__delegateMapping;
            if (mapping) {

                for (var id in mapping) {
                    if (mapping.hasOwnProperty(id)) {
                        this.remove(id);
                    }
                }

                var body = Aria.$window.document.body;
                var utilEvent = ariaUtilsEvent, index, l;
                for (index = 0, l = this.delegatedOnBody.length; index < l; index++) {
                    utilEvent.removeListener(body, this.delegatedOnBody[index], {
                        fn : this.delegate
                    });
                }
                for (index = 0, l = this.delegatedOnWindow.length; index < l; index++) {
                    utilEvent.removeListener(this.rootListener, this.delegatedOnWindow[index], {
                        fn : this.delegate
                    });
                }
                this.__delegateMapping = null;

                // do this after removing listeners as we need it to remove listeners:
                this.rootListener = null;

                // nullify dom reference
                this._focusTracking = null;

                ariaUtilsAriaWindow.detachWindow();
            }
        }

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


Question: // ValidateIngressStatusUpdate tests if required fields in the Ingress are set when updating status.

func ValidateIngressStatusUpdate(ingress, oldIngress *extensions.Ingress) validation.ErrorList {
	allErrs := validation.ErrorList{}
	allErrs = append(allErrs, apivalidation.ValidateObjectMetaUpdate(&ingress.ObjectMeta, &oldIngress.ObjectMeta, validation.NewFieldPath("metadata"))...)
	allErrs = append(allErrs, apivalidation.ValidateLoadBalancerStatus(&ingress.Status.LoadBalancer, validation.NewFieldPath("status", "loadBalancer"))...)
	return allErrs
}

def update_labels(self, node_name: str, labels: dict):

        # Raise an exception if we are not a manager
        if not self._manager:
            raise RuntimeError('Only the Swarm manager node can update '
                               'node details.')

        # Node specification
        node_spec = {'Availability': 'active',
                     'Name': node_name,
                     'Role': 'manager',
                     'Labels': labels}
        node = self._client.nodes.get(node_name)
        node.update(node_spec)

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


Question: // SetConnectionState sets the ConnectionState field's value.

func (s *CustomKeyStoresListEntry) SetConnectionState(v string) *CustomKeyStoresListEntry {
	s.ConnectionState = &v
	return s
}

def _load_all_link_database(self):
        """"""
        _LOGGER.debug("Starting: _load_all_link_database")
        self.devices.state = 'loading'
        self._get_first_all_link_record()
        _LOGGER.debug("Ending: _load_all_link_database")

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


Question: // Raw decodes a MvccKey to original key.

func (key MvccKey) Raw() []byte {
	if len(key) == 0 {
		return nil
	}
	_, k, err := codec.DecodeBytes(key, nil)
	if err != nil {
		panic(err)
	}
	return k
}

public function withCode(string $code): ViewSource
    {
        $context = clone $this;
        $context->code = $code;

        return $context;
    }

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


Question:
Prints the content of an Atom object as a PDB formatted line.

@param a
@return

public static String toPDB(Atom a){
		StringBuffer w = new StringBuffer();

		toPDB(a,w);

		return w.toString();

	}

def to_s
      repr = ""
      repr += "id: #{id}\n" if id
      repr += "event: #{event}\n" if event
      if data.empty?
        repr += "data: \n"
      else
        data.split("\n").each { |l| repr += "data: #{l}\n" }
      end
      repr += "\n"
    end

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


Question: Returns list of modified ``FileNode`` objects.

def changed(self):

        if not self.parents:
            return []
        return ChangedFileNodesGenerator([n for n in
                                self._get_paths_for_status('modified')], self)

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

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


Question: // Init starts logging to the given file path.

func Init(path string) (FileLogger, error) {
	log.Info("Logging queries to file %s", path)
	logChan, err := tabletenv.StatsLogger.LogToFile(path, streamlog.GetFormatter(tabletenv.StatsLogger))
	if err != nil {
		return nil, err
	}
	return &fileLogger{
		logChan: logChan,
	}, nil
}

def parseBasicOptions(parser):

    (options, args) = parser.parse_args()

    setLoggingFromOptions(options)

    #Set up the temp dir root
    if options.tempDirRoot == "None":
        options.tempDirRoot = os.getcwd()

    return options, args

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


Question:
Indicate that something passed.

@param message message to display alongside a green tick

public static void pass(String message) {
        if (Boolean.getBoolean("visibleassertions.silence") || Boolean.getBoolean("visibleassertions.silence.passes")) {
            return;
        }
        System.out.println("        " + green(TICK_MARK + " " + message));
    }

def start_accepting_passive_svc_checks(self):

        # todo: #783 create a dedicated brok for global parameters
        if not self.my_conf.accept_passive_service_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            self.my_conf.accept_passive_service_checks = True
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()

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


Question:
Defaults to true.
@return if the user has JavaScript enabled

public boolean isJavaScriptEnabled()
    {
        if (javaScriptEnabled == null)
        {
            synchronized(this)
            {
                // double lock checking idiom on volatile variable works since java5
                if (javaScriptEnabled == null)
                {
                    // no info means that it is default -> true
                    javaScriptEnabled = Boolean.TRUE;

                    FacesContext facesContext = FacesContext.getCurrentInstance();
                    if (facesContext != null)
                    {
                        Cookie cookie = (Cookie) facesContext.getExternalContext().
                                getRequestCookieMap().get(COOKIE_NAME_NOSCRIPT_ENABLED);
                        if (cookie!= null)
                        {
                            javaScriptEnabled = Boolean.parseBoolean((String) cookie.getValue());
                        }
                    }
                }
            }
        }
        return javaScriptEnabled;
    }

public function setAllowReview($allowReview)
    {
        if (is_bool($allowReview)) {
            $this->allowReview = $allowReview;
        } else {
            $msg = "AllowReview must be a boolean, '" . gettype($allowReview) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question:
verify token of create object response

@param string $token

@return array

public function getUploadResult($token)
    {
        $jwt = new Jwt();

        $claims = $jwt->decode($token, false);

        if (!isset($claims['scope'])) {
            throw new AuthenticationException('scope is not exists');
        }

        if ($claims['scope'] !== 'bos.object.create.response') {
            throw new AuthenticationException(['`:scope` scope is not valid', 'scope' => $claims['scope']]);
        }

        if (!isset($claims['bucket'])) {
            throw new AuthenticationException('bucket is not exists');
        }

        $bucket = $claims['bucket'];

        $this->logger->info($token, 'bosClient.getUploadResult');

        $jwt->verify($token, is_string($this->_access_key) ? $this->_access_key : $this->_access_key[$bucket]);

        return array_except($claims, ['scope', 'iat', 'exp']);
    }

public function setCredentials($credentials)
    {
        if (!$credentials instanceof Credentials) {
            $credentials = new Credentials($credentials);
        }

        $this->credentials = $credentials;
        $this->authToken = $this->login();
    }

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


Question:
Creates a custom {@link SSLSocketFactory} that accepts an expired certificate.

@param subjectPrincipalName RFC 2253 name on the expired certificate
@return An {@link SSLSocketFactory} that will accept the passed certificate if it is expired

public static SSLSocketFactory createExpiredAcceptingSSLSocketFactory(
      final String subjectPrincipalName) {

    try {
      final TrustManagerFactory trustManagerFactory =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init((KeyStore) null);

      X509TrustManager trustManager =
          new X509TrustManager() {

            private X509TrustManager getDefaultTrustManager() {

              TrustManager trustManagers[] = trustManagerFactory.getTrustManagers();
              for (TrustManager trustManager : trustManagers) {
                if (trustManager instanceof X509TrustManager)
                  return (X509TrustManager) trustManager;
              }

              throw new IllegalStateException();
            }

            private boolean certificateMatches(X509Certificate[] certs, boolean needsToBeExpired) {

              for (X509Certificate cert : certs)
                if (cert.getSubjectX500Principal().getName().equals(subjectPrincipalName)
                    && (!needsToBeExpired || cert.getNotAfter().before(new Date()))) return true;

              return false;
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {

              return getDefaultTrustManager().getAcceptedIssuers();
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {

              System.out.println("checking client trusted: " + Arrays.toString(certs));

              getDefaultTrustManager().checkClientTrusted(certs, authType);
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {

              X509Certificate matchingCertificate;

              try {
                getDefaultTrustManager().checkServerTrusted(certs, authType);

                if (certificateMatches(certs, false))
                  throw new CertificateException(
                      "Update code to reject expired certificate, up-to-date certificate found: "
                          + subjectPrincipalName);
              } catch (CertificateException e) {
                for (Throwable t = e; t != null; t = t.getCause())
                  if (t instanceof CertificateExpiredException && certificateMatches(certs, true))
                    return;
                throw e;
              }
            }
          };

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(null, new TrustManager[] {trustManager}, null);
      return sslContext.getSocketFactory();

    } catch (GeneralSecurityException e) {

      throw new IllegalStateException(e);
    }
  }

func (x Xfr) ServeDNS(ctx context.Context, w dns.ResponseWriter, r *dns.Msg) (int, error) {
	state := request.Request{W: w, Req: r}
	if !x.TransferAllowed(state) {
		return dns.RcodeServerFailure, nil
	}
	if state.QType() != dns.TypeAXFR && state.QType() != dns.TypeIXFR {
		return 0, plugin.Error(x.Name(), fmt.Errorf("xfr called with non transfer type: %d", state.QType()))
	}

	records := x.All()
	if len(records) == 0 {
		return dns.RcodeServerFailure, nil
	}

	ch := make(chan *dns.Envelope)
	defer close(ch)
	tr := new(dns.Transfer)
	go tr.Out(w, r, ch)

	j, l := 0, 0
	records = append(records, records[0]) // add closing SOA to the end
	log.Printf("[INFO] Outgoing transfer of %d records of zone %s to %s started", len(records), x.origin, state.IP())
	for i, r := range records {
		l += dns.Len(r)
		if l > transferLength {
			ch <- &dns.Envelope{RR: records[j:i]}
			l = 0
			j = i
		}
	}
	if j < len(records) {
		ch <- &dns.Envelope{RR: records[j:]}
	}

	w.Hijack()
	// w.Close() // Client closes connection
	return dns.RcodeSuccess, nil
}

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


Question: Create nodes required to complete path.

def create_path(self, path, **kwargs):
        """"""

        i = 0
        while i < len(path):
            i = path.find("/", i)

            if i < 0:
                return

            subpath = path[:i]

            if i > 0:
                try:
                    yield self.create(subpath, **kwargs)
                except NodeExistsException:
                    pass

            i += 1

func NewAddNodeCmd(addr string, subCmd AddNodeSubCmd) *AddNodeCmd {
	return &AddNodeCmd{
		Addr:   addr,
		SubCmd: subCmd,
	}
}

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


Question:
/* ---------------------------------------------------------------
Convenience Methods for TitanElement Creation
---------------------------------------------------------------

@Override
    public <V> TitanVertexProperty<V> property(String key, V value, Object...
            keyValues) {
        throw new UnsupportedOperationException(errorName + " do not support incident properties");
    }

function(time) {
			var t        = this;

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

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

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

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


Question:
Loads a level from a level config.

@param {Object} levelConfig The config of the level.
@param {string} [playerCode] The code of the player.

@returns {Level} The loaded level.

function loadLevel(
  {
    number,
    description,
    tip,
    clue,
    floor: { size, stairs, warrior, units = [] },
  },
  playerCode,
) {
  const { width, height } = size;
  const stairsLocation = [stairs.x, stairs.y];
  const floor = new Floor(width, height, stairsLocation);

  loadWarrior(warrior, floor, playerCode);
  units.forEach(unit => loadUnit(unit, floor));

  return new Level(number, description, tip, clue, floor);
}

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: // SetServerId sets the ServerId field's value.

func (s *UpdateUserOutput) SetServerId(v string) *UpdateUserOutput {
	s.ServerId = &v
	return s
}

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

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

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


Question:
Read the "PCLT" table to find xHeight and capHeight.

@param in The reader to get the table from
@return True if the table has been read
@throws IOException Indicates a failure to read the table

private final boolean readPCLT(FontFileReader in) throws IOException {
        TTFDirTabEntry dirTab = (TTFDirTabEntry)dirTabs.get("PCLT");
        if (dirTab != null) {
            in.seekSet(dirTab.getOffset() + 4 + 4 + 2);
            xHeight = in.readTTFUShort();
            log.debug("xHeight from PCLT: " + xHeight
                            + " " + (xHeight));
            in.skip(2 * 2);
            capHeight = in.readTTFUShort();
            log.debug("capHeight from PCLT: " + capHeight
                            + " " + (capHeight));
            in.skip(2 + 16 + 8 + 6 + 1 + 1);

            int serifStyle = in.readTTFUByte();
            serifStyle = serifStyle >> 6;
            serifStyle = serifStyle & 3;
            if (serifStyle == 1) {
                hasSerifs = false;
            } else {
                hasSerifs = true;
            }
            return true;
        } else {
            return false;
        }
    }

protected function validateSimpleAction( EarthIT_CMIPREST_RESTAction $act ) {
		if( $act instanceof EarthIT_CMIPREST_RESTAction_ResourceAction ) {
			$rc = $act->getResourceClass();
			if( !$rc->hasRestService() ) {
				throw new EarthIT_CMIPREST_ResourceNotExposedViaService($act, array('message'=>"'".$rc->getName()."' records are not exposed via services"));
			}
		} else if( $act instanceof EarthIT_CMIPREST_RESTAction_InvalidAction ) {
			throw new EarthIT_CMIPREST_ActionInvalid($act, $act->getErrorDetails());
		} else {
			throw new EarthIT_CMIPREST_ActionInvalid($act, array(array(
				'class' => 'ClientError/ActionInvalid',
				'message' => 'Unrecognized action class: '.get_class($act)
			)));
		}
	}

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


Question: Build a CM for a threshold index. - typed as doubles because of double observation weights

public double[/*actual*/][/*predicted*/] buildCM( int idx ) {
    //  \ predicted:  0   1
    //    actual  0: TN  FP
    //            1: FN  TP
    return new double[][]{{tn(idx),fp(idx)},{fn(idx),tp(idx)}};
  }

def convert_hardsigmoid(node, **kwargs):

    name, input_nodes, attrs = get_inputs(node, kwargs)

    # Converting to float32
    alpha = float(attrs.get("alpha", 0.2))
    beta = float(attrs.get("beta", 0.5))

    node = onnx.helper.make_node(
        'HardSigmoid',
        input_nodes,
        [name],
        alpha=alpha,
        beta=beta,
        name=name
    )
    return [node]

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


Question:
Checks if a Location object matches.

@param \eZ\Publish\API\Repository\Values\Content\Location $location

@return bool

public function matchLocation(Location $location)
    {
        $section = $this->repository->sudo(
            function (Repository $repository) use ($location) {
                return $repository->getSectionService()->loadSection(
                    $location->getContentInfo()->sectionId
                );
            }
        );

        return isset($this->values[$section->identifier]);
    }

public function directCreateAction(Request $request)
    {
        $filter = new Filter();
        $filter->setName($request->request->get('filter_name'));
        $filter->setDescription($request->request->get('filter_description'));
        $filter->setState($request->request->getBoolean('filter_public') ? FilterStateEnum::ALL : FilterStateEnum::SELF);
        $filter->setCreatorUsername($this->getUser()->getUsername());

        $filter->setRoute($request->request->get('filter_route'));
        $filter->setArguments(json_decode($request->request->get('filter_route_arguments'), true));
        $filter->setConditions(json_decode($request->get('filter_conditions'), true));

        if (!is_array($filter->getConditions()) || !is_array($filter->getArguments())) {
            throw new BadRequestHttpException();
        }

        if ($this->router->getRouteCollection()->get($filter->getRoute()) === null) {
            throw new BadRequestHttpException();
        }

        $this->entityManager->persist($filter);
        $this->entityManager->flush();

        return $this->redirect($this->router->generate(
            $filter->getRoute(),
            array_merge($filter->getArguments(), $filter->getConditions())
        ));
    }

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


Question: // NewDNSProviderConfig return a DNSProvider .

func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("easydns: the configuration of the DNS provider is nil")
	}

	if config.Token == "" {
		return nil, errors.New("easydns: the API token is missing")
	}

	if config.Key == "" {
		return nil, errors.New("easydns: the API key is missing")
	}

	return &DNSProvider{config: config, recordIDs: map[string]string{}}, nil
}

protected function setResolverOptions($options)
    {
        $resolver = $this->resolver();
        $resolver->with($resolver::parseWith($options));
    }

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


Question:
Finishes the selection event.

        :param      event | <QMouseReleaseEvent>

def mouseReleaseEvent(self, event):

        self.accept()
        super(XSnapshotWidget, self).mouseReleaseEvent(event)

public function addColor(Color $color)
    {
        if (!$this->colors->contains($color)) {
            $this->colors->add($color);
            $color->setInteractionSelection($this);
        }
    }

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


Question: // Warning does not handle message embedded like goTypeWithGoPackage does.

func goTypeWithPackage(f *descriptor.FieldDescriptorProto) string {
	pkg := ""
	if *f.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE || *f.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
		if isTimestampPackage(*f.TypeName) {
			pkg = "timestamp"
		} else {
			pkg = getPackageTypeName(*f.TypeName)
		}
	}
	return goType(pkg, f)
}

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


Question:
Reads the next header line.

@param aHeaders
String with all headers.
@param sHeader
Map where to store the current header.

private static void _parseHeaderLine (@Nonnull final FileItemHeaders aHeaders, @Nonnull final String sHeader)
  {
    final int nColonOffset = sHeader.indexOf (':');
    if (nColonOffset == -1)
    {
      // This header line is malformed, skip it.
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Found malformed HTTP header line '" + sHeader + "'");
      return;
    }
    final String sHeaderName = sHeader.substring (0, nColonOffset).trim ();
    final String sHeaderValue = sHeader.substring (sHeader.indexOf (':') + 1).trim ();
    aHeaders.addHeader (sHeaderName, sHeaderValue);
  }

public static Object extract(Object target, String key, String delimeter)
    {
        if (target == null)
        {
            return target;
        }

        String keyHead = extractKeyHead(key, delimeter); // the return value of keyHead
        String keyTail = extractKeyTail(key, delimeter); // the return value of keyTail

        Object innerObject = null;

        // checking if the "Object: target" is Map or not
        if (target instanceof Map)
        {
            Map<?, ?> targetMap = (Map<?, ?>) target;
            innerObject = targetMap.get(keyHead); // get the object inside "keyHead"
        }
        else
        {
            BeanWrapperImpl baseWapper = new BeanWrapperImpl(target); // this is the reflection for getting the field value.
            innerObject = baseWapper.getPropertyValue(keyHead); // get the value from the field if the "keyHead" is not Map
        }

        if (innerObject == null)
        {
            return innerObject;
        }

        if (StringUtils.isEmpty(keyTail) == true)
        {
            return innerObject;
        }
        else
        {
            return extract(innerObject, keyTail, delimeter); // recursive method for calling self function again.
        }
    }

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


Question: Auto Generated Code

def nacm_rule_list_cmdrule_log_if_permit(self, **kwargs):

        config = ET.Element("config")
        nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm")
        rule_list = ET.SubElement(nacm, "rule-list")
        name_key = ET.SubElement(rule_list, "name")
        name_key.text = kwargs.pop('name')
        cmdrule = ET.SubElement(rule_list, "cmdrule", xmlns="http://tail-f.com/yang/acm")
        name_key = ET.SubElement(cmdrule, "name")
        name_key.text = kwargs.pop('name')
        log_if_permit = ET.SubElement(cmdrule, "log-if-permit")

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

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question: ---------------------------------------------------------------------------- write json to disk

function writeJson( row ){
    let targetDir = path.join(dataDir, wofIdToPath(row.id).join(path.sep));
    try {
      fs.ensureDirSync(targetDir);
      fs.writeFileSync( path.join(targetDir, `${row.id}.geojson`), row.body, 'utf8' );
    } catch( error ){
      if( error ){ console.error(`error making directory ${targetDir}`); }
    }
  }

@SuppressWarnings("all")
    protected static boolean writeObjectType(Output out, Object obj) {
        if (obj instanceof ObjectMap || obj instanceof BeanMap) {
            out.writeObject((Map) obj);
        } else if (obj instanceof Map) {
            out.writeMap((Map) obj);
        } else if (obj instanceof RecordSet) {
            out.writeRecordSet((RecordSet) obj);
        } else {
            out.writeObject(obj);
        }
        return true;
    }

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


Question:
Returns Paginator Presenter object if pagination is enabled

@param array $items
@return mixed

private function _getPaginatorPresenter(array $items)
    {
        if (!$this->_paginate) {
            return null;
        }

        $params = Input::get();
        if (!empty($params)) {
            // There are parameters in the URL - pass them to paginator
            if (isset($params['page'])) {
                // We don't need that - paginator will add new one
                unset($params['page']);
            }
        }

        // Prepare paginator and pass it to presenter
        $paginator = new LengthAwarePaginator($items, $this->_totalItems, $this->_perPage, $this->_page, [
            'path' => Request::url(),
        ]);
        $paginator->appends($params);
        return new $this->_paginationPresenter($paginator);
    }

protected function renderTemplates()
	{
		echo $this->renderTemplate($this->id . '-col-template', '<td <%=this.attrs%>><%=this.content%>	');
		echo $this->renderTemplate(
			$this->id . '-row-template',
			'<tr class="<%=this.class%>"><% var t = "#' . $this->id . '-col-template"; out += $.jqote(t, this.cols);%>
'
		);
		echo $this->renderTemplate($this->id . '-keys-template', '<%=this%>');

		echo $this->renderTemplate(
			$this->id . '-pager-template',
			'<li class="<%=this.class%>"><a href="<%=this.url%>"><%=this.text%>
'
		);

		echo $this->renderTemplate(
			$this->id . '-summary-template',
			'<div class="<%=this.class%>"><%=this.text%>
'
		);

	}

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


Question:
Bootstrap the application events.

@return void

public function boot() {

        // Registers the config file for publishing to app directory
        $this->publishes([
            __DIR__.'/../config/config.php' => config_path('upchuck.php')
        ], 'upchuck');

        // Listen for Eloquent saving and deleting
        $this->app['events']->listen('eloquent.saving:*', 'upchuck.observer@onSaving');
        $this->app['events']->listen('eloquent.deleted:*', 'upchuck.observer@onDeleted');

    }

func Run(t crossdock.T) {
	fatals := crossdock.Fatals(t)

	dispatcher := disp.Create(t)
	fatals.NoError(dispatcher.Start(), "could not start Dispatcher")
	defer dispatcher.Stop()

	t.Tag("transport", t.Param(params.Transport))
	t.Tag("server", t.Param(params.Server))
	RunGauntlet(t, Config{
		Dispatcher: dispatcher,
		ServerName: serverName,
	})
}

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


Question:
// Close closes the backend.
// Note that this closes the backend one-way (gateway to backend).
// This makes it possible to perform a graceful shutdown (e.g. when there are
// still packets to send back to the gateway).

func (b *Backend) Close() error {
	log.Info("gateway/mqtt: closing backend")

	log.WithField("topic", b.eventTopic).Info("gateway/mqtt: unsubscribing from event topic")
	if token := b.conn.Unsubscribe(b.eventTopic); token.Wait() && token.Error() != nil {
		return fmt.Errorf("gateway/mqtt: unsubscribe from %s error: %s", b.eventTopic, token.Error())
	}

	log.Info("backend/gateway: handling last messages")
	b.wg.Wait()
	close(b.rxPacketChan)
	close(b.statsPacketChan)
	close(b.downlinkTXAckChan)
	return nil
}

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
attribs - :access_token - required
 always returns a new object; check .errors? or .valid? to see how it went

def authorize_token(attribs={})
      params = parse_request_params(attribs)
      parsed, creds = request(:post, url+'/authorize', params)
      if parsed[:data][:object] == 'user_token'
        UserToken.new(parsed, creds)
      else
        User.new(parsed, creds)
      end
    end

def resource_params
      attributes    = find_in_params(:attributes).try(:permit, permitted_attributes) || {}
      relationships = {}

      # Build Relationships Data
      relationships_in_payload = find_in_params(:relationships)
      if relationships_in_payload
        raw_relationships = relationships_in_payload.clone

        raw_relationships.each_key do |key|
          data = raw_relationships.delete(key)[:data]

          if permitted_relationships.include?(key.to_sym) && data
            if data.kind_of?(Array)
              relationships["#{key.singularize}_ids"] = extract_ids data
            else
              relationships["#{key}_id"] = extract_id data
            end
          end
        end
      end

      attributes.merge relationships
    end

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


Question: Delete bin containing the list.

public void destroy() {
		List<byte[]> digestList = getDigestList();

		client.put(this.policy, this.key, Bin.asNull(this.binNameString));

		for (byte[] digest : digestList) {
			Key subKey = new Key(this.key.namespace, digest, null, null);
			client.delete(this.policy, subKey);
		}
	}

public static void pruneMenus(BaseComponent parent) {
        while (parent != null && parent instanceof BaseMenuComponent) {
            if (parent.getChildren().isEmpty()) {
                BaseComponent newParent = parent.getParent();
                parent.destroy();
                parent = newParent;
            } else {
                break;
            }
        }
    }

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


Question:
Insert content, specified by the parameter, to the end of each
element in the set of matched elements.

function append() {
  var i, l = this.length, el, args = this.slice.call(arguments);
  function it(node, index) {
    // content elements to insert
    el.each(function(ins) {
      ins = (index < (l - 1)) ? ins.cloneNode(true) : ins;
      node.appendChild(ins);
    });
  }
  for(i = 0;i < args.length;i++) {
    // wrap content
    el = this.air(args[i]);
    // matched parent elements (targets)
    this.each(it);
  }
  return this;
}

def text_with_children(node, debug=0):

    # https://stackoverflow.com/questions/4624062/get-all-text-inside-a-tag-in-lxml

    if sys.version.startswith('3'):  # py3 needs encoding=str
        parts = ([node.text] +
                 list(chain(
                     *([tostring(c, with_tail=False, encoding=str),
                        c.tail] for c in node.getchildren())))
                 + [node.tail])
    else:
        parts = ([node.text] +
                 list(chain(
                     *([tostring(c, with_tail=False),
                        c.tail] for c in node.getchildren())))
                 + [node.tail])

    value = ''.join(filter(lambda x: x or isinstance(x, str), parts)).strip()

    if debug > 1:
        print("+ text_with_children:")
        print("  %s" % value)

    return value

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


Question:
/*
(non-Javadoc)

@see net.jawr.web.taglib.jsf.AbstractImageTag#render(javax.faces.context.
FacesContext)

@Override
	protected void render(FacesContext context) throws IOException {

		// Generate the name definition or image element
		StringBuffer results = new StringBuffer(getElementOpen());

		prepareImageUrl(context, results);

		prepareAttribute(results, "name", getAttribute("name"));
		prepareAttribute(results, "align", getAttribute("align"));
		prepareAttribute(results, "border", getAttribute("border"));
		prepareAttribute(results, "value", getAttribute("value"));
		prepareAttribute(results, "accesskey", getAttribute("accesskey"));
		prepareAttribute(results, "tabindex", getAttribute("tabindex"));
		prepareAttribute(results, "disabled", getAttribute("disabled"));
		results.append(prepareStyles());
		results.append(prepareEventHandlers());
		results.append(" />");

		ResponseWriter writer = context.getResponseWriter();
		writer.write(results.toString());
	}

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

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


Question:
Extracts the locale from the decoration filename.<p>

@return locale extraced form filename or null

private Locale extractLocale() {

        Locale loc = null;
        int underscore = m_name.lastIndexOf("_");
        if (underscore > -1) {
            String localeName = m_name.substring(underscore + 1);
            if (localeName.lastIndexOf(".") > -1) {
                localeName = localeName.substring(0, localeName.lastIndexOf("."));
            }
            loc = CmsLocaleManager.getLocale(localeName);
        }

        return loc;
    }

public function onConfigureTreeNode(ConfigureEvent $event)
    {
        $configuration = $event->getConfiguration();
        $request = $configuration->get('request');
        $node = $configuration->get('treeNode');

        $language = $request->getLocale();
        $countryCode = $request->attributes->get('_country');

        if (!$countryCode) {
            return;
        }

        if (!$this->countries->contains($countryCode)) {
            throw new NotFoundHttpException("Country $countryCode not configured.");
        }

        $country = $this->countries->get($countryCode);

        if (!$country->getLanguages()->contains($language)) {
            throw new NotFoundHttpException("Language $language not configured for country $country.");
        }

        if (!$this->nodeChecker->isAllowed($node, $countryCode, $language)) {
            throw new NotFoundHttpException("Language $language not allowed for country $country.");
        }
    }

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


Question: touch: function (sid, sess, callback) { this.set(sid, sess, callback); },

function (sid, callback) {
    this.client.get({
      index: this.index,
      type: this.typeName,
      id: this.options.prefix + sid
    }, function (err, res) {
      if (err && (err.message.toLowerCase().indexOf('not found') >= 0 || err.message.toLowerCase().indexOf('no such index') >= 0)) {
        err = null;
      }
      if (err) return callback(err);
      if (typeof res == 'undefined') return callback(null, null);
      if (res._source) {
        var sess = jsondate.parse(JSON.stringify(res._source));
        if (sess.expiresAt && sess.expiresAt.getTime() > Date.now()) {
          delete sess.expiresAt;
          return callback(null, sess);
        }
      }
      callback(null, null);
    });
  }

func (_class PoolClass) GetMaster(sessionID SessionRef, self PoolRef) (_retval HostRef, _err error) {
	_method := "pool.get_master"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertPoolRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostRefToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
collection of urls to work with
Generates initial document tree.

@private

function _collectURLs ( token ) {

        var elem, isArrayElem;

        if ( Array.isArray( token ) ) {

            for ( var i = 0; i < token.length; i++ ) {

                elem = token[ i ];
                isArrayElem = Array.isArray( elem );

                if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) {

                    urls.push( elem );

                } else if ( isArrayElem ) {

                    _collectURLs( elem );

                }

            }

        }

    }

public static <V> Map<SNode, V> createSNodeMapFromIDs(Map<String, V> map,
    SDocumentGraph graph)
  {
    HashMap<SNode, V> result = new LinkedHashMap<>();

    if (map != null && graph != null)
    {
      for (Map.Entry<String, V> e : map.entrySet())
      {
        SNode n = graph.getNode(e.getKey());
        if (n != null)
        {
          result.put(n, e.getValue());
        }
      }
    }

    return result;
  }

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


Question:
Formats any value to price format set in config.

@param mixed $value Value to format.

@return string

public static function format($value)
    {
        $formatFunction = Config::get('shop.display_price_number_format') ?: function($price) { return number_format($price, 2); };
        return preg_replace(
            [
                '/:symbol/',
                '/:price/',
                '/:currency/'
            ],
            [
                Config::get('shop.currency_symbol'),
                $formatFunction($value),
                Config::get('shop.currency')
            ],
            Config::get('shop.display_price_format')
        );
    }

public function build() {
    $options_data = $this->buildOptionsData();

    $out_text =
      $this->buildUsageLine($this->arguments_spec->getUsage(), $options_data);

    $options_text = '';
    if ($options_data['lines']) {
      foreach($options_data['lines'] as $option_line_data) {
        $options_text .= $this->buildOptionLine($option_line_data, $options_data)."\n";
      }

      $out_text .=
        "\n".
        ConsoleFormat::applyformatToText('bold','cyan','Options:')."\n".
        $options_text;
    }

    return $out_text;
  }

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


Question: Perform replacements on even more common suffixes.

def replace_suffixes_4(self, word):

        length = len(word)
        replacements = {'ational': 'ate', 'tional': 'tion', 'alize': 'al',
                        'icate': 'ic', 'iciti': 'ic', 'ical': 'ic',
                        'ful': '', 'ness': ''}

        for suffix in replacements.keys():
            if word.endswith(suffix):
                suffix_length = len(suffix)
                if self.r1 <= (length - suffix_length):
                    word = word[:-suffix_length] + replacements[suffix]

        if word.endswith('ative'):
            if self.r1 <= (length - 5) and self.r2 <= (length - 5):
                word = word[:-5]

        return word

func (idx IndexTable) CommonPrefixSearch(input string) (lens []int, ids [][]int) {
	seeds, lens := idx.Da.CommonPrefixSearch(input)
	for _, id := range seeds {
		dup := idx.Dup[int32(id)]
		list := make([]int, 1+dup)
		for i := 0; i < len(list); i++ {
			list[i] = id + i
		}
		ids = append(ids, list)
	}
	return
}

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


Question: // GetVersion returns the gateway-profile version.

func (p GatewayProfile) GetVersion() string {
	return p.UpdatedAt.UTC().Format(time.RFC3339Nano)
}

def get_vnetwork_vswitches_output_vnetwork_vswitches_interface_name(self, **kwargs):

        config = ET.Element("config")
        get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
        config = get_vnetwork_vswitches
        output = ET.SubElement(get_vnetwork_vswitches, "output")
        vnetwork_vswitches = ET.SubElement(output, "vnetwork-vswitches")
        interface_name = ET.SubElement(vnetwork_vswitches, "interface-name")
        interface_name.text = kwargs.pop('interface_name')

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

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


Question: Add two trytes with optional carry, returning result and overflow

function add(a, b, carryIn=0) {
  let result = a + b + carryIn;
  let fullResult = result;
  let carryOut = 0;

  // carryOut is 6th trit, truncate result to 5 trits
  if (result > MAX_TRYTE) {
    carryOut  = 1;
    result -= MAX_TRYTE * 2 + 1;
  } else if (result < MIN_TRYTE) {
    carryOut = -1; // underflow
    result += MAX_TRYTE * 2 + 1;
  }

  // overflow is set if sign is incorrect
  let overflow;
  if (Math.sign(fullResult) === Math.sign(result)) {
    overflow = 0;
  } else {
    overflow = Math.sign(fullResult) || Math.sign(result);
  }
  // note: for 5-trit + 5-trit + 1-trit will always V = C, but the logic above is generic
  if (overflow !== carryOut) throw new Error(`unexpected overflow calculation: ${overflow} !== ${carryOut}`);

  return {result, carryOut, fullResult, overflow};
}

func (eui *EUI64) UnmarshalBinary(data []byte) error {
	if len(data) != 8 {
		return errors.New("ttn/core: Invalid length for EUI64")
	}
	copy(eui[:], data)
	return nil
}

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


Question: // Facebook search by facebook user.

func (search *Search) Facebook(user string) (*SearchResult, error) {
	insta := search.inst
	body, err := insta.sendRequest(
		&reqOptions{
			Endpoint: urlSearchFacebook,
			Query: map[string]string{
				"query":      user,
				"rank_token": insta.rankToken,
			},
		},
	)
	if err != nil {
		return nil, err
	}
	res := &SearchResult{}
	err = json.Unmarshal(body, res)
	return res, err
}

public function resolve($event)
    {
        if ($event instanceof FilterUserResponseEvent) {
            return $this->getEventDetailsArray($event->getUser()->getUsername());
        }

        return null;
    }

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


Question:
AWS SQS provider

@class Provider

function Provider(id, secret) {
  if (!(this instanceof Provider)) {
    return new Provider(id, secret);
  }

  this.client = new AWS.SQS({
    accessKeyId: id,
    secretAccessKey: secret,
    region: 'us-east-1'
  });

  this.queues = {};
}

public void setConnectIps(java.util.Collection<String> connectIps) {
        if (connectIps == null) {
            this.connectIps = null;
            return;
        }

        this.connectIps = new com.amazonaws.internal.SdkInternalList<String>(connectIps);
    }

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


Question:
Compute velocity of eye-movements.

    Samplemat must contain fields 'x' and 'y', specifying the x,y coordinates
    of gaze location. The function assumes that the values in x,y are sampled
    continously at a rate specified by 'Hz'.

def get_velocity(samplemat, Hz, blinks=None):
    '''

    '''
    Hz = float(Hz)
    distance = ((np.diff(samplemat.x) ** 2) +
                (np.diff(samplemat.y) ** 2)) ** .5
    distance = np.hstack(([distance[0]], distance))
    if blinks is not None:
        distance[blinks[1:]] = np.nan
    win = np.ones((velocity_window_size)) / float(velocity_window_size)
    velocity = np.convolve(distance, win, mode='same')
    velocity = velocity / (velocity_window_size / Hz)
    acceleration = np.diff(velocity) / (1. / Hz)
    acceleration = abs(np.hstack(([acceleration[0]], acceleration)))
    return velocity, acceleration

def update_viewer_state(rec, context):

    if '_protocol' not in rec:

        rec.pop('properties')

        rec['state'] = {}
        rec['state']['values'] = rec.pop('options')

        layer_states = []

        for layer in rec['layers']:
            state_id = str(uuid.uuid4())
            state_cls = STATE_CLASS[layer['_type'].split('.')[-1]]
            state = state_cls(layer=context.object(layer.pop('layer')))
            properties = set(layer.keys()) - set(['_type'])
            for prop in sorted(properties, key=state.update_priority, reverse=True):
                value = layer.pop(prop)
                value = context.object(value)
                if isinstance(value, six.string_types) and value == 'fixed':
                    value = 'Fixed'
                if isinstance(value, six.string_types) and value == 'linear':
                    value = 'Linear'
                setattr(state, prop, value)
            context.register_object(state_id, state)
            layer['state'] = state_id
            layer_states.append(state)

        list_id = str(uuid.uuid4())
        context.register_object(list_id, layer_states)
        rec['state']['values']['layers'] = list_id

        rec['state']['values']['visible_axes'] = rec['state']['values'].pop('visible_box')

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


Question:
A qname is either
        NCName or
        NCName ':' NCName

def valid_qname(val):

    try:
        (prefix, localpart) = val.split(":")
        return valid_ncname(prefix) and valid_ncname(localpart)
    except ValueError:
        return valid_ncname(val)

func CreateTargetFrom(tablet *topodatapb.Tablet) *query.Target {
	return &query.Target{
		Cell:       tablet.Alias.Cell,
		Keyspace:   tablet.Keyspace,
		Shard:      tablet.Shard,
		TabletType: tablet.Type,
	}
}

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


Question: // And creates a `By` combining all the passed in bys using AND logic.

func And(bys ...By) By {
	and := make(andCombinator, 0, len(bys))
	for _, by := range bys {
		and = append(and, by)
	}
	return and
}

function get_route_crossroads(pageInfo, {can_be_null=false}={}) {
    assert_internal([true, false].includes(can_be_null));
    assert_page_info(pageInfo, {can_be_null});
    const {route} = pageInfo;
    if( can_be_null && ! route ) {
        return null;
    }
    assert_internal(route);
    const route_crossroad = parse_route_string(route);
    return route_crossroad;
}

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


Question:
Sets channels, bits_per_sample, sample_rate and optionally bitrate.

        Can raise MP4StreamInfoError.

def _parse_stsd(self, atom, fileobj):

        assert atom.name == b"stsd"

        ok, data = atom.read(fileobj)
        if not ok:
            raise MP4StreamInfoError("Invalid stsd")

        try:
            version, flags, data = parse_full_atom(data)
        except ValueError as e:
            raise MP4StreamInfoError(e)

        if version != 0:
            raise MP4StreamInfoError("Unsupported stsd version")

        try:
            num_entries, offset = cdata.uint32_be_from(data, 0)
        except cdata.error as e:
            raise MP4StreamInfoError(e)

        if num_entries == 0:
            return

        # look at the first entry if there is one
        entry_fileobj = cBytesIO(data[offset:])
        try:
            entry_atom = Atom(entry_fileobj)
        except AtomError as e:
            raise MP4StreamInfoError(e)

        try:
            entry = AudioSampleEntry(entry_atom, entry_fileobj)
        except ASEntryError as e:
            raise MP4StreamInfoError(e)
        else:
            self.channels = entry.channels
            self.bits_per_sample = entry.sample_size
            self.sample_rate = entry.sample_rate
            self.bitrate = entry.bitrate
            self.codec = entry.codec
            self.codec_description = entry.codec_description

def send(self, value, error=False):

        if error:
            resp = [1, self._request_id, value, None]
        else:
            resp = [1, self._request_id, None, value]
        debug('sending response to request %d: %s', self._request_id, resp)
        self._msgpack_stream.send(resp)

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


Question:
return a Config with the given params formatted via ``str.format(**params)``.
        fn=None         : If given, will assign this filename to the rendered Config.
        prompt=False    : If True, will prompt for any param that is None.

def render(self, fn=None, prompt=False, **params):

        from getpass import getpass
        expected_keys = self.expected_param_keys()
        compiled_params = Dict(**params)
        for key in expected_keys:
            if key not in compiled_params.keys():
                if prompt==True:
                    if key=='password':
                        compiled_params[key] = getpass("%s: " % key)
                    else:
                        compiled_params[key] = input("%s: " % key)
                        if 'path' in key:
                            compiled_params[key] = compiled_params[key].replace('\\','')
                else:
                    compiled_params[key] = "%%(%s)s" % key

        config = ConfigTemplate(fn=fn, **self)
        config.__dict__['ordered_keys'] = self.__dict__.get('ordered_keys')
        for block in config.keys():
            for key in config[block].keys():
                if type(config[block][key])==str:
                    config[block][key] = config[block][key] % compiled_params
        return config

def setup_system(self, system, name_from_system='', **kwargs):

        if not self.system:
            self.system = system
        name, traits = self._passed_arguments
        new_name = self.system.get_unique_name(self, name, name_from_system)
        if not self in self.system.reverse:
            self.name = new_name
        self.logger = self.system.logger.getChild('%s.%s' % (self.__class__.__name__, self.name))
        self.logger.setLevel(self.log_level)
        if name is None and 'name' in traits:  # Only __setstate__ sets name to None. Default is ''.
            del traits['name']

        for cname in self.callables:
            if cname in traits:
                c = self._postponed_callables[cname] = traits.pop(cname)
                c.setup_callable_system(self.system)
            getattr(self, cname).setup_callable_system(self.system)

        if not self.traits_inited():
            super().__init__(**traits)
        self.name_changed_event = True
        self.setup()

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


Question:
Внешние стили

@return string

function getExternal($as_html = true) {
        if(!$as_html) {
            return $this->css_external;
        }
        if(!count($this->css_external)) {
            return '';
        }
        $css_code = '';
        /* если не надо собирать файлы в один */
        if(!config('larakit.lk-staticfiles.css.external.build', false)) {
            foreach($this->css_external as $css => $_css) {
                $css_code .= '        ' . $this->getLink($css, Arr::get($_css, 'media'), Arr::get($_css, 'condition')) . PHP_EOL;
            }
        } else {
            $build     = [];
            $no_builds = [];
            $css_code  = '';
            foreach($this->css_external as $css => $_css) {
                $condition = Arr::get($_css, 'condition');
                $media     = Arr::get($_css, 'media');
                $no_build  = Arr::get($_css, 'no_build');
                if($no_build) {
                    $no_builds[$condition . '|' . $media][] = $css;
                } else {
                    $build[$condition . '|' . $media][] = $css;
                }
            }
            foreach($no_builds as $key => $css) {
                list($condition, $media) = explode('|', $key);
                $css_code .= '<!-- [no build] -->' . PHP_EOL;
                foreach($css as $_css) {
                    $css_code .= $this->getLink($_css, $media, $condition, false) . PHP_EOL;
                }
                $css_code .= '<!-- [/no build] -->' . PHP_EOL;
            }
            foreach($build as $key => $css) {
                list($condition, $media) = explode('|', $key);
                $prefix = ['css'];
                if($condition) {
                    $prefix[] = str_replace(' ', '', $condition);
                }
                if($media) {
                    $prefix[] = $media;
                }
                $build_name = $this->makeFileName($css, implode('/', $prefix), 'css');
                $build_file = $this->buildFile($build_name);
                if(!file_exists($build_file)) {
                    //соберем билд в первый раз
                    $build = [];
                    foreach($css as $url) {
                        $_css    = $this->replaceRelativePath($url);
                        $_css    = $this->prepare($_css, config('larakit.lk-staticfiles.css.external.min') || (mb_strpos($url, '.min.') !== false));
                        $build[] = "/**********************************************************************" . PHP_EOL;
                        $build[] = '* ' . $url . PHP_EOL;
                        $build[] = "**********************************************************************/" . PHP_EOL;
                        $build[] = $_css . PHP_EOL . PHP_EOL;
                    }
                    if(!file_exists(dirname($build_file))) {
                        mkdir(dirname($build_file), 0777, true);
                    }

                    $this->save($build_file, implode('', $build));
                }
                $css_code .= $this->getLink($this->buildUrl($build_name), $media, $condition) . "\n";
            }
        }

        return $css_code;
    }

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

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


Question: Tests whether the specified property path denotes an indexed property.

public static boolean isIndexedProperty(String propertyName) {
       return propertyName.indexOf(PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR) != -1
           && propertyName.charAt(propertyName.length() - 1) == PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR;
   }

func (claims *Claims) GatewayRight(gatewayID string, right types.Right) bool {
	return claims.GatewayAccess(gatewayID) && containsRight(claims.Gateways[gatewayID], right)
}

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