Question: Decode bytes. Return a (text, encoding) tuple.

def _auto_decode(data):

    assert isinstance(data, six.binary_type)

    for e in ENCODINGS:
        try:
            return data.decode(e), e
        except UnicodeDecodeError:
            pass

    return data.decode('utf-8', 'ignore')

def get_content_type(
            self,
            bucket: str,
            key: str
    ) -> str:

        response = self.get_all_metadata(bucket, key)
        # hilariously, the ETag is quoted.  Unclear why.
        return response['ContentType']

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


def user_tags_delete(self, id, **kwargs):
        ""
        api_path = "/api/v2/users/{id}/tags.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, method="DELETE", **kwargs)

protected function stripTagAttributes($word)
    {
        $space = $this->stringUtil->strpos($word, ' ', 1);

        if ($space) {
            return '<' . $this->stringUtil->substr($word, 1, $space) . '>';
        }

        return trim($word, '<>');
    }

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


Question:
Handles methods corresponding to a tag name, ending with either
 _list or _attr, or starting with add_ .

def method_missing m, *args, &block
      if method_name_is_tag_name? m
        return assign_tag(m, args, &block)
      elsif method_name_is_tag_adder_method? m
        return extend_tag_list(m, args, &block)
      elsif method_name_is_tag_list_method? m
        return child_tags[m[0..-6].to_sym] ||= []
      elsif method_name_is_attr_accessor_method? m
        return assign_attribute(m[0..-6].to_sym, args, &block)
      end
      super(m, *args, &block)
    end

def _assign_faucets(self, faucets):
        """"""
        if not faucets:
            raise TypeError("Controller does not have a faucet assigned.")

        for faucet_id in faucets:
            self.faucets.append(
                RainCloudyFaucet(self._parent, self, faucet_id))

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


Question:
Get the validation rules that apply to the request.

@return array

public function rules(): array
    {
        $admin = $this->route('admin') ?? app('cortex.auth.admin');
        $admin->updateRulesUniques();
        $rules = $admin->getRules();

        $rules['roles'] = 'nullable|array';
        $rules['abilities'] = 'nullable|array';
        $rules['password'] = $admin->exists
            ? 'confirmed|min:'.config('cortex.auth.password_min_chars')
            : 'required|confirmed|min:'.config('cortex.auth.password_min_chars');

        return $this->isMethod('POST') ? $rules : [];
    }

protected void parseDeclaredAttributes() {
        ItemRuleMap attributeItemRuleMap = getRequestRule().getAttributeItemRuleMap();
        if (attributeItemRuleMap != null && !attributeItemRuleMap.isEmpty()) {
            ItemEvaluator evaluator = new ItemExpression(this);
            for (ItemRule itemRule : attributeItemRuleMap.values()) {
                Object value = evaluator.evaluate(itemRule);
                getRequestAdapter().setAttribute(itemRule.getName(), value);
            }
        }
    }

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


Question:
actions that get prevented by a lock are forwareded to this action
parameter view is currently ignored

public function locked()
    {
        $this->defaultData();
	    $resource = $this->getResource($this->getRequestParameter('id'));
	    $lockData = LockManager::getImplementation()->getLockData($resource);

	    $this->setData('topclass-label',
	        $this->hasRequestParameter('topclass-label') ? $this->getRequestParameter('topclass-label') : __('Resource')
        );

	    if (AclProxy::hasAccess($this->getSession()->getUser(), __CLASS__, 'forceRelease', array('uri' => $resource->getUri()))) {
	        $this->setData('id', $resource->getUri());
            $this->setData('forceRelease', true);
	    }

	    $this->setData('lockDate', $lockData->getCreationTime());
	    $this->setData('ownerHtml', UserHelper::renderHtmlUser($lockData->getOwnerId()));

	    if ($this->hasRequestParameter('view') && $this->hasRequestParameter('ext')) {
	        $this->setView($this->getRequestParameter('view'), $this->getRequestParameter('ext'));
	    } else {
	        $this->setView('Lock/locked.tpl', 'tao');
	    }
	}

func (c *FakeControllerRevisions) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(controllerrevisionsResource, c.ns, opts))

}

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


Question:
Prepare a list of identity providers for output.

@param array $identityproviders as returned by {@link self::get_identity_providers()}
@param renderer_base $output
@return array the identity providers ready for output

public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
        $data = [];
        foreach ($identityproviders as $idp) {
            if (!empty($idp['icon'])) {
                // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
                $idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
            }
            if ($idp['iconurl'] instanceof moodle_url) {
                $idp['iconurl'] = $idp['iconurl']->out(false);
            }
            unset($idp['icon']);
            if ($idp['url'] instanceof moodle_url) {
                $idp['url'] = $idp['url']->out(false);
            }
            $data[] = $idp;
        }
        return $data;
    }

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question: // SetAvailabilityZone sets the AvailabilityZone field's value.

func (s *DevEndpoint) SetAvailabilityZone(v string) *DevEndpoint {
	s.AvailabilityZone = &v
	return s
}

def zone_schedules_backup(self, filename):
        """"""
        _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...",
                     self.systemId, self.location.name)

        schedules = {}

        if self.hotwater:
            _LOGGER.info("Retrieving DHW schedule: %s...",
                         self.hotwater.zoneId)

            schedule = self.hotwater.schedule()
            schedules[self.hotwater.zoneId] = {
                'name': 'Domestic Hot Water',
                'schedule': schedule}

        for zone in self._zones:
            zone_id = zone.zoneId
            name = zone.name

            _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name)

            schedule = zone.schedule()
            schedules[zone_id] = {'name': name, 'schedule': schedule}

        schedule_db = json.dumps(schedules, indent=4)

        _LOGGER.info("Writing to backup file: %s...", filename)
        with open(filename, 'w') as file_output:
            file_output.write(schedule_db)

        _LOGGER.info("Backup completed.")

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


Question:
重定向到404
@param int $code
@throws SwooleException
@throws SwooleRedirectException

protected function redirect404($code = 302)
    {
        $location = 'http://' . $this->request->header['host'] . "/" . '404';
        $this->redirect($location, $code);
    }

def run(self):

        if self.init_error:
            logger.error('init error: %r did not exist at initialization time',
                         self.wal_e.env_dir)
            return ExitCode.FAIL

        try:
            should_use_s3 = self.should_use_s3_to_create_replica()
            if should_use_s3 is None:  # Need to retry
                return ExitCode.RETRY_LATER
            elif should_use_s3:
                return self.create_replica_with_s3()
            elif not should_use_s3:
                return ExitCode.FAIL
        except Exception:
            logger.exception("Unhandled exception when running WAL-E restore")
        return ExitCode.FAIL

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


Question:
Set the default values of the options
@param {Object} options Options object as passed to the constructor

function (options) {

			inputEx.SelectTwiceField.superclass.setOptions.call(this, options);

			this.options.choices = lang.isArray(options.choices) ? options.choices : [];

			this.options.valueSeparator = options.valueSeparator || "_";

		}

protected function substituteImplicitBindings( $route )
	{
		$parameters = $route->parameters();

		foreach ( $route->signatureParameters( Model::class ) as $parameter )
		{
			$class = $parameter->getClass();

			if ( array_key_exists( $parameter->name, $parameters ) && !$route->getParameter( $parameter->name ) instanceof Model )
			{
				$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';

				$model = $class->newInstance();

				$route->setParameter( $parameter->name, $model->where( $model->getRouteKeyName(), $parameters[$parameter->name] )->{$method()} );
			}
		}
	}

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


Question:
Generate string with entity class name and a list of the entity values

@param \Twizo\Api\AbstractEntity $entity

@return string

public static function getEntity(\Twizo\Api\AbstractEntity $entity)
    {
        $result = '';
        $values = self::getEntityValues($entity);

        $result .= str_repeat('-', strlen(get_class($entity)) + 4) . PHP_EOL;
        $result .= '| ' . get_class($entity) . ' |' . PHP_EOL;
        $result .= str_repeat('-', strlen(get_class($entity)) + 4) . PHP_EOL;

        foreach ($values as $method => $value) {
            $result .= substr($method, 3) . ' : ' . var_export($value, true) . PHP_EOL;
        }

        return $result;
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question: Parse the response, returning a dictionary.

def _parse(self, registers):
        """"""
        result = {'ip': self.ip, 'connected': True}
        decoder = BinaryPayloadDecoder.fromRegisters(registers,
                                                     byteorder=Endian.Big,
                                                     wordorder=Endian.Little)
        # Register 40001 is a collection of alarm status signals
        b = [decoder.decode_bits(), decoder.decode_bits()]
        reg_40001 = b[1] + b[0]
        # Bits 0-3 map to the monitor state
        monitor_integer = sum(1 << i for i, b in enumerate(reg_40001[:4]) if b)
        result['state'] = options['monitor state'][monitor_integer]
        # Bits 4-5 map to fault status
        fault_integer = sum(1 << i for i, b in enumerate(reg_40001[4:6]) if b)
        result['fault'] = {'status': options['fault status'][fault_integer]}
        # Bits 6 and 7 tell if low and high alarms are active
        low, high = reg_40001[6:8]
        result['alarm'] = options['alarm level'][low + high]
        # Bits 8-10 tell if internal sensor relays 1-3 are energized. Skipping.
        # Bit 11 is a heartbeat bit that toggles every two seconds. Skipping.
        # Bit 12 tells if relays are under modbus control. Skipping.
        # Remaining bits are empty. Skipping.
        # Register 40002 has a gas ID and a sensor cartridge ID. Skipping.
        decoder._pointer += 2
        # Registers 40003-40004 are the gas concentration as a float
        result['concentration'] = decoder.decode_32bit_float()
        # Register 40005 is the concentration as an int. Skipping.
        decoder._pointer += 2
        # Register 40006 is the number of the most important fault.
        fault_number = decoder.decode_16bit_uint()
        if fault_number != 0:
            code = ('m' if fault_number < 30 else 'F') + str(fault_number)
            result['fault']['code'] = code
            result['fault'].update(faults[code])
        # Register 40007 holds the concentration unit in the second byte
        # Instead of being an int, it's the position of the up bit
        unit_bit = decoder.decode_bits().index(True)
        result['units'] = options['concentration unit'][unit_bit]
        decoder._pointer += 1
        # Register 40008 holds the sensor temperature in Celsius
        result['temperature'] = decoder.decode_16bit_int()
        # Register 40009 holds number of hours remaining in cell life
        result['life'] = decoder.decode_16bit_uint() / 24.0
        # Register 40010 holds the number of heartbeats (16 LSB). Skipping.
        decoder._pointer += 2
        # Register 40011 is the sample flow rate in cc / min
        result['flow'] = decoder.decode_16bit_uint()
        # Register 40012 is blank. Skipping.
        decoder._pointer += 2
        # Registers 40013-40016 are the alarm concentration thresholds
        result['low-alarm threshold'] = round(decoder.decode_32bit_float(), 6)
        result['high-alarm threshold'] = round(decoder.decode_32bit_float(), 6)
        # Despite what the manual says, thresholds are always reported in ppm.
        # Let's fix that to match the concentration units.
        if result['units'] == 'ppb':
            result['concentration'] *= 1000
            result['low-alarm threshold'] *= 1000
            result['high-alarm threshold'] *= 1000
        return result

def dehydrate(self, iterator):

        for line in iterator:
            try:
                yield json.loads(line)['id_str']
            except Exception as e:
                log.error("uhoh: %s\n" % e)

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


Question:
/* (non-Javadoc)
@see org.apache.hadoop.hbase.client.Admin#truncateTableAsync(org.apache.hadoop.hbase.TableName, boolean)

@Override
  public Future<Void> truncateTableAsync(TableName tableName, boolean preserveSplits) throws IOException {
   if (!preserveSplits) {
      LOG.info("truncate will preserveSplits. The passed in variable is ignored.");
   }
   return FutureUtils.toCompletableFuture(
        tableAdminClientWrapper
          .dropAllRowsAsync(tableName.getNameAsString()));
  }

public function delete(array $where, $tableName = null)
    {
        $tableName = $tableName ?: $this->getTableName();
        $sql = $this->getSql();
        $delete = $sql->delete($tableName);

        $delete->where($where);

        $statement = $sql->prepareStatementForSqlObject($delete);

        return $statement->execute();
    }

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


Question:
definePath

@param integer $id
@param string $title
@param string $extension

@return string

public function definePath($id, $title, $extension, $prefix = '', $suffix = '')
    {
        $path = '';

        if ($suffix) {
            $path = sprintf(
                '%s/%s-%s%s-%s.%s',
                $this->getCurrentDirectory(),
                (new \DateTime())->format('His'),
                $prefix,
                Canonicalizer::slug($title),
                $suffix,
                $extension
            );
        } else {
            $path = sprintf(
                '%s/%s-%s%s.%s',
                $this->getCurrentDirectory(),
                (new \DateTime())->format('His'),
                $prefix,
                Canonicalizer::slug($title),
                $extension
            );
        }

        if (file_exists(sprintf('%s/%s', $this->rootDir, $path))) {
            return $this->definePath($id, $title, $extension, $prefix, intval($suffix) + 1);
        }

        return $path;
    }

def _ParseShellItemPathSegment(self, shell_item):

    path_segment = None

    if isinstance(shell_item, pyfwsi.root_folder):
      description = shell_folder_ids.DESCRIPTIONS.get(
          shell_item.shell_folder_identifier, None)

      if description:
        path_segment = description
      else:
        path_segment = '{{{0:s}}}'.format(shell_item.shell_folder_identifier)

      path_segment = '<{0:s}>'.format(path_segment)

    elif isinstance(shell_item, pyfwsi.volume):
      if shell_item.name:
        path_segment = shell_item.name
      elif shell_item.identifier:
        path_segment = '{{{0:s}}}'.format(shell_item.identifier)

    elif isinstance(shell_item, pyfwsi.file_entry):
      long_name = ''
      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name

      if long_name:
        path_segment = long_name
      elif shell_item.name:
        path_segment = shell_item.name

    elif isinstance(shell_item, pyfwsi.network_location):
      if shell_item.location:
        path_segment = shell_item.location

    if path_segment is None and shell_item.class_type == 0x00:
      # TODO: check for signature 0x23febbee
      pass

    if path_segment is None:
      path_segment = '<UNKNOWN: 0x{0:02x}>'.format(shell_item.class_type)

    return path_segment

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


Question:
Generates a URI based on a serial stored in the database.

@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@return string
@throws common_UriProviderException

public function provide()
    {
        $returnValue = (string) '';

        $dbWrapper = core_kernel_classes_DbWrapper::singleton();
        try {
            $sth = $this->getPersistence()->query($this->getPersistence()->getPlatForm()->getSqlFunction("generis_sequence_uri_provider"), array(
                    $this->getOption(self::OPTION_NAMESPACE)
            ));

            if ($sth !== false) {

                $row = $sth->fetch();

                $returnValue = current($row);
                $sth->closeCursor();
            } else {
                throw new UriProviderException("An error occured while calling the stored procedure for persistence ".$this->getOption(self::OPTION_PERSISTENCE).".");
            }
        } catch (Exception $e) {
        	throw new UriProviderException("An error occured while calling the stored ': " . $e->getMessage() . ".");
        }

        return (string) $returnValue;
    }

private BadRequestException getBadRequestException(Exception ex) {
	    return (BadRequestException) ExceptionUtils
	            .getThrowables(ex)[ExceptionUtils.indexOfThrowable(ex, BadRequestException.class)];
	}

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


Question:
Delete cached images from the cache

@param EventInterface $event The current event

public function deleteFromCache(EventInterface $event) {
        $request = $event->getRequest();
        $cacheDir = $this->getCacheDir($request->getUser(), $request->getImageIdentifier());

        if (is_dir($cacheDir)) {
            $this->rmdir($cacheDir);
        }
    }

public function terminate()
    {
        if (!$this->application || false === $this->application->isStarted()) {
            return;
        }

        ob_implicit_flush(true);
        flush();

        // $response may not be set
        if ($this->response instanceof Response) {
            $this->application->getEventDispatcher()->dispatch(
                KernelEvents::TERMINATE,
                new PostResponseEvent($this, $this->getRequest(), $this->response)
            );
        }
    }

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


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

@SuppressWarnings("unchecked")
	@Override
	public EList<Double> getCoordinates() {
		return (EList<Double>) eGet(Ifc4Package.Literals.IFC_CARTESIAN_POINT__COORDINATES, true);
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
Creates data provider instance with search query applied

@param array $params

@return ActiveDataProvider

public function search($params)
    {
        $query = Order::find()->where(['not in','status', [OrderStatus::STATUS_INCOMPLETE]]);

        $query->orderBy(['status' => SORT_ASC, 'id' => SORT_DESC]);

        // add conditions that should always apply here

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

        $this->load($params);

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

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

        $query
            ->andFilterWhere(['like', 'status', $this->status])
            ->andFilterWhere(['like', 'uid', $this->uid]);
        return $dataProvider;
    }

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

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

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


Question: // Printf is part of the Logger interface

func (cl *ConsoleLogger) Printf(format string, v ...interface{}) {
	fmt.Printf(format, v...)
}

protected function writeln($messages, $verbosity = OutputInterface::VERBOSITY_NORMAL)
    {
        $this->write($messages, true, $verbosity);
    }

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


Question:
Get configuration for plugin.

@param string $key The name of the parameter to retrieve the configurations.
@return mixed Configuration for plugin

public function getConfig($key = null) {
		$configPath = 'CakeSettingsApp';
		if (!empty($key)) {
			$configPath .= '.' . $key;
		}

		$result = Configure::read($configPath);

		return $result;
	}

static public function config($config = array())
    {
        !empty($config) && self::$config = array_merge(self::$config, $config);
        if (!empty(self::$config['cachepath'])) {
            Cache::$cachepath = self::$config['cachepath'];
        }
        if (empty(self::$config['component_verify_ticket'])) {
            self::$config['component_verify_ticket'] = Cache::get('component_verify_ticket');
        }
        if (empty(self::$config['token']) && !empty(self::$config['component_token'])) {
            self::$config['token'] = self::$config['component_token'];
        }
        if (empty(self::$config['appsecret']) && !empty(self::$config['component_appsecret'])) {
            self::$config['appsecret'] = self::$config['component_appsecret'];
        }
        if (empty(self::$config['encodingaeskey']) && !empty(self::$config['component_encodingaeskey'])) {
            self::$config['encodingaeskey'] = self::$config['component_encodingaeskey'];
        }
        return self::$config;
    }

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


Question:
Sort tau matrix by dependece with variable y.

        Args:
            :param y: index of variable of intrest
            :type y: int

def _sort_tau_by_y(self, y):

        # first column is the variable of interest
        tau_y = self.tau_matrix[:, y]
        tau_y[y] = np.NaN

        temp = np.empty([self.n_nodes, 3])
        temp[:, 0] = np.arange(self.n_nodes)
        temp[:, 1] = tau_y
        temp[:, 2] = abs(tau_y)
        temp[np.isnan(temp)] = -10
        tau_sorted = temp[temp[:, 2].argsort()[::-1]]

        return tau_sorted

def _build_session_metric_values(self, session_name):
    """"""

    # result is a list of api_pb2.MetricValue instances.
    result = []
    metric_infos = self._experiment.metric_infos
    for metric_info in metric_infos:
      metric_name = metric_info.name
      try:
        metric_eval = metrics.last_metric_eval(
            self._context.multiplexer,
            session_name,
            metric_name)
      except KeyError:
        # It's ok if we don't find the metric in the session.
        # We skip it here. For filtering and sorting purposes its value is None.
        continue

      # metric_eval is a 3-tuple of the form [wall_time, step, value]
      result.append(api_pb2.MetricValue(name=metric_name,
                                        wall_time_secs=metric_eval[0],
                                        training_step=metric_eval[1],
                                        value=metric_eval[2]))
    return result

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


Question:
Initialize.

@param tr
the tr
@param m
the m
@param entity
the entity
@param tr
@return the object
@throws InstantiationException
the instantiation exception
@throws IllegalAccessException
the illegal access exception

public static Object initialize(Class clazz, Object record)
    {
        try
        {
            if (record == null)
            {
                record = createNewInstance(clazz);
            }
            return record;
        }
        catch (Exception e)
        {
            throw new PersistenceException("Error occured while instantiating entity.", e);
        }
    }

public void addField(String fieldName) throws QueryException {
		EReference feature = null;
		for (TypeDef typeDef : types) {
			if (typeDef.geteClass().getEStructuralFeature(fieldName) == null) {
				throw new QueryException("Class \"" + typeDef.geteClass().getName() + "\" does not have the field \"" + fieldName + "\"");
			}
			if (feature == null) {
				if (!(typeDef.geteClass().getEStructuralFeature(fieldName) instanceof EReference)) {
					throw new QueryException(fieldName + " is not a reference");
				}
				feature = (EReference) typeDef.geteClass().getEStructuralFeature(fieldName);
			} else {
				if (feature != typeDef.geteClass().getEStructuralFeature(fieldName)) {
					throw new QueryException("Classes \"" + typeDef.geteClass().getName() + "\" and \"" + feature.getEContainingClass().getName() + "\" have fields with the same name, but they are not logically the same");
				}
			}
		}
		if (fields == null) {
			fields = new ArrayList<>();
		}
		fields.add(feature);
	}

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


Question:
Checks the Critical Value to determine if the Hypothesis should be rejected

@param score
@param n
@param k
@param is_twoTailed
@param aLevel
@return

public static boolean checkCriticalValue(double score, int n, int k, boolean is_twoTailed, double aLevel) {
        /*
        if(n<=200 && k<=20) {
            //Calculate it from tables
            //http://www3.nd.edu/~wevans1/econ30331/Durbin_Watson_tables.pdf
        }
        */

        //Follows normal distribution for large samples
        //References: http://econometrics.com/guide/dwdist.htm
        double z=(score-2.0)/Math.sqrt(4.0/n);

        double probability=ContinuousDistributions.gaussCdf(z);

        boolean rejectH0=false;

        double a=aLevel;
        if(is_twoTailed) { //if to tailed test then split the statistical significance in half
            a=aLevel/2.0;
        }
        if(probability<=a || probability>=(1-a)) {
            rejectH0=true;
        }

        return rejectH0;
    }

def R(self):
        ''
        self._check_estimated()
        if not self._estimation_finished:
            self._finish_estimation()
        return self._R

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


Question:
@param string $point
@param \Imagine\Image\ImageInterface $pasteImage
@param \Imagine\Image\ImageInterface $image

@return integer

protected function stringXtoInteger($point, ImageInterface $pasteImage, ImageInterface $image)
    {
        switch ($point) {
            case 'right':
                return (integer) $image->getSize()->getWidth() - $pasteImage->getSize()->getWidth();
            case 'center':
                return (integer) round( ($image->getSize()->getWidth() / 2) - ($pasteImage->getSize()->getWidth() / 2) );
            case 'left':
            default:
                return 0;
        }
    }

public function interceptAfterUpload($str) {
	$this->logDebug('interceptAfterUpload', 'Entering function');
	$this->logPHPDebug('interceptAfterUpload', $this->files);

	if (count($this->files) > 0) {
		if (isset($this->classparams['callbackAfterUploadManagement'])) {
			$this->logDebug('interceptAfterUpload', 'Before call of ' .$this->classparams['callbackAfterUploadManagement']);
			$strForFListContent = call_user_func($this->classparams['callbackAfterUploadManagement'], $this, $this->files);
		} else {
			$strForFListContent = $this->defaultAfterUploadManagement();
		}
		$str = preg_replace('/'.$this->classparams['tag_flist'].'/', $strForFListContent, $str);
	}
	return $this->generateAppletTag($str);
}

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


Question: Returns the 10th-90th percentile range of array :py:obj:`x`.

def _range10_90(x):
    '''

    '''

    x = np.delete(x, np.where(np.isnan(x)))
    i = np.argsort(x)
    a = int(0.1 * len(x))
    b = int(0.9 * len(x))
    return x[i][b] - x[i][a]

def _parse_lightgbm_simple_model(scope, model, inputs):
    '''

    '''
    this_operator = scope.declare_local_operator(_get_lightgbm_operator_name(type(model)), model)
    this_operator.inputs = inputs

    if type(model) in lightgbm_classifier_list:
        # For classifiers, we may have two outputs, one for label and the other one for probabilities of all classes.
        # Notice that their types here are not necessarily correct and they will be fixed in shape inference phase
        label_variable = scope.declare_local_variable('label', FloatTensorType())
        probability_map_variable = scope.declare_local_variable('probabilities', FloatTensorType())
        this_operator.outputs.append(label_variable)
        this_operator.outputs.append(probability_map_variable)
    else:
        # We assume that all scikit-learn operator can only produce a single float tensor.
        variable = scope.declare_local_variable('variable', FloatTensorType())
        this_operator.outputs.append(variable)
    return this_operator.outputs

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


Question:
Focus to cell.
@param {squireext} sq - squire instance
@param {range} range - range object
@param {HTMLElement} targetCell - cell element for focus
@ignore

function focusToCell(sq, range, targetCell) {
  range.selectNodeContents(targetCell);
  range.collapse(true);
  sq.setSelection(range);
}

public function recursiveRender()
    {
        $field_input = $this->template->cloneRegion('InputField');
        $field_no_label = $this->template->cloneRegion('InputNoLabel');
        $labeled_group = $this->template->cloneRegion('LabeledGroup');
        $no_label_group = $this->template->cloneRegion('NoLabelGroup');

        $this->template->del('Content');

        foreach ($this->elements as $el) {

            // Buttons go under Button section
            if ($el instanceof \atk4\ui\Button) {
                $this->template->appendHTML('Buttons', $el->getHTML());
                continue;
            }

            if ($el instanceof \atk4\ui\FormLayout\Generic) {
                if ($el->label && !$el->inline) {
                    $template = $labeled_group;
                    $template->set('label', $el->label);
                } else {
                    $template = $no_label_group;
                }

                if ($el->width) {
                    $template->set('width', $el->width);
                }

                if ($el->inline) {
                    $template->set('class', 'inline');
                }
                $template->setHTML('Content', $el->getHTML());

                $this->template->appendHTML('Content', $template->render());
                continue;
            }

            // Anything but fields or explicitly defined fields gets inserted directly
            if (!$el instanceof \atk4\ui\FormField\Generic || !$el->layoutWrap) {
                $this->template->appendHTML('Content', $el->getHTML());
                continue;
            }

            $template = $field_input;
            $label = $el->caption ?: $el->field->getCaption();

            // Anything but fields gets inserted directly
            if ($el instanceof \atk4\ui\FormField\CheckBox) {
                $template = $field_no_label;
                $el->template->set('Content', $label);
                /*
                $el->addClass('field');
                $this->template->appendHTML('Fields', '
'.$el->getHTML().'
');
                continue;
                 */
            }

            if ($this->label && $this->inline) {
                $el->placeholder = $label;
                $label = $this->label;
                $this->label = null;
            } elseif ($this->label || $this->inline) {
                $template = $field_no_label;
                $el->placeholder = $label;
            }

            // Fields get extra pampering
            $template->setHTML('Input', $el->getHTML());
            $template->trySet('label', $label);
            $template->trySet('label_for', $el->id.'_input');
            $template->set('field_class', $el->getFieldClass());

            if ($el->field->required) {
                $template->append('field_class', 'required ');
            }

            if (isset($el->width)) {
                $template->append('field_class', $el->width.' wide ');
            }

            if ($el->hint && $template->hasTag('Hint')) {
                $hint = new \atk4\ui\Label([null, 'pointing', 'id'=>$el->id.'_hint']);
                if (is_object($el->hint) || is_array($el->hint)) {
                    $hint->add($el->hint);
                } else {
                    $hint->set($el->hint);
                }
                $template->setHTML('Hint', $hint->getHTML());
            } elseif ($template->hasTag('Hint')) {
                $template->del('Hint');
            }

            $this->template->appendHTML('Content', $template->render());
        }

        // Now collect JS from everywhere
        foreach ($this->elements as $el) {
            if ($el->_js_actions) {
                $this->_js_actions = array_merge_recursive($this->_js_actions, $el->_js_actions);
            }
        }
    }

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


Question: // SetAZList sets the AZList field's value.

func (s *ListAvailableZonesOutput) SetAZList(v []*string) *ListAvailableZonesOutput {
	s.AZList = 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:
find the asset and create symlink
@param  string $url  Asset URL to find
@return string|bool

public function findAsset($url)
    {
        if (empty($url)) {
            return false;
        }

        $this->asset = $this->processUrl($url);

        if ($this->asset === false) {
            return false;
        }

        // check main assets dir
        $mainAsset = $this->findMainAsset(
            $this->docRoot . DS . $this->assetDir . DS . $this->asset['asset']
        );
        if ($mainAsset !== false) {
            return $mainAsset;
        }

        // check the set theme
        $themeAsset = $this->findThemeAsset(
            $this->asset['folder'],
            $this->assetDir . DS . $this->asset['asset']
        );
        if ($themeAsset !== false) {
            return $themeAsset;
        }

        // get the last "fallback" directory
        return $this->findFallbackAsset(
            $this->assetDir . DS . $this->asset['asset'],
            $this->Folder
        );
    }

public function handle()
    {
        $ds = DIRECTORY_SEPARATOR;
        $resources = $this->argument('resources');
        $resources = !is_array($resources) ? [$resources] : $resources;
        $module = $this->option('module');
        $routesFile = base_path('routes') . $ds . 'web.php';

        if ($module) {
            $module = is_array($module) ? $module[0] : $module;
            $moduleDirectory = config('support.module.directory') . $ds . ucfirst($module);

            $this->namespace = $this->getAppNamespace() . ucfirst($module);
            $routesFile = config('support.module.directory') . $ds . ucfirst($module) . $ds . config('support.module.routes');

            if (!file_exists($moduleDirectory)) {
                $this->error("The requested module '$moduleDirectory' does not exists!");
                return;
            }

            if(config('support.namespace')) {
                $this->namespace = config('support.namespace');
            }
        }

        foreach ($resources as $resource) {
            $stub = file_get_contents(__DIR__ . $ds . '..' . $ds . '..' . $ds . '..' . $ds . '..' . $ds . 'resources' . $ds . 'Stubs' . $ds . (empty($module) ? 'Standard' : 'Modular') . $ds . 'Route.stub');
            $stub = str_replace([
                        '{{resource}}',                    '{{class}}'],
                        [str_plural(strtolower($resource)),  str_plural(ucfirst($resource))],
                        $stub);

            if (!file_exists($routesFile)) {
                $this->error('Could not update routes file \'' . $routesFile . '\' as it does not exist!');
                return;
            }

            $routes = file_get_contents($routesFile);
            $stub = $routes ? $routes . "\n" . $stub : $stub;

            file_put_contents($routesFile, $stub);
            $this->info($routesFile . ' routes updated!');
        }
    }

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


Question:
Returns a "201 Created" response with a location header.

@param Response $response
@param string   $route
@param array    $params

@return Response

protected function created(Response $response, $route, array $params = [])
    {
        return $this->redirect($response, $route, $params)->withStatus(201);
    }

public function prepareError($message, $errors=[], $code=404) {
        $this->prepareResult(false, $message, $code, null , $errors);
    }

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


Question: // SetSelectionStatus sets the SelectionStatus field's value.

func (s *Block) SetSelectionStatus(v string) *Block {
	s.SelectionStatus = &v
	return s
}

def status(self):
        """"""
        # Deal with status column mechanics based in this cell's data
        if hasattr(self, '_status'):
            # pylint: disable=access-member-before-definition
            return self._status

        if self.column.status or \
                self.column.name in self.column.table._meta.status_columns:
            # returns the first matching status found
            data_status_lower = six.text_type(
                self.column.get_raw_data(self.datum)).lower()
            for status_name, status_value in self.column.status_choices:
                if six.text_type(status_name).lower() == data_status_lower:
                    self._status = status_value
                    return self._status
        self._status = None
        return self._status

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


Question: // NewGlobalPositionInt returns a new GlobalPositionInt

func NewGlobalPositionInt(TIME_BOOT_MS uint32, LAT int32, LON int32, ALT int32, RELATIVE_ALT int32, VX int16, VY int16, VZ int16, HDG uint16) *GlobalPositionInt {
	m := GlobalPositionInt{}
	m.TIME_BOOT_MS = TIME_BOOT_MS
	m.LAT = LAT
	m.LON = LON
	m.ALT = ALT
	m.RELATIVE_ALT = RELATIVE_ALT
	m.VX = VX
	m.VY = VY
	m.VZ = VZ
	m.HDG = HDG
	return &m
}

public function seek($position)
    {
        reset($this->_storage);
        while (($key = key($this->_storage)) !== null && $key !== $position)
        {
            next($this->_storage);
        }
    }

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


Question:
r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective
        function.

def obfn_g1(self, Y1):

        """

        return np.linalg.norm((self.Pcn(Y1) - Y1))

def _determine_minimizer(self):

        if self.constraints:
            return SLSQP
        elif any([bound is not None for pair in self.model.bounds for bound in pair]):
            # If any bound is set
            return LBFGSB
        else:
            return BFGS

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


Question: // PermCreate adds a user to an app or makes them an administrator.

func PermCreate(appID string, username string, admin bool) error {

	c, appID, err := permsLoad(appID, admin)

	if err != nil {
		return err
	}

	if admin {
		fmt.Printf("Adding %s to system administrators... ", username)
		err = perms.NewAdmin(c, username)
	} else {
		fmt.Printf("Adding %s to %s collaborators... ", username, appID)
		err = perms.New(c, appID, username)
	}

	if err != nil {
		return err
	}

	fmt.Println("done")

	return nil
}

public Map<String, Permission> ymlToPermissions(String yml, String msName) {
        Map<String, Permission> result = new TreeMap<>();
        try {
            Map<String, Map<String, Set<Permission>>> map = mapper
                .readValue(yml, new TypeReference<TreeMap<String, TreeMap<String, TreeSet<Permission>>>>() {
                });
            map.entrySet().stream()
                .filter(entry -> StringUtils.isBlank(msName) || StringUtils.startsWithIgnoreCase(entry.getKey(), msName))
                .filter(entry -> entry.getValue() != null)
                .forEach(entry -> entry.getValue()
                    .forEach((roleKey, permissions) ->
                                 permissions.forEach(permission -> {
                                     permission.setMsName(entry.getKey());
                                     permission.setRoleKey(roleKey);
                                     result.put(roleKey + ":" + permission.getPrivilegeKey(), permission);
                                 })
                    ));
        } catch (Exception e) {
            log.error("Failed to create permissions collection from YML file, error: {}", e.getMessage(), e);
        }
        return Collections.unmodifiableMap(result);
    }

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


Question: Track an object which needs destruction when it is garbage collected.

def track(cls, obj, ptr):

        cls._objects.add(cls(obj, ptr))

def delete(self, context, plan):

		op = execution.Delete(self.__comp_name, self.__comp())
		if op not in plan and self.available(context) != False:
			for dep_stub in self.__dependents(self.__comp_stub_reg.get(None)):
				dep_stub.delete(context, plan)
			plan.append(op)

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


Question: Gets the information about the operators input/output types.

@Override
	@SuppressWarnings("unchecked")
	public BinaryOperatorInformation<IN1, IN2, OUT> getOperatorInfo() {
		return (BinaryOperatorInformation<IN1, IN2, OUT>) this.operatorInfo;
	}

private void scanOperator() {
        while (true) {
            reader.putChar(false);
            Name newname = reader.name();
            TokenKind tk1 = tokens.lookupKind(newname);
            if (tk1 == TokenKind.IDENTIFIER) {
                reader.sp--;
                break;
            }
            tk = tk1;
            reader.scanChar();
            if (!isSpecial(reader.ch)) break;
        }
    }

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


Question: /* utility functions

@Override
  public <T> ByteBuffer serialize(final Serializer<T> serializer, final T value)
    throws IOException {
    try (final BytesSerialWriter writer = writeBytes()) {
      serializer.serialize(writer, value);
      return writer.toByteBuffer();
    }
  }

def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"):

        return self.__do_menu("as_ul", show_leaf, current_linkable, class_current)

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


Question: Merges mask1 and mask2 into this FieldMask.

def Union(self, mask1, mask2):
    """"""
    _CheckFieldMaskMessage(mask1)
    _CheckFieldMaskMessage(mask2)
    tree = _FieldMaskTree(mask1)
    tree.MergeFromFieldMask(mask2)
    tree.ToFieldMask(self)

public function createUiField(PropertyPath $propertyPath, HtmlView $view, UiOutfitter $uiOutfitter): UiComponent {
		return $view->getImport('\rocket\impl\ei\component\prop\relation\view\toManyForm.html',
				array('selectOverviewToolsUrl' => $this->selectOverviewToolsUrl,
						'newMappingFormUrl' => $this->newMappingFormUrl, 'propertyPath' => $propertyPath));
	}

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


Question:
@param string $string

@return ButtonInterface

public function setAddString(string $string): ButtonInterface
    {
        if ($this->isVisibility()) {
            $this->strings[] = $string;
        }

        return $this;
    }

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question: // SetApplications sets the Applications field's value.

func (s *ListApplicationsOutput) SetApplications(v []*string) *ListApplicationsOutput {
	s.Applications = v
	return s
}

def enable(self):

        core_napps_manager = CoreNAppsManager(base_path=self._enabled)
        core_napps_manager.enable(self.user, self.napp)

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


Question:
Read JdbcConnectionDescriptors from this InputStream.

@see #mergeConnectionRepository

public ConnectionRepository readConnectionRepository(InputStream inst)
    {
        try
        {
            RepositoryPersistor persistor = new RepositoryPersistor();
            return persistor.readConnectionRepository(inst);
        }
        catch (Exception e)
        {
            throw new MetadataException("Can not read repository from " + inst, e);
        }
    }

public List<String> getDevicePipeList(Database database, String deviceName, String wildcard) throws DevFailed {
        DeviceData argIn = new DeviceData();
        argIn.insert(new String[]{deviceName, wildcard});
        DeviceData argOut = database.command_inout("DbGetDevicePipeList", argIn);
        //System.out.println("database.command_inout(\"DbGetDevicePipeList\", argIn)");

        String[] array = argOut.extractStringArray();
        ArrayList<String> list = new ArrayList<String>();
        Collections.addAll(list, array);
        return list;
    }

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


Question:
// SetRemovalInProgress sets the container state as being removed.
// It returns true if the container was already in that state.

func (s *State) SetRemovalInProgress() bool {
	s.Lock()
	defer s.Unlock()
	if s.RemovalInProgress {
		return true
	}
	s.RemovalInProgress = true
	return false
}

public function onPostStateChange(OrderEvent $event)
    {
        $order = $event->getOrder();
        $cart  = $this->provider->getCart();
        if ($order->getId() === $cart->getId() && $order->getType() !== OrderTypes::TYPE_CART) {
            $this->provider->clearCart();
        }
    }

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


public static <K, V> Map<K, V> sortByValue(Map<K, V> map, BeanComparator beanComparator)
	{
		return map.entrySet()
		.stream()
		.sorted(Map.Entry.comparingByValue(beanComparator))
		.collect(Collectors.toMap(
		Map.Entry::getKey,
		Map.Entry::getValue,
		(e1, e2) -> e1,
		LinkedHashMap::new));
	}

def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)

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


Question:
Logs out of all sessions for specified uid
@param int $uid
@return boolean

public function logoutAll($uid)
    {
        $this->isAuthenticated = false;
        $this->currentuser = null;

        return $this->deleteExistingSessions($uid);
    }

def logout(database)
      command = Protocol::Command.new(database, logout: 1)
      self.write([command])
      reply = self.receive_replies([command]).first
      if command.failure?(reply)
        return
      end
      credentials.delete(database)
    end

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *CreateImageBuilderInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateImageBuilderInput"}
	if s.AppstreamAgentVersion != nil && len(*s.AppstreamAgentVersion) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("AppstreamAgentVersion", 1))
	}
	if s.ImageName != nil && len(*s.ImageName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ImageName", 1))
	}
	if s.InstanceType == nil {
		invalidParams.Add(request.NewErrParamRequired("InstanceType"))
	}
	if s.InstanceType != nil && len(*s.InstanceType) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("InstanceType", 1))
	}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.Tags != nil && len(s.Tags) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Tags", 1))
	}

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

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
获取存储跟路径
@return bool|string

public static function getStorePath()
    {
        $storePath = Yii::getAlias(Yii::$app->settings->get('storePath', 'attachment'));
        if (!is_dir($storePath)) {
            FileHelper::createDirectory($storePath, 0775, true);
        }
        return $storePath;
    }

function yy_r114(){
    if (preg_match('~^true$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'true';
    } elseif (preg_match('~^false$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'false';
    } elseif (preg_match('~^null$~i', $this->yystack[$this->yyidx + 0]->minor)) {
        $this->_retvalue = 'null';
    } else {
        $this->_retvalue = "'".$this->yystack[$this->yyidx + 0]->minor."'";
    }
    }

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


Question:
Walks by list's nodes and extracts optional value of type T.
@param list subject
@param clazz value type
@param path nodes to walk in list
@param <T> value type
@return optional value of type T

public static <T> Optional<T> get(final List list, final Class<T> clazz, final Integer... path) {
        if (path == null || path.length == 0) {
            throw new IllegalArgumentException(PATH_MUST_BE_SPECIFIED);
        }
        if (path.length == 1) {
            return Optional.ofNullable((T) list.get(path[0]));
        }
        final Integer[] pathToLastNode = Arrays.copyOfRange(path, 0, path.length - 1);
        final Integer lastKey = path[path.length - 1];
        List intermediateList = list;
        for (Integer index : pathToLastNode) {
            final Object node = intermediateList.get(index);
            if (node != null) {
                final Optional<List> nodeListOption = ClassApi.cast(node, List.class);
                if (nodeListOption.isPresent()) {
                    intermediateList = nodeListOption.get();
                } else {
                    throw new IllegalAccessError("Node with key '" + index + "' is not a list!");
                }
            } else {
                return Optional.empty();
            }
        }
        return Optional.ofNullable((T) intermediateList.get(lastKey));
    }

public function path($name, array $parameters = [], $relative = false)
    {
        if ($name instanceof TreeNodeInterface) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ContentTreeContext) {
            return $this->router->generate($name->getNode(), $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        } elseif ($name instanceof ElementStructureValue) {
            if ($name->getType() === 'link') {
                $link = $name->getValue();
                if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                    $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                    if ($tree) {
                        $node = $tree->get($link['tid']);

                        return $this->router->generate(
                            $node,
                            $parameters,
                            $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                        );
                    }
                } elseif ($link['type'] === 'external') {
                    return $link['url'];
                } elseif ($link['type'] === 'mailto') {
                    return 'mailto:'.$link['recipient'];
                }
            }
        } elseif (is_array($name) && isset($name['type']) && in_array($name['type'], array('internal', 'intrasiteroot', 'external', 'mailto'))) {
            $link = $name;
            if ($link['type'] === 'internal' || $link['type'] === 'intrasiteroot') {
                $tree = $this->contentTreeManager->findByTreeId($link['tid']);
                if ($tree) {
                    $node = $tree->get($link['tid']);

                    return $this->router->generate(
                        $node,
                        $parameters,
                        $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH
                    );
                }
            } elseif ($link['type'] === 'external') {
                return $link['url'];
            } elseif ($link['type'] === 'mailto') {
                return 'mailto:'.$link['recipient'];
            }
        } elseif (strlen($name) && (is_int($name) || (int) $name)) {
            $tree = $this->contentTreeManager->findByTreeId((int) $name);
            if ($tree) {
                $node = $tree->get((int) $name);

                return $this->router->generate($node, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
            }
        } elseif (is_string($name)) {
            return $this->router->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
        }

        return '';
    }

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


Question: // Create runs the create action.

func (c *OrganizationController) Create(ctx *app.CreateOrganizationContext) error {
	currentUser, err := manager.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError(err.Error()))
	}

	if currentUser == nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError("error finding the current user"))
	}

	if ctx.Payload.Name == nil || len(strings.TrimSpace(*ctx.Payload.Name)) == 0 {
		log.Error(ctx, map[string]interface{}{}, "organization name cannot be empty")
		return jsonapi.JSONErrorResponse(ctx, goa.ErrBadRequest("organization name cannot be empty"))
	}

	organizationID, err := c.app.OrganizationService().CreateOrganization(ctx, *currentUser, *ctx.Payload.Name)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":      err,
			"org_name": *ctx.Payload.Name,
		}, "failed to create organization")

		return jsonapi.JSONErrorResponse(ctx, err)
	}

	log.Debug(ctx, map[string]interface{}{
		"organization_id": organizationID.String(),
	}, "organization created")

	orgID := organizationID.String()

	return ctx.Created(&app.CreateOrganizationResponse{
		OrganizationID: &orgID,
	})
}

@Override
    public boolean applyAction(Model m) {
        Mapping map = m.getMapping();
        return map.isRunning(vm) &&
                map.getVMLocation(vm).equals(src) &&
                map.addSleepingVM(vm, dst);
    }

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


Question: // SetYears sets the Years field's value.

func (s *DefaultRetention) SetYears(v int64) *DefaultRetention {
	s.Years = &v
	return s
}

public function crudFormatValueDate($val, $args = [])
    {
        if (is_int($val)) {
            return date($args['format'] ?? 'd.m.Y', $val);
        } elseif ($val instanceof \Carbon\Carbon) {
            return $val->format($args['format'] ?? 'd.m.Y');
        }
    }

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


Question:
// readCSV reads the CSV file and returns the corresponding Prog.
// It may print details about problems to standard error using the log package.

func readCSV(file string) (*Prog, error) {
	// Read input.
	// Skip leading blank and # comment lines.
	f, err := os.Open(file)
	if err != nil {
		return nil, err
	}
	b := bufio.NewReader(f)
	for {
		c, err := b.ReadByte()
		if err != nil {
			break
		}
		if c == '\n' {
			continue
		}
		if c == '#' {
			b.ReadBytes('\n')
			continue
		}
		b.UnreadByte()
		break
	}
	table, err := csv.NewReader(b).ReadAll()
	if err != nil {
		return nil, fmt.Errorf("parsing %s: %v", file, err)
	}
	if len(table) == 0 {
		return nil, fmt.Errorf("empty csv input")
	}
	if len(table[0]) < 6 {
		return nil, fmt.Errorf("csv too narrow: need at least six columns")
	}

	p := &Prog{}
	for _, row := range table {
		add(p, row[0], row[1], row[2], row[3], row[4], row[5])
	}

	check(p)

	return p, nil
}

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
@param Search $data
@param int|null $limit
@param int|null $offset
@param string|null $sort_column
@param string|null $sort_direction

@return array {list:[],total:0}

public function search(
        Search $data,
        $limit = 0,
        $offset = 0,
        $sort_column = self::DEFAULT_SORT_COLUMN,
        $sort_direction = self::DEFAULT_SORT_DIRECTION
    ) {
        return $this->driver->search(
            $data,
            ($limit > 0 ? (int) $limit : 0),
            ($offset > 0 ? (int) $offset : 0),
            $this->getValidSortColumn($sort_column),
            $this->getValidSortDirection($sort_direction)
        );
    }

private void init() {

		factories.put(NotEmptyQuery.class,     new NotEmptyQueryFactory(this));
		factories.put(FulltextQuery.class,     new KeywordQueryFactory(this));
		factories.put(SpatialQuery.class,      new SpatialQueryFactory(this));
		factories.put(GroupQuery.class,        new GroupQueryFactory(this));
		factories.put(RangeQuery.class,        new RangeQueryFactory(this));
		factories.put(ExactQuery.class,        new KeywordQueryFactory(this));
		factories.put(ArrayQuery.class,        new ArrayQueryFactory(this));
		factories.put(EmptyQuery.class,        new EmptyQueryFactory(this));
		factories.put(TypeQuery.class,         new TypeQueryFactory(this));
		factories.put(UuidQuery.class,         new UuidQueryFactory(this));
		factories.put(RelationshipQuery.class, new RelationshipQueryFactory(this));
		factories.put(ComparisonQuery.class,   new ComparisonQueryFactory(this));

		converters.put(Boolean.class, new BooleanTypeConverter());
		converters.put(String.class,  new StringTypeConverter());
		converters.put(Date.class,    new DateTypeConverter());
		converters.put(Long.class,    new LongTypeConverter());
		converters.put(Short.class,   new ShortTypeConverter());
		converters.put(Integer.class, new IntTypeConverter());
		converters.put(Float.class,   new FloatTypeConverter());
		converters.put(Double.class,  new DoubleTypeConverter());
		converters.put(byte.class,    new ByteTypeConverter());
	}

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


Question: ********* Private methods *********

protected void startInstance(final HttpServletRequest request, final String requestBody) {
        try {
            addPropertiesStart(request, requestBody);
            writePropertiesToLog(this.logger, Level.DEBUG);
        } catch (Exception e) {
            logger.error("Failed logging HTTP transaction start: " + e.getMessage(), e);
        }
    }

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

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


Question:
Get a request parameter stripped of white space. Return default for null
or zero length.

@param name    name of parameter
@param def default value
@return  String   value

public String getReqPar(final String name, final String def) {
    final String s = Util.checkNull(request.getParameter(name));

    if (s != null) {
      return s;
    }

    return def;
  }

public function render() {
    $value = (string) $this;
    if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) {
      return Html::escape($this->name) . '="' . $value . '"';
    }
  }

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


Question:
Get a Npcap parameter matching key in the registry.

    List:
    AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support
    LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport
    WinPcapCompatible

def _get_npcap_config(param_key):

    hkey = winreg.HKEY_LOCAL_MACHINE
    node = r"SYSTEM\CurrentControlSet\Services\npcap\Parameters"
    try:
        key = winreg.OpenKey(hkey, node)
        dot11_adapters, _ = winreg.QueryValueEx(key, param_key)
        winreg.CloseKey(key)
    except WindowsError:
        return None
    return dot11_adapters

func (p *Params) Bind(dest interface{}, name string) {
	value := reflect.ValueOf(dest)
	if value.Kind() != reflect.Ptr {
		paramsLogger.Panic("Bind: revel/params: non-pointer passed to Bind: " + name)
	}
	value = value.Elem()
	if !value.CanSet() {
		paramsLogger.Panic("Bind: revel/params: non-settable variable passed to Bind: " + name)
	}

	// Remove the json from the Params, this will stop the binder from attempting
	// to use the json data to populate the destination interface. We do not want
	// to do this on a named bind directly against the param, it is ok to happen when
	// the action is invoked.
	jsonData := p.JSON
	p.JSON = nil
	value.Set(Bind(p, name, value.Type()))
	p.JSON = jsonData
}

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


Question:
Read fields extracted from Bash's debugging output
 @return [Hash<Pathname, Array<Integer, nil>>] A hash mapping Bash scripts
   to Simplecov-style coverage stats

def read
      @field_stream.read = @read

      field_count = FIELDS.length
      fields = @field_stream.each(
        self.class.delimiter, field_count, PS4_START_REGEXP
      )

      # +take(field_count)+ would be more natural here, but doesn't seem to
      # play nicely with +Enumerator+s backed by +IO+ objects.
      loop do
        break if (hit = (1..field_count).map { fields.next }).empty?

        parse_hit!(*hit)
      end

      @read.close unless @read.closed?

      @files
    end

func (c *ControllerGauges) Collect(ch chan<- prometheus.Metric) {
	c.ModelConfigReads.Collect(ch)
	c.ModelHashCacheHit.Collect(ch)
	c.ModelHashCacheMiss.Collect(ch)

	c.ApplicationConfigReads.Collect(ch)
	c.ApplicationHashCacheHit.Collect(ch)
	c.ApplicationHashCacheMiss.Collect(ch)

	c.LXDProfileChangeError.Collect(ch)
	c.LXDProfileChangeHit.Collect(ch)
	c.LXDProfileChangeMiss.Collect(ch)
}

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


Question: // SetVaultName sets the VaultName field's value.

func (s *UploadArchiveInput) SetVaultName(v string) *UploadArchiveInput {
	s.VaultName = &v
	return s
}

def name(self):
        """"""
        if self._name == '' and self.details != None and 'name' in self.details:
            self._name = self.details['name']
        return self._name

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


Question:
Removes all the commerce order items where commerceOrderId = ? and subscription = ? from the database.

@param commerceOrderId the commerce order ID
@param subscription the subscription

@Override
	public void removeByC_S(long commerceOrderId, boolean subscription) {
		for (CommerceOrderItem commerceOrderItem : findByC_S(commerceOrderId,
				subscription, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(commerceOrderItem);
		}
	}

public function resolveField(FieldValue $fieldValue): FieldValue
    {
        return $fieldValue->setResolver(
            function ($root, array $args) {
                $argumentDefinition = $this->getSingleArgumentDefinition();

                if ($argumentDefinition->type->kind !== NodeKind::NON_NULL_TYPE) {
                    throw new DirectiveException(
                        "The @delete directive requires the field {$this->definitionNode->name->value} to have a NonNull argument. Mark it with !"
                    );
                }

                $idOrIds = reset($args);
                if ($this->directiveArgValue('globalId', false)) {
                    // At this point we know the type is at least wrapped in a NonNull type, so we go one deeper
                    if ($argumentDefinition->type->type->kind === NodeKind::LIST_TYPE) {
                        $idOrIds = array_map(
                            function ($id) {
                                return $this->globalId->decodeID($id);
                            },
                            $idOrIds
                        );
                    } else {
                        $idOrIds = $this->globalId->decodeID($idOrIds);
                    }
                }

                $modelClass = $this->getModelClass();
                $model = $modelClass::find($idOrIds);

                if (! $model) {
                    return;
                }

                if ($model instanceof Model) {
                    $model->delete();
                }

                if ($model instanceof Collection) {
                    $modelClass::destroy($idOrIds);
                }

                return $model;
            }
        );
    }

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


Question: Manages fatal errors (out of memory etc.) sending email to all address in options.

public static function fatalErrorHandler() {

		// get fatal error array
		$error = error_get_last();

		if (!is_null($error)) {

			// command line log has date and plain text
			if ('cli' == php_sapi_name()) {

				print date(DATE_RFC2822) . "\nFatal error (" . $error['type'] . ') on file ' .
					$error['file'] . ' line ' . $error['line'] . ': ' . $error['message'] . "\n";

			// format for an HTML web print
			} else {

				print '
' .
						PRODUCT_NAME . ' fatal error: ' . $error['message'] . '
';

			}

			// get admin emails by options
			$emails = array_filter(explode(',', Options::get('admin_emails')));

			if (count($emails)) {

				// get proper server description
				if (isset($_SERVER['SERVER_NAME'])) {
					$server = $_SERVER['SERVER_NAME'];
				} else if (isset($_SERVER['SERVER_ADDR'])) {
					$server = $_SERVER['SERVER_ADDR'];
				} else {
					$server = '[Unknown]';
				}

				// build email parameters
				$subject = PRODUCT_NAME . ' fatal error on ' . $server;
				$message = PRODUCT_NAME . ' generated a fatal error on server ' .  BASE_HREF . ' as of ' .
					date(DATE_RFC2822) . " UTC." . PHP_EOL . PHP_EOL .
					'Error [type ' . $error['type'] . ']: ' . PHP_EOL .
					$error['message'] . ' (' . $error['file'] . ' line ' . $error['line'] . ')';
				$headers = 'From: ' . PRODUCT_NAME . ' <' . strtolower(PRODUCT_NAME) . '@' . $server . '>';

				// send email to each admin
				foreach ($emails as $email) {
					mail($email, $subject, $message, $headers);
				}

			}

		}

	}

@Override
    protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
        try {
            final File baseDir = getSettings().getTempDirectory();
            tempFileLocation = File.createTempFile("check", "tmp", baseDir);
            if (!tempFileLocation.delete()) {
                setEnabled(false);
                final String msg = String.format(
                        "Unable to delete temporary file '%s'.",
                        tempFileLocation.getAbsolutePath());
                throw new InitializationException(msg);
            }
            if (!tempFileLocation.mkdirs()) {
                setEnabled(false);
                final String msg = String.format(
                        "Unable to create directory '%s'.",
                        tempFileLocation.getAbsolutePath());
                throw new InitializationException(msg);
            }
        } catch (IOException ex) {
            setEnabled(false);
            throw new InitializationException("Unable to create a temporary file", ex);
        }
    }

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


Question: ~ Methods ------------------------------------------------------------------------------------

@Override
    public void addClientBehaviorRenderer(String type, ClientBehaviorRenderer renderer)
    {
        if (type == null)
        {
            throw new NullPointerException("client behavior renderer type must not be null");
        }
        if ( renderer == null)
        {
            throw new NullPointerException("client behavior renderer must not be null");
        }

        _clientBehaviorRenderers.put(type, renderer);
    }

public Set<HttpMethod> allAllowedMethods() {
		if (anyMethodRouter.size() > 0) {
			Set<HttpMethod> ret = new HashSet<HttpMethod>(9);
			ret.add(HttpMethod.CONNECT);
			ret.add(HttpMethod.DELETE);
			ret.add(HttpMethod.GET);
			ret.add(HttpMethod.HEAD);
			ret.add(HttpMethod.OPTIONS);
			ret.add(HttpMethod.PATCH);
			ret.add(HttpMethod.POST);
			ret.add(HttpMethod.PUT);
			ret.add(HttpMethod.TRACE);
			return ret;
		} else {
			return new HashSet<HttpMethod>(routers.keySet());
		}
	}

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


Question:
Moves the file to the supplied file path.

@param string $path
@param int    $fileNameLength

@return static

public function moveToPathWithRandomFileName(string $path, int $fileNameLength = 16)
    {
        return $this->process(FileMoverProcessor::withRandomFileName($this->movedClassName(), $path, $fileNameLength));
    }

public function assertStringEqualsFile($expectedFile, $canonicalize = false, $ignoreCase = false) {
        $this->callAssertMethod(__FUNCTION__, [
            'expected' => $expectedFile,
            'additionalParams' => [
                $canonicalize,
                $ignoreCase,
            ],
        ]);
    }

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


Question:
imagecolorallocateで色IDを取得する。
@return int

public function imagecolorallocate($imageResource)
	{

		return imagecolorallocate(
			$imageResource,
			$this->_r,
			$this->_g,
			$this->_b
		);

	}

public void setOutRGB(IntRange outRGB) {
        this.outRed = outRGB;
        this.outGreen = outRGB;
        this.outBlue = outRGB;

        CalculateMap(inRed, outRGB, mapRed);
        CalculateMap(inGreen, outRGB, mapGreen);
        CalculateMap(inBlue, outRGB, mapBlue);
    }

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


Question: Count the number of 1s in the 'location'th subregion

public int countOnes(int location) {

    int count = 0;
    for (int i = 0; i < populationSize; i++) {
      if (subregionIdx[location][i] == 1) {
        count++;
      }
    }

    return count;
  }

public static function isUniqueExist( $name, $countryId, $provinceId ) {

		$region = self::findUnique( $name, $countryId, $provinceId );

		return isset( $region );
	}

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


Question:
Creates a task that to retry a previously abandoned task.

    Returns:
      Task: a task that was abandoned but should be retried or None if there are
          no abandoned tasks that should be retried.

def CreateRetryTask(self):

    with self._lock:
      abandoned_task = self._GetTaskPendingRetry()
      if not abandoned_task:
        return None

      # The abandoned task is kept in _tasks_abandoned so it can be still
      # identified in CheckTaskToMerge and UpdateTaskAsPendingMerge.

      retry_task = abandoned_task.CreateRetryTask()
      logger.debug('Retrying task {0:s} as {1:s}.'.format(
          abandoned_task.identifier, retry_task.identifier))

      self._tasks_queued[retry_task.identifier] = retry_task
      self._total_number_of_tasks += 1

      self.SampleTaskStatus(retry_task, 'created_retry')

      return retry_task

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question: Send: scheduleWork rejected

void sendDeltaScheduleWorkRejected()
   {
      scheduleWorkRejected.incrementAndGet();

      if (trace)
         log.tracef("sendDeltaScheduleWorkRejected: %s", workManagers);

      if (own != null && transport != null && transport.isInitialized())
      {
         for (Address address : workManagers)
         {
            if (!own.equals(address))
               transport.deltaScheduleWorkRejected(address);
         }
      }
   }

protected String pauseMsg() throws IOException {
        final WorkerStatus status = new WorkerStatus();
        status.setRunAt(new Date());
        status.setPaused(isPaused());
        return ObjectMapperFactory.get().writeValueAsString(status);
    }

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


Question:
Create a {@link State} from stateFn, a function that maps an initial state into a result and a final
state.

@param stateFn the state function
@param <S>     the state type
@param      the result type
@return the new {@link State} instance

public static <S, A> State<S, A> state(Fn1<? super S, ? extends Product2<A, S>> stateFn) {
        return new State<>(stateFn.fmap(into(HList::tuple)));
    }

func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	var agent agent.Agent
	if err := context.Get(config.AgentName, &agent); err != nil {
		return nil, errors.Trace(err)
	}

	var clock clock.Clock
	if err := context.Get(config.ClockName, &clock); err != nil {
		return nil, errors.Trace(err)
	}

	// Ensure that the controller-port worker is running.
	if err := context.Get(config.ControllerPortName, nil); err != nil {
		return nil, errors.Trace(err)
	}

	var stTracker workerstate.StateTracker
	if err := context.Get(config.StateName, &stTracker); err != nil {
		return nil, errors.Trace(err)
	}
	statePool, err := stTracker.Use()
	if err != nil {
		return nil, errors.Trace(err)
	}

	st := statePool.SystemState()
	mongoSession := st.MongoSession()
	agentConfig := agent.CurrentConfig()
	stateServingInfo, ok := agentConfig.StateServingInfo()
	if !ok {
		return nil, errors.New("state serving info missing from agent config")
	}
	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	supportsHA := model.Type() != state.ModelTypeCAAS

	w, err := config.NewWorker(Config{
		State:              StateShim{st},
		MongoSession:       MongoSessionShim{mongoSession},
		APIHostPortsSetter: &CachingAPIHostPortsSetter{APIHostPortsSetter: st},
		Clock:              clock,
		Hub:                config.Hub,
		MongoPort:          stateServingInfo.StatePort,
		APIPort:            stateServingInfo.APIPort,
		ControllerAPIPort:  stateServingInfo.ControllerAPIPort,
		SupportsHA:         supportsHA,
	})
	if err != nil {
		stTracker.Done()
		return nil, errors.Trace(err)
	}
	return common.NewCleanupWorker(w, func() { stTracker.Done() }), nil
}

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


Question:
Sets the gravity if something should be cropped. (See {@see \Beluga\Drawing\Gravity}}::* constants)

@param  int $gravity
@return ImageSizeReducer
@throws \Beluga\ArgumentError

public function setGravity( int $gravity ) : ImageSizeReducer
   {

      if ( ! \in_array( $gravity, Gravity::KNOWN_VALUES ) )
      {
         throw new ArgumentError( 'gravity', $gravity, 'Drawing.Image', 'Can not crop an image with an unknown gravity!' );
      }

      $this->data[ 'gravity' ] = $gravity;

      return $this;

   }

public function subtract($arg1) : \Object\Value\Math {
		\Math::subtract2($this->result, $arg1, $this->scale);
		return $this;
	}

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


Question:
处理回调的result
@param result 回调的result
@param rstCode 业务结果码

private void disposeObtainedResult(SignInResult result, int rstCode) {
        if(result.isSuccess()){
            //可以获取帐号的 openid，昵称，头像 at信息
            SignInHuaweiId account = result.getSignInHuaweiId();
            onSignInResult(rstCode, account);
        } else {
            if(rstCode == HuaweiIdStatusCodes.SIGN_IN_UNLOGIN
                    || rstCode == HuaweiIdStatusCodes.SIGN_IN_AUTH
                    || rstCode == HuaweiIdStatusCodes.SIGN_IN_CHECK_PASSWORD){
                Activity curActivity = ActivityMgr.INST.getLastActivity();
                if (curActivity == null) {
                    HMSAgentLog.e("activity is null");
                    onSignInResult(HMSAgent.AgentResultCode.NO_ACTIVITY_FOR_USE, null);
                    return;
                }

                try {
                    signInResultForDispose = result;
                    Intent nxtIntent = new Intent(curActivity, HMSSignInAgentActivity.class);
                    curActivity.startActivity(nxtIntent);
                } catch (Exception e) {
                    HMSAgentLog.e("start HMSSignInAgentActivity error:" + e.getMessage());
                    onSignInResult(HMSAgent.AgentResultCode.START_ACTIVITY_ERROR, null);
                }
            } else {
                onSignInResult(rstCode, null);
            }
        }
    }

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


Question:
// AllOrigins compute all CORS policies for the resource taking into account any API policy.
// The result is sorted alphabetically by policy origin.

func (r *ResourceDefinition) AllOrigins() []*CORSDefinition {
	all := make(map[string]*CORSDefinition)
	for n, o := range Design.Origins {
		all[n] = o
	}
	for n, o := range r.Origins {
		all[n] = o
	}
	names := make([]string, len(all))
	i := 0
	for n := range all {
		names[i] = n
		i++
	}
	sort.Strings(names)
	cors := make([]*CORSDefinition, len(names))
	for i, n := range names {
		cors[i] = all[n]
	}
	return cors
}

def origin_mexico(origin):

    return origin in (u'CIUDADJUAREZ', u'GUADALAJARA', u'HERMOSILLO',
                      u'MATAMOROS', u'MERIDA', u'MEXICO', u'MONTERREY',
                      u'NOGALES',
                      u'NUEVOLAREDO', u'TIJUANA')

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


Question:
Get the additional values to inject while exporting.

@param renderer_base $output The renderer.
@return array Keys are the property names, values are their values.

protected function get_other_values(renderer_base $output) {
        global $CFG;

        $values = new stdClass();

        if (!empty($CFG->enablecalendarexport)) {
            if ($exportbutton = $this->get_export_calendar_button()) {
                $values->exportcalendarbutton = $exportbutton->export_for_template($output);
            }
            if ($managesubscriptionbutton = $this->get_manage_subscriptions_button()) {
                $values->managesubscriptionbutton = $managesubscriptionbutton->export_for_template($output);
            }
        }

        return (array) $values;
    }

public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        $xml = $this->parseFile($path);
        $xml->registerXPathNamespace('config', 'http://thelia.net/schema/dic/config');

        $this->removeScope($xml);

        $this->container->addResource(new FileResource($path));

        $this->parseLoops($xml);

        $this->parseFilters($xml);

        $this->parseTemplateDirectives($xml);

        $this->parseParameters($xml);

        $this->parseCommands($xml);

        $this->parseForms($xml);

        $this->parseDefinitions($xml, $path);

        $this->parseHooks($xml, $path, $type);

        $this->propelOnlyRun(
            [$this, "parseExportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseExports"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImports"],
            $xml
        );
    }

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


Question:
@param string|NodeList|\DOMNode $input

@return \DOMNode|null

protected function inputAsFirstNode($input): ?\DOMNode {
        $nodes = $this->inputAsNodeList($input);

        return $nodes->findXPath('self::*')->first();
    }

private function handleINFO()
    {
        header('Content-Type: text/html');

        $css = '
body {
    margin: 0px;
    padding: 10px;
    font-family: sans-serif;
}
#header {
    background-color: #339900;
    color: #FFFFFF;
    padding: 5px 10px;
    margin: -10px;
}
h1 {
    font-size: xx-large;
    color: #CCFF99;
}
#header p {
    font-size: large;
}

dt {
    margin-top: 1em;
}

.description {
    padding-left: 1.5em;
    margin-bottom: 1.5em;
}

a:link {
    color: #006600;
}

a:visited {
    color: #030;
}

a:hover {
    color: #003300;
}
';

        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>' . $this->wsdlclassname . ' WebService</title>
<meta name="generator" content="PEAR::Services_Webservice" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">

'.
        '
' . $this->wsdlclassname . '

' .
        htmlspecialchars($this->description)
        . '

The following operations are supported. ' .
        'For a formal definition, please review the getSelfUrl()) . '?WSDL">Service Description.

';

        foreach ($this->wsdlStruct[$this->wsdlclassname]['method'] as $methodName => $method) {
            $paramValue = array();
            foreach ($method['var'] as $methodVars) {
                if (isset($methodVars['param'])) {
                    $paramValue[] = $methodVars['type']
                                     . str_repeat('[]', $methodVars['length']);
                }
            }
            $returnValue = array();
            foreach ($method['var'] as $methodVars) {
                if (isset($methodVars['return'])) {
                    $returnValue[] = $methodVars['type']
                                     . str_repeat('[]', $methodVars['length']);
                }
            }
            echo sprintf(
                '
<samp><var class="returnedValue">%s</var> '
                . '%s'
                . '( <var class="parameter">%s</var> )</samp>%s
',
                implode(',', $returnValue),
                $methodName,
                implode(
                    '</var> , <var class="parameter">',
                    $paramValue
                ), ((empty($method['description'])) ?
                    '' : ('
'
                    . htmlspecialchars($method['description']) . ''))
            );
        }
        echo '

getSelfUrl()) . '?DISCO">DISCO makes it possible for clients to reflect against endpoints to discover services and their associated <acronym title="Web Service Description Language">WSDL</acronym> documents.
';

        if ($this->warningNamespace == true
            || $this->namespace == 'http://example.org/'
        ) {
            echo '

This web service is using http://example.org/ as its default namespace.

Recommendation: Change the default namespace before the <acronym title="eXtensible Markup Language">XML</acronym> Web service is made public.

Each XML Web service needs a unique namespace in order for client applications to distinguish it from other services on the Web. http://example.org/ is available for XML Web services that are under development, but published XML Web services should use a more permanent namespace.

Your XML Web service should be identified by a namespace that you control. For example, you can use your company`s Internet domain name as part of the namespace. Although many XML Web service namespaces look like <acronym title="Uniform Resource Locators">URLs</acronym>, they need not point to actual resources on the Web. (XML Web service namespaces are <acronym title="Uniform Resouce Identifiers">URIs</acronym>.)

For more details on XML namespaces, see the <acronym title="World Wide Web Consortium">W3C</acronym> recommendation on Namespaces in XML.

For more details on <acronym title="Web Service Description Language">WSDL</acronym>, see the WSDL Specification.

For more details on URIs, see <acronym title="Request For Comment">RFC</acronym> 2396.

Powered by PEAR http://pear.php.net

';

        }
        echo '';
    }

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


Question: Return an array of the operations associated with the bean name.

public MBeanOperationInfo[] getOperationsInfo(ObjectName name) throws JMException {
		checkClientConnected();
		try {
			return mbeanConn.getMBeanInfo(name).getOperations();
		} catch (Exception e) {
			throw createJmException("Problems getting bean information from " + name, e);
		}
	}

public static <T> Level0ArrayOperator<Calendar[],Calendar> on(final Calendar[] target) {
        return onArrayOf(Types.CALENDAR, target);
    }

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