Question:
@param EloquentFile $file
@param $path

@return bool

protected function applyChangesInFs(EloquentFile $file, $path)
    {

        if ($file->exists) {
            if ($file->getPath() != $file->getOriginalPath()) {
                $this->filesystem->move($file->getOriginalPath(), $file->getPath());
                return true;
            }
            return false;
        }

        // else
        if ($file->isDir()) {
            return $this->filesystem->makeDirectory($path);
        }

        if (!$this->filesystem->exists($path)) {
            // Basically just touch the file if it does not exist
            $this->filesystem->write($path, '');
        }

        return true;
    }

public function processFile(string $type)
    {
        $this->alert(strtoupper($type) . ' PROCESS');
        foreach ($this->tables as $key => $table) {
            if ($table->relationTable === true && $type !== 'pivot') {
                continue;
            }

            if ($table->relationTable !== true && $type === 'pivot') {
                continue;
            }

            if (trim($this->option('table')) !== 'all') {
                $tableKey = $this->option('table');
                if ((int) $tableKey !== (int) $key) {
                    continue;
                }
            }

            $table->arqs = [
                $type => $this->getTemplate($type),
            ];

            foreach ($this->marks()[$type] as $mark){
                $table->arqs[$type] = str_replace('{{{' . $mark . '}}}',
                                                        trim($table->marks[$mark]),
                                                        $table->arqs[$type]);
            }

            //$this->info($table->arqs[$type]);
            $this->createFile($type, $table);
        }
    }

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


Question:
checkSession
@param array $p_params
@return boolean

public function checkSession($p_params){
        try {
            $params = new SimpleObject\OdaPrepareReqSql();
            $params->sql = "SELECT true as 'check'
                FROM `api_tab_session` a
                WHERE 1=1
                AND a.`key` = :key
                AND a.`datas` like '%\"code_user\":\"".$p_params["code_user"]."\"%'
                AND (a.`dateCreation` + INTERVAL a.`periodeValideMinute` MINUTE) > NOW()
            ;";
            $params->bindsValue = [
                "key" => $p_params["key"]
            ];
            $params->typeSQL = OdaLibBd::SQL_GET_ONE;
            $retour = $this->BD_AUTH->reqODASQL($params);

            return $retour->nombre;
        } catch ( Exception $ex ) {
            $this->dieInError($ex.'');
        }
    }

public function flash(string $message, string $style = 'info'): self
    {
        $this->session->flash('alert.message', $message);
        $this->session->flash('alert.style', $style);

        return $this;
    }

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


Question:
Converts a camelcase variable name to a human readable text.

@param camel the String to be converted
@return the hopefully human readable version

public static String labelFromCamelCase(String camel) {
		StringBuilder label = new StringBuilder();
		for (int i = 0; i < camel.length(); i++) {
			char c = camel.charAt(i);
			if (Character.isDigit(c)) {
				if (i > 0 && Character.isAlphabetic(camel.charAt(i - 1)))
					label.append(" ");
			}
			if (c == '_') {
				label.append(" ");
			} else if (Character.isUpperCase(c)) {
				label.append(' ');
				label.append(Character.toLowerCase(c));
			} else {
				label.append(c);
			}
		}
		return label.toString();
	}

def translated_attributes
      attributes = {}
      translations = []
      translations << { :var => 'client_id', :xml_var => 'ClientID' }
      translations << { :var => 'concat', :xml_var => 'Concat' }
      translations << { :var => 'from', :xml_var => 'From' }
      translations << { :var => 'invalid_char_action', :xml_var => 'InvalidCharAction' }
      translations << { :var => 'content', :xml_var => 'Content' }
      translations << { :var => 'to', :xml_var => 'To' }
      translations << { :var => 'truncate', :xml_var => 'Truncate' }
      translations << { :var => 'wrapper_id', :xml_var => 'WrapperID' }

      translations.each do |t|
        self.instance_variable_set( "@#{t[:var]}", @api.instance_variable_get( "@#{t[:var]}" ) ) if self.instance_variable_get( "@#{t[:var]}" ).nil?
        attributes[ t[:xml_var] ] = self.instance_variable_get( "@#{t[:var]}" ) unless self.instance_variable_get( "@#{t[:var]}" ).nil?
      end

      attributes
    end

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


Question: InternalPureXbase.g:5782:1: ruleQualifiedName returns [AntlrDatatypeRuleToken current=new AntlrDatatypeRuleToken()] : (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* ) ;

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

        Token kw=null;
        AntlrDatatypeRuleToken this_ValidID_0 = null;

        AntlrDatatypeRuleToken this_ValidID_2 = null;

        	enterRule();

        try {
            // InternalPureXbase.g:5788:2: ( (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* ) )
            // InternalPureXbase.g:5789:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
            {
            // InternalPureXbase.g:5789:2: (this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )* )
            // InternalPureXbase.g:5790:3: this_ValidID_0= ruleValidID ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
            {
            if ( state.backtracking==0 ) {

              			newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_0());

            }
            pushFollow(FOLLOW_68);
            this_ValidID_0=ruleValidID();

            state._fsp--;
            if (state.failed) return current;
            if ( state.backtracking==0 ) {

              			current.merge(this_ValidID_0);

            }
            if ( state.backtracking==0 ) {

              			afterParserOrEnumRuleCall();

            }
            // InternalPureXbase.g:5800:3: ( ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID )*
            loop100:
            do {
                int alt100=2;
                int LA100_0 = input.LA(1);

                if ( (LA100_0==54) ) {
                    int LA100_2 = input.LA(2);

                    if ( (LA100_2==RULE_ID) ) {
                        int LA100_3 = input.LA(3);

                        if ( (synpred48_InternalPureXbase()) ) {
                            alt100=1;
                        }

                    }

                }

                switch (alt100) {
            	case 1 :
            	    // InternalPureXbase.g:5801:4: ( ( '.' )=>kw= '.' ) this_ValidID_2= ruleValidID
            	    {
            	    // InternalPureXbase.g:5801:4: ( ( '.' )=>kw= '.' )
            	    // InternalPureXbase.g:5802:5: ( '.' )=>kw= '.'
            	    {
            	    kw=(Token)match(input,54,FOLLOW_12); if (state.failed) return current;
            	    if ( state.backtracking==0 ) {

            	      					current.merge(kw);
            	      					newLeafNode(kw, grammarAccess.getQualifiedNameAccess().getFullStopKeyword_1_0());

            	    }

            	    }

            	    if ( state.backtracking==0 ) {

            	      				newCompositeNode(grammarAccess.getQualifiedNameAccess().getValidIDParserRuleCall_1_1());

            	    }
            	    pushFollow(FOLLOW_68);
            	    this_ValidID_2=ruleValidID();

            	    state._fsp--;
            	    if (state.failed) return current;
            	    if ( state.backtracking==0 ) {

            	      				current.merge(this_ValidID_2);

            	    }
            	    if ( state.backtracking==0 ) {

            	      				afterParserOrEnumRuleCall();

            	    }

            	    }
            	    break;

            	default :
            	    break loop100;
                }
            } while (true);

            }

            }

            if ( state.backtracking==0 ) {

              	leaveRule();

            }
        }

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

func (s *UpdateRuleInput) SetChangeToken(v string) *UpdateRuleInput {
	s.ChangeToken = &v
	return s
}

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


Question:
(non-PHPdoc)
@see PDOStatement::bindValue()

public function bindValue($parameter, $value, $dataType = null) {
		$this->boundValues[$parameter] = $value;
		if ($dataType !== null) {
			return parent::bindValue($parameter, $value, $dataType);
		} else {
			return parent::bindValue($parameter, $value);
		}
	}

public function buildUpdateSQL($table = null, $data = array())
	{
		$sql = 'update ' . $this->parseTable($table) . ' set ';
		if(is_string($data))
		{
			$sql .= $data . ' ';
		}
		else
		{
			$data = $this->parseParams($data);
			foreach($data as $key => $value)
			{
				$sql .= $this->parseKeyword($key) . '=:' . $this->parseParamName($key) . ',';
			}
		}
		$where = $this->parseCondition(isset($this->operationOption['where']) ? $this->operationOption['where'] : '');
		if ('' !== $where)
		{
			$where = 'where ' . $where . ' ';
		}
		return substr($sql,0,-1) . ' '
				. $where
				. $this->parseOrder()
				. $this->parseLimit()
				. $this->parseLock()
				;
	}

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


Question: .google.privacy.dlp.v2.CharacterMaskConfig character_mask_config = 3;

public com.google.privacy.dlp.v2.CharacterMaskConfigOrBuilder getCharacterMaskConfigOrBuilder() {
    if (transformationCase_ == 3) {
      return (com.google.privacy.dlp.v2.CharacterMaskConfig) transformation_;
    }
    return com.google.privacy.dlp.v2.CharacterMaskConfig.getDefaultInstance();
  }

def parse_rmd_options(line):

    parsing_context = ParsingContext(line)

    result = []
    prev_char = ''

    name = ''
    value = ''

    for char in ',' + line + ',':
        if parsing_context.in_global_expression():
            if char == ',':
                if name != '' or value != '':
                    if result and name == '':
                        raise RMarkdownOptionParsingError(
                            'Option line "{}" has no name for '
                            'option value {}'.format(line, value))
                    result.append((name.strip(), value.strip()))
                    name = ''
                    value = ''
            elif char == '=':
                if name == '':
                    name = value
                    value = ''
                else:
                    value += char
            else:
                parsing_context.count_special_chars(char, prev_char)
                value += char
        else:
            parsing_context.count_special_chars(char, prev_char)
            value += char
        prev_char = char

    if not parsing_context.in_global_expression():
        raise RMarkdownOptionParsingError(
            'Option line "{}" is not properly terminated'.format(line))

    return result

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


Question: // SetDemographic sets the Demographic field's value.

func (s *PublicEndpoint) SetDemographic(v *EndpointDemographic) *PublicEndpoint {
	s.Demographic = 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: // hash serializes the RRset and return a signature cache key.

func hash(rrs []dns.RR) uint64 {
	h := fnv.New64()
	buf := make([]byte, 256)
	for _, r := range rrs {
		off, err := dns.PackRR(r, buf, 0, nil, false)
		if err == nil {
			h.Write(buf[:off])
		}
	}

	i := h.Sum64()
	return i
}

func (f *Facade) ReportHealthStatus(key health.HealthStatusKey, value health.HealthStatus, expires time.Duration) {
	f.hcache.Set(key, value, expires)
}

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


Question: Message received from websocket

def _on_auth(self, sock, authenticated):  # pylint: disable=unused-argument
        """"""
        def ack(eventname, error, data):  # pylint: disable=unused-argument
            """Ack"""
            if error:
                self.log.error(f"""OnAuth: {error}""")
            else:
                self.connect_channels(self.channels)
                self.post_conn_cb()

        sock.emitack("auth", self.creds, ack)

void createMethodBody(String classname, ExecutableElement methodElement, List<String> arguments, Writer writer) throws IOException {
		String methodName = getMethodName(methodElement);
		boolean ws = isWebsocketDataService(methodElement);
		String args = stringJoinAndDecorate(arguments, COMMA, new NothingDecorator());
		String keys = computeKeys(methodElement, arguments);
		createReturnOcelotPromiseFactory(classname, methodName, ws, args, keys, writer);
	}

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


Question: create from middle, angle and distance

def fromAttr(mid, ang, dist):

    mx, my = mid
    dx = cos(ang) * dist * 0.5
    dy = sin(ang) * dist * 0.5
    return mx - dx, my - dy, mx + dx, my + dy

public void setArcByCenter (float x, float y, float radius,
                                float start, float extent, int type) {
        setArc(x - radius, y - radius, radius * 2f, radius * 2f, start, extent, type);
    }

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


Question: Directory that contains the the settings for the project

def settings_dir(self):

        path = os.path.join(self.dir, '.dsb')
        utils.create_dir(path)
        return os.path.realpath(path)

function (value)
		{
			if (value != undefined && fs.statSync(value).isDirectory())
			{
				this.modulePath = value;
				this.setConfig('modulePath',value);
			}
			return this;
		}

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


Question:
Returns all the commerce regions where uuid = ? and companyId = ?.

@param uuid the uuid
@param companyId the company ID
@return the matching commerce regions

public static List<CommerceRegion> findByUuid_C(String uuid, long companyId) {
		return getPersistence().findByUuid_C(uuid, companyId);
	}

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


Question:
Introduction to the shell

@return void

public function main()
    {
        $this->out('Welcome to the Proffer shell.');
        $this->out('This shell can be used to regenerate thumbnails and cleanup unlinked images.');
        $this->hr();
        $this->out($this->OptionParser->help());
    }

async def terminate_vm(self, vm_id):
        '''

        '''
        try:
            await self.nova.servers.force_delete(vm_id)
        except JSONDecodeError as exc:
            logging.info("nova sent 'content-type: application/json' but no content appeared, whatever")
            pass
        except Exception:
            raise

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


Question:
Trims away parts of an image

@param  \Intervention\Image\Image $image
@return boolean

public function execute($image)
    {
        $base = $this->argument(0)->type('string')->value();
        $away = $this->argument(1)->value();
        $tolerance = $this->argument(2)->type('numeric')->value(0);
        $feather = $this->argument(3)->type('numeric')->value(0);

        $width = $image->getWidth();
        $height = $image->getHeight();

        // default values
        $checkTransparency = false;

        // define borders to trim away
        if (is_null($away)) {
            $away = ['top', 'right', 'bottom', 'left'];
        } elseif (is_string($away)) {
            $away = [$away];
        }

        // lower border names
        foreach ($away as $key => $value) {
            $away[$key] = strtolower($value);
        }

        // define base color position
        switch (strtolower($base)) {
            case 'transparent':
            case 'trans':
                $checkTransparency = true;
                $base_x = 0;
                $base_y = 0;
                break;

            case 'bottom-right':
            case 'right-bottom':
                $base_x = $width - 1;
                $base_y = $height - 1;
                break;

            default:
            case 'top-left':
            case 'left-top':
                $base_x = 0;
                $base_y = 0;
                break;
        }

        // pick base color
        if ($checkTransparency) {
            $color = new Color; // color will only be used to compare alpha channel
        } else {
            $color = $image->pickColor($base_x, $base_y, 'object');
        }

        $top_x = 0;
        $top_y = 0;
        $bottom_x = $width;
        $bottom_y = $height;

        // search upper part of image for colors to trim away
        if (in_array('top', $away)) {

            for ($y=0; $y < ceil($height/2); $y++) {
                for ($x=0; $x < $width; $x++) {

                    $checkColor = $image->pickColor($x, $y, 'object');

                    if ($checkTransparency) {
                        $checkColor->r = $color->r;
                        $checkColor->g = $color->g;
                        $checkColor->b = $color->b;
                    }

                    if ($color->differs($checkColor, $tolerance)) {
                        $top_y = max(0, $y - $feather);
                        break 2;
                    }

                }
            }

        }

        // search left part of image for colors to trim away
        if (in_array('left', $away)) {

            for ($x=0; $x < ceil($width/2); $x++) {
                for ($y=$top_y; $y < $height; $y++) {

                    $checkColor = $image->pickColor($x, $y, 'object');

                    if ($checkTransparency) {
                        $checkColor->r = $color->r;
                        $checkColor->g = $color->g;
                        $checkColor->b = $color->b;
                    }

                    if ($color->differs($checkColor, $tolerance)) {
                        $top_x = max(0, $x - $feather);
                        break 2;
                    }

                }
            }

        }

        // search lower part of image for colors to trim away
        if (in_array('bottom', $away)) {

            for ($y=($height-1); $y >= floor($height/2)-1; $y--) {
                for ($x=$top_x; $x < $width; $x++) {

                    $checkColor = $image->pickColor($x, $y, 'object');

                    if ($checkTransparency) {
                        $checkColor->r = $color->r;
                        $checkColor->g = $color->g;
                        $checkColor->b = $color->b;
                    }

                    if ($color->differs($checkColor, $tolerance)) {
                        $bottom_y = min($height, $y+1 + $feather);
                        break 2;
                    }

                }
            }

        }

        // search right part of image for colors to trim away
        if (in_array('right', $away)) {

            for ($x=($width-1); $x >= floor($width/2)-1; $x--) {
                for ($y=$top_y; $y < $bottom_y; $y++) {

                    $checkColor = $image->pickColor($x, $y, 'object');

                    if ($checkTransparency) {
                        $checkColor->r = $color->r;
                        $checkColor->g = $color->g;
                        $checkColor->b = $color->b;
                    }

                    if ($color->differs($checkColor, $tolerance)) {
                        $bottom_x = min($width, $x+1 + $feather);
                        break 2;
                    }

                }
            }

        }

        // trim parts of image
        return $this->modify($image, 0, 0, $top_x, $top_y, ($bottom_x-$top_x), ($bottom_y-$top_y), ($bottom_x-$top_x), ($bottom_y-$top_y));

    }

function(l) {
			if (l.type === gui.LIFE_ENTER) {
				if (!this.spirit.life.rendered) { // spirit did a manual run?
					this.run.apply(this, this._arguments || []);
				}
				this.spirit.life.remove(l.type, this);
				this._arguments = null;
			}
		}

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


Question:
Use this API to unset the properties of rnatparam resource.
Properties that need to be unset are specified in args array.

public static base_response unset(nitro_service client, rnatparam resource, String[] args) throws Exception{
		rnatparam unsetresource = new rnatparam();
		return unsetresource.unset_resource(client,args);
	}

def delete_target(target_id)
      # In order to delete the target, we have to set it to non-active.
      # Therefore,first retrieve target info and act accordingly to target info
      # returned
      target_data = JSON.parse(retrieve_target(target_id)) # have to JSON.parse
      # retrieve_target's results since they're in string format
      target_result_code = target_data["result_code"]
      if target_result_code != "AuthenticationFailure"
        if target_result_code != "UnknownTarget"
          target_active_flag = target_data["target_record"]["active_flag"]
          target_status = target_data["status"]
          if target_result_code == "Success"
            if target_active_flag == true && target_status == "success"
              return {:result_code => "TargetActive"}.to_json
            elsif target_active_flag == false && target_status == "success"
              # if we reached this point, the target is fine, inactive and
              # ready to be deleted
              date_timestamp = Time.now.httpdate
              target_id_url = TARGETS_URL + '/' + target_id
              target_id_suburl = '/targets' + '/' + target_id
              signature = self.build_signature(target_id_suburl, nil, 'DELETE', date_timestamp)
              raise ArgumentError.new('Signature returned nil. Aborting...') if signature == nil
              authorization_header = "VWS " + @accesskey + ":" + signature
                begin
                  RestClient.delete(target_id_url,
                                             :'Date' => date_timestamp,
                                             :'Authorization' => authorization_header)
                rescue => e
                  e.response
                end
            else
              return {:result_code => "#{target_status}"}.to_json
            end
          end
        else
          return {:result_code => "UnknownTarget"}.to_json
        end
      else
        return {:result_code => "AuthenticationFailure"}.to_json
      end
    end

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


Question: Return the location as a good

def get_location(self):

        image_string = self.__dict__['location']['image']
        image_ints = list(map(int, image_string.split(",")))
        return Location(*image_ints)

public void fixAddress(String name) throws IOException
    {
        Label label = labels.get(name);
        if (label == null)
        {
            label = new Label(name);
            labels.put(name, label);
        }
        int pos = position();
        label.setAddress(pos);
        labelMap.put(pos, label);
    }

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


Question:
Initialize context
        :param CliContext self: this
        :param settings.TransferAction action: transfer action

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

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

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

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

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

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

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

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

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


Question:
Update metadata.

@param MediaInterface $media
@param bool           $force

public function updateMedadata(MediaInterface $media)
    {
        try {
            $url = sprintf(
                'https://www.googleapis.com/youtube/v3/videos?id=%s&key=%s&part=snippet,contentDetails,statistics,status',
                $media->getReference(),
                $this->apikey
            );
            $metadata = $this->getMetadata($media, $url);
        } catch (\RuntimeException $e) {
            $media->setStatus(Media::STATUS_DISABLED);

            return;
        }

        $metadata = $metadata['items'][0];
        $metadata['contentDetails']['duration'] = $this->convertDuration($metadata['contentDetails']['duration']);

        if (!$media->getName()) {
            $media->setName($metadata['snippet']['title']);
        }

        $thumb = $this->saveThumbnail($media, $metadata['snippet']['thumbnails']['high']['url']);
        $media->setThumb($thumb);

        $media->setMetadata($metadata);
        $media->setContentType('video/x-flv');
    }

public function add_meta($key, $meta_data) {
	if (is_object($meta_data)) {
		$meta_data = parent::convert_object_to_array($meta_data);
	}

	$this->meta_data[$key] = $meta_data;
}

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


Question: ### Returns * Instance of Cellar

function Cellar(name, mongoose, schema, options) {
	// connect to mongodb if they pass credentials
	if(mongoose.constructor.name === 'Object') {
		var mongoUrl = 'mongodb://' + mongoose.user + ':' + mongoose.pass + '@' + mongoose.host + ':' + mongoose.port + '/' + mongoose.name;
		mongoose = _mongoose.connect(mongoUrl);
	}
	// create a schema instance if they pass the literal
	schema = schema instanceof mongoose.Schema ? schema : new mongoose.Schema(schema);

	options = options || {};
	//default maxAge is 1 day, -1 means no expiration
	var maxAge = (typeof options.maxAge === undefined ? 1 : options.maxAge);
	// initialize lastChecked as a long time ago
	var lastChecked = new Date(0);
	// add an `updated_at` field to track when the document was last touched
	schema.add({updated_at: {type: Date, required:true, "default": Date.now}});

	// instantiate the model
	var mongoose_model = mongoose.model(name, schema);

	// prune

	// Private
	// Remove expired documents from the collection

	// ### Arguments
	// None

	// ### Returns
	// None

	function prune() {
		//check if this database is meant to be pruned
		if(~maxAge) {
			var d = new Date();
			d.setDate(d.getDate() - maxAge);

			if(lastChecked < d) { // make sure we're not trying to prune more often than at least maxAge since the last time we did
				mongoose_model.remove()
					.where('updated_at').lt(d)
					.exec(function(error, numAffected) {
						lastChecked = new Date(); //update our lastChecked to reflect our touching the database
						if(error) {
							console.log("Error while removing docs from database", error);
						} else {
							if(options.verbose) {
								console.log("Removed "+numAffected+" old docs from the database.");
							}
						}
					});
			}
		}
	}

	// Cellar#store

	// Public
	// Create or update a document in the collection

	// ### Arguments
	// * `where` - Optional Object describing criteria by which to update the document (see http://www.mongodb.org/display/DOCS/Querying)
	// * `data` - Object of data to update or create the document
	// * `callback` - Function to be evaluated upon completion of the insert/update
	//		- Arguments
	//			1. Error
	//			2. Mongoose document created or updated

	// ### Returns
	// * Instance of Cellar

	this.store = function(where, data, callback) {
		if(arguments.length < 3) {
			callback = data;
			data = where;
			where = null;
		}

		if(where) {
			//update
			data.updated_at = Date.now();
			for(var p in where) {
				if(where.hasOwnProperty(p)) {
					if(typeof data[p] === 'undefined') {
						// add all the `where` properties to the replacement doc (where there are no conflicts) in case this document gets upserted
						data[p] = where[p];
					}
				}
			}
			mongoose_model.findOneAndUpdate(where, data, {upsert:true}, callback);
		} else {
			//insert
			var store = new mongoose_model(data);
			store.save(callback);
		}
		//prune the db
		prune();
		return this;
    };

    // Cellar#retrieve

	// Public
	// Find a document in the collection

	// ### Arguments
	// * `where` - Object of criteria by which to find the document (see http://www.mongodb.org/display/DOCS/Querying)
	// * `fields` - Optional Array of String field names to retrieve on the document
	// * `callback` - Function to be evaluated upon completion of the find operation
	//		- Arguments
	//			1. Error
	//			2. Mongoose document that matched the criteria or null if no document matched

	// ### Returns
	// * Instance of Cellar

    this.retrieve = function(where, fields, callback) {
		if(arguments.length < 3 || fields === undefined || fields === null) {
			fields = [];
		}
		var args = [where];
		if(fields.length) {
			args.push(fields.join(" "));
		}
		args.push(callback);
		mongoose_model.findOne.apply(mongoose_model, args);
		return this;
    };

    // Cellar#retrieve_field

	// Public
	// Find the contents of one field on a document in the collection

	// ### Arguments
	// * `where` - Object of criteria by which to find the document where the field is (see http://www.mongodb.org/display/DOCS/Querying)
	// * `field` - String name of field desired
	// * `callback` - Function to be evaluated after the find is completed
	//		- Arguments
	//			1. Error - will also return an error if looking for a field on a document which does not have the field
	//			2. Contents of `field` in a matching document, or null if no document matched

	// ### Returns
	// * Instance of Cellar

    this.retrieve_field = function(where, field, callback) {
		this.retrieve(where, [field], function(error, doc) {
			if(error || !doc) {
				callback(error);
				return;
			}
			if(!doc[field]) {
				callback(new Error(field+" does not exist in this document"));
				return;
			}
			callback(null, doc[field]);
		});
		return this;
    };

    return this;
}

public static function getInstance($type, $init)
    {

        if (!self::$cachingInstance) {
            self::$cachingInstance = new IDS_Caching_Session($type, $init);
        }

        return self::$cachingInstance;
    }

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


Question:
Calls the event {@link JPEContentHandler#endFeatureCollection(Object)} of
both {@link JPEContentHandler} set through
{@link #setJPEParseContentHandler(JPEContentHandler)} and
{@link #setJPEWriteContentHandler(JPEContentHandler)}

public void end() {
		// if (((ArrayList) this.featureCollection).size() == 0) {
		this.endNewElement();
		// }
		contentHandler.endFeatureCollection(this.featureCollection);
		if (writerContentHandler != null)
			geoJSON = writerContentHandler.endFeatureCollection(geoJSON);
	}

public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException
    {
        float[] parameter = this.parameter;
        this.compress(ratio, 1e-3f);

        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile)));
        save(out);
        out.close();

        if (text)
        {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8"));
            TagSet tagSet = featureMap.tagSet;
            for (Map.Entry<String, Integer> entry : featureIdSet)
            {
                bw.write(entry.getKey());
                if (featureIdSet.size() == parameter.length)
                {
                    bw.write("\t");
                    bw.write(String.valueOf(parameter[entry.getValue()]));
                }
                else
                {
                    for (int i = 0; i < tagSet.size(); ++i)
                    {
                        bw.write("\t");
                        bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i]));
                    }
                }
                bw.newLine();
            }
            bw.close();
        }
    }

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


Question:
Return the boolean value of the attribute having *attr_name*, or
        |False| if not present.

def bool_prop(self, attr_name):

        value = getattr(self, attr_name)
        if value is None:
            return False
        return value

public function getConfirmation()
    {
        $cAttribute = $this->confirmationAttribute;
        return (is_string($cAttribute) && !empty($cAttribute)) ? $this->$cAttribute : null;
    }

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


Question: // Echo returns the same message

func Echo(ctx *cli.Context) command.Command {
	usage := "echo [text]"
	desc := "Returns the [text]"

	return command.NewCommand("echo", usage, desc, func(args ...string) ([]byte, error) {
		if len(args) < 2 {
			return []byte("echo what?"), nil
		}
		return []byte(strings.Join(args[1:], " ")), nil
	})
}

def push(self, code, msg=None):
        """"""
        if msg is None:
            msg = str(code)
        else:
            msg = '%s %s' % (code, msg)

        if not msg.endswith(self.LINE_TERMINATOR):
            msg += self.LINE_TERMINATOR
        self._channel.write(msg)

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


Question:
Copies a file. {'_file_copy': {'dest': 'new_file_name'}}

        Args:
            filename (str): Filename.
            settings (dict): Must be {"dest": path of new file}

def file_copy(filename, settings):

        for k, v in settings.items():
            if k.startswith("dest"):
                shutil.copyfile(filename, v)

func Daemonize() (isDaemon bool, err error) {
	const errLoc = "daemonigo.Daemonize()"
	isDaemon = os.Getenv(EnvVarName) == EnvVarValue
	if WorkDir != "" {
		if err = os.Chdir(WorkDir); err != nil {
			err = fmt.Errorf(
				"%s: changing working directory failed, reason -> %s",
				errLoc, err.Error(),
			)
			return
		}
	}
	if isDaemon {
		syscall.Umask(int(Umask))
		if _, err = syscall.Setsid(); err != nil {
			err = fmt.Errorf(
				"%s: setsid failed, reason -> %s", errLoc, err.Error(),
			)
			return
		}
		if pidFile, err = lockPidFile(); err != nil {
			err = fmt.Errorf(
				"%s: locking PID file failed, reason -> %s",
				errLoc, err.Error(),
			)
		}
	} else {
		flag.Usage = func() {
			arr := make([]string, 0, len(actions))
			for k, _ := range actions {
				arr = append(arr, k)
			}
			fmt.Fprintf(os.Stderr, "Usage: %s {%s}\n",
				os.Args[0], strings.Join(arr, "|"),
			)
			flag.PrintDefaults()
		}
		if !flag.Parsed() {
			flag.Parse()
		}
		action, exist := actions[flag.Arg(0)]
		if exist {
			action()
		} else {
			flag.Usage()
		}
	}
	return
}

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


Question:
indexes a directory of stan files
    returns as dictionary containing contents of files

def _list_files_in_path(path, pattern="*.stan"):

    results = []
    for dirname, subdirs, files in os.walk(path):
        for name in files:
            if fnmatch(name, pattern):
                results.append(os.path.join(dirname, name))
    return(results)

def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')):
    """"""
    # FIXME add device number too
    standard_inos = {}
    for stream in streams:
        try:
            stream_stat = os.fstat(getattr(sys, stream).fileno())
            key = stream_stat.st_dev, stream_stat.st_ino
            standard_inos[key] = stream
        except Exception:  # FIXME UnsupportedOperation
            pass
        # FIXME if not getattr(sys, stream).istty()

    def stream_inos(paths):
        """Yield tuples with stats and path."""
        for path in paths:
            try:
                stat = os.stat(path)
                key = (stat.st_dev, stat.st_ino)
                if key in standard_inos:
                    yield standard_inos[key], path
            except FileNotFoundError:  # pragma: no cover
                pass

    return dict(stream_inos(lookup_paths)) if standard_inos else {}

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


Question:
Iterate through all classes and construct documentation for them.

@param root      the RootDoc of source to document.
@param classtree the data structure representing the class tree.

protected void generateClassFiles(RootDoc root, ClassTree classtree) {
        generateClassFiles(classtree);
        PackageDoc[] packages = root.specifiedPackages();
        for (PackageDoc pkg : packages) {
            generateClassFiles(pkg.allClasses(), classtree);
        }
    }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

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


Question: InternalPureXbase.g:5005:1: ruleIdOrSuper returns [AntlrDatatypeRuleToken current=new AntlrDatatypeRuleToken()] : (this_FeatureCallID_0= ruleFeatureCallID | kw= 'super' ) ;

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

        Token kw=null;
        AntlrDatatypeRuleToken this_FeatureCallID_0 = null;

        	enterRule();

        try {
            // InternalPureXbase.g:5011:2: ( (this_FeatureCallID_0= ruleFeatureCallID | kw= 'super' ) )
            // InternalPureXbase.g:5012:2: (this_FeatureCallID_0= ruleFeatureCallID | kw= 'super' )
            {
            // InternalPureXbase.g:5012:2: (this_FeatureCallID_0= ruleFeatureCallID | kw= 'super' )
            int alt90=2;
            int LA90_0 = input.LA(1);

            if ( (LA90_0==RULE_ID) ) {
                alt90=1;
            }
            else if ( (LA90_0==72) ) {
                alt90=2;
            }
            else {
                if (state.backtracking>0) {state.failed=true; return current;}
                NoViableAltException nvae =
                    new NoViableAltException("", 90, 0, input);

                throw nvae;
            }
            switch (alt90) {
                case 1 :
                    // InternalPureXbase.g:5013:3: this_FeatureCallID_0= ruleFeatureCallID
                    {
                    if ( state.backtracking==0 ) {

                      			newCompositeNode(grammarAccess.getIdOrSuperAccess().getFeatureCallIDParserRuleCall_0());

                    }
                    pushFollow(FOLLOW_2);
                    this_FeatureCallID_0=ruleFeatureCallID();

                    state._fsp--;
                    if (state.failed) return current;
                    if ( state.backtracking==0 ) {

                      			current.merge(this_FeatureCallID_0);

                    }
                    if ( state.backtracking==0 ) {

                      			afterParserOrEnumRuleCall();

                    }

                    }
                    break;
                case 2 :
                    // InternalPureXbase.g:5024:3: kw= 'super'
                    {
                    kw=(Token)match(input,72,FOLLOW_2); if (state.failed) return current;
                    if ( state.backtracking==0 ) {

                      			current.merge(kw);
                      			newLeafNode(kw, grammarAccess.getIdOrSuperAccess().getSuperKeyword_1());

                    }

                    }
                    break;

            }

            }

            if ( state.backtracking==0 ) {

              	leaveRule();

            }
        }

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

@CheckResult
    @NonNull
    public final Data<T> filter(@NonNull Predicate<? super T> predicate) {
        return new FilterData<>(this, predicate);
    }

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


Question:
Creates an ECKey given the private key only.

@param privKey
-

@return -

public static ECKey fromPrivate(BigInteger privKey) {
        return new ECKey(privKey, CURVE.getG().multiply(privKey));
    }

public void ENsettimeparam( TimeParameterCodes code, Long timevalue ) throws EpanetException {
        int errcode = epanet.ENsettimeparam(code.getCode(), timevalue);
        checkError(errcode);
    }

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


Question: //Key creates a Key suitable for getting, putting and deleting LogFilters

func Key(name, version string) datastore.Key {
	name = strings.TrimSpace(name)
	version = strings.TrimSpace(version)
	return datastore.NewKey(kind, buildID(name, version))
}

public void init(Record record, BaseField fldDeleteFlag)
    {
        m_fldDeleteFlag = fldDeleteFlag;
        m_bFilterThisRecord = true;
        super.init(record);
    }

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


Question: Basic boolean test

function( name, test, startFunc, extra ) {
		var self = this;

		// Require an active state for tests
		self.requireState( munit.ASSERT_STATE_ACTIVE, startFunc || self.ok );

		// Prevent non empty string names
		if ( ! munit.isString( name ) || ! name.length ) {
			throw new munit.AssertionError(
				"Name not found for test on '" + self.nsPath + "'",
				startFunc || self.ok
			);
		}
		// Prevent duplicate tests
		else if ( self.tests[ name ] ) {
			throw new munit.AssertionError(
				"Duplicate Test '" + name + "' on '" + self.nsPath + "'",
				startFunc || self.ok
			);
		}

		// Increment test count and mark it
		self[ !!( test ) ? '_pass' : '_fail' ]( name, startFunc || self.ok, extra );

		// Reached expected number of tests, close off
		if ( self.options.expect > 0 && self.count >= self.options.expect ) {
			self.close();
		}

		return self;
	}

def ask(message='Are you sure? [y/N]'):
    """"""
    agree = False
    answer = raw_input(message).lower()
    if answer.startswith('y'):
        agree = True
    return agree

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


Question:
// SetOther is the middleware that checks if the current logged user can see the required profile
// and if the required profile exists. On success sets the "other" = *User variable in the context

func SetOther() echo.MiddlewareFunc {
	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return echo.HandlerFunc(func(c echo.Context) error {
			var other *nerdz.User
			var err error
			if other, err = rest.User("id", c); err != nil {
				return err
			}
			// store the other User into the context
			c.Set("other", other)
			// pass context to the next handler
			return next(c)
		})
	}
}

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question: /* Shorthand alias for jQuery's $.data() utility.

function Data (element) {
        /* Hardcode a reference to the plugin name. */
        var response = $.data(element, NAME);

        /* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */
        return response === null ? undefined : response;
    }

def sql_key(self, generation, sql, params, order, result_type,
                using='default'):

        # these keys will always look pretty opaque
        suffix = self.keygen.gen_key(sql, params, order, result_type)
        using = settings.DB_CACHE_KEYS[using]
        return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)

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


Question: // Put writes a value into the mapping

func (p *PathMap) Put(ctx context.Context, s logical.Storage, k string, v map[string]interface{}) error {
	ps, err := p.pathStruct(ctx, s, k)
	if err != nil {
		return err
	}
	return ps.Put(ctx, s, v)
}

private HashMap<String, DBIDs> multipleAssignment(Relation<?> data) {
    HashMap<String, DBIDs> labelMap = new HashMap<>();

    for(DBIDIter iditer = data.iterDBIDs(); iditer.valid(); iditer.advance()) {
      String[] labels = data.get(iditer).toString().split(" ");
      for(String label : labels) {
        assign(labelMap, label, iditer);
      }
    }
    return labelMap;
  }

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


Question:
Parses the value in Config.TOPOLOGY_COMPONENT_CPUMAP,
and returns a map containing only component specified.
Returns a empty map if the Config is not set

@param topology the topology def
@return a map (componentName -> cpu required)

public static Map<String, Double> getComponentCpuMapConfig(TopologyAPI.Topology topology)
      throws RuntimeException {
    Map<String, String> configMap =
        getComponentConfigMap(topology, Config.TOPOLOGY_COMPONENT_CPUMAP);
    Map<String, Double> cpuMap = new HashMap<>();

    for (Map.Entry<String, String> entry : configMap.entrySet()) {
      Double requiredCpu = Double.parseDouble(entry.getValue());
      cpuMap.put(entry.getKey(), requiredCpu);
    }
    return cpuMap;
  }

func dataSourceComputeFlavorV2Attributes(
	d *schema.ResourceData, computeClient *gophercloud.ServiceClient, flavor *flavors.Flavor) error {

	log.Printf("[DEBUG] Retrieved openstack_compute_flavor_v2 %s: %#v", flavor.ID, flavor)

	d.SetId(flavor.ID)
	d.Set("name", flavor.Name)
	d.Set("flavor_id", flavor.ID)
	d.Set("disk", flavor.Disk)
	d.Set("ram", flavor.RAM)
	d.Set("rx_tx_factor", flavor.RxTxFactor)
	d.Set("swap", flavor.Swap)
	d.Set("vcpus", flavor.VCPUs)
	d.Set("is_public", flavor.IsPublic)

	es, err := flavors.ListExtraSpecs(computeClient, d.Id()).Extract()
	if err != nil {
		return err
	}

	if err := d.Set("extra_specs", es); err != nil {
		log.Printf("[WARN] Unable to set extra_specs for openstack_compute_flavor_v2 %s: %s", d.Id(), err)
	}

	return nil
}

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


Question:
Replace UrlRoutable parameters with their route parameter.

@param  array  $parameters
@return array

protected function replaceRoutableParameters($parameters = array())
	{
		$parameters = is_array($parameters) ? $parameters : array($parameters);

		foreach ($parameters as $key => $parameter)
		{
			if ($parameter instanceof UrlRoutable)
			{
				$parameters[$key] = $parameter->getRouteKey();
			}
		}

		return $parameters;
	}

protected function getAllRouteNames($resourceName = null)
    {
        $resourceName = $resourceName ?? $this->resourceName;

        return [
            'index'   => $this->prefix.$this->resourceName.'.index',
            'create'  => $this->prefix.$this->resourceName.'.create',
            'store'   => $this->prefix.$this->resourceName.'.store',
            'show'    => $this->prefix.$this->resourceName.'.show',
            'edit'    => $this->prefix.$this->resourceName.'.edit',
            'update'  => $this->prefix.$this->resourceName.'.update',
            'destroy' => $this->prefix.$this->resourceName.'.destroy',
        ];
    }

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


Question: The status of the container. For example, ``running``, or ``exited``.

def status(self):

        if isinstance(self.attrs['State'], dict):
            return self.attrs['State']['Status']
        return self.attrs['State']

def end_workunit(self, workunit):
    """"""
    if not self.is_under_main_root(workunit):
      return

    if workunit.outcome() != WorkUnit.SUCCESS and not self._show_output(workunit):
      # Emit the suppressed workunit output, if any, to aid in debugging the problem.
      if self._get_label_format(workunit) != LabelFormat.FULL:
        self._emit_indented_workunit_label(workunit)
      for name, outbuf in workunit.outputs().items():
        self.emit(self._prefix(workunit, '\n==== {} ====\n'.format(name)))
        self.emit(self._prefix(workunit, outbuf.read_from(0).decode('utf-8')))
        self.flush()

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


Question: Return full path to specified command, or raise OSError if missing.

def which(cmd):
    """"""
    try:
        # For Python 3
        from shutil import which as _which
    except ImportError:
        # For Python 2
        from backports.shutil_which import which as _which  # pylint: disable=relative-import
    full_path = _which(cmd)
    if full_path is None:
        raise OSError('Cannot find {!r} in $PATH'.format(cmd))
    log.debug('which %r => %r', cmd, full_path)
    return full_path

function run(cmd){

        var proc = require('child_process'),
            done = grunt.task.current.async(); // Tells Grunt that an async task is complete

        proc.exec(cmd,
            function(error, stdout, stderr){
                if(stderr){
                    grunt.log.writeln('ERROR: ' + stderr).error();
                }
                grunt.log.writeln(stdout);
                done(error);
            }
        );
    }

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


Question:
The runtime main. String arguments are treated and parsed as
command line parameters.

@param args
Command line arguments.

public static void main(String[] args) {
        Generator schemaGen = new Generator();
        System.exit(schemaGen.createSchema(args));
    }

private void printParameterizedType(ParameterizedType parameterizedType)
    throws IOException
  {
    Type rawType = parameterizedType.getRawType();

    if (rawType instanceof Class<?>)
      printClass((Class<?>) rawType);
    else
      printType(rawType);

    print("<");

    Type[] typeParameters = parameterizedType.getActualTypeArguments();

    for (int i = 0; i < typeParameters.length; i++) {
      if (i != 0) {
        print(", ");
      }

      printType(typeParameters[i]);
    }

    print(">");
  }

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


Question:
Key related to pivot table. Must include pivot table alias.

@see pivotKey()

@param string $key

@return null|string

protected function pivotKey(string $key)
    {
        if (!isset($this->schema[$key])) {
            return null;
        }

        return $this->pivotAlias() . '.' . $this->schema[$key];
    }

public static function getQueryWhere($request, $query, $parameters)
    {
        $indexColumns   = isset($parameters['indexColumns'])? $parameters['indexColumns'] : null;
        $where          = isset($parameters['where'])? $parameters['where'] : null;
        $whereColumns   = isset($parameters['whereColumns'])? $parameters['whereColumns'] : null;

        if($where != null)
        {
            $columns = $request->input('columns');

            $query->where(function($query) use ($columns, $indexColumns, $where){
                $i=0;
                foreach($indexColumns as $indexColumn)
                {
                    // check if column if is searchable
                    if($columns[$i]['searchable'] === 'true')
                    {
                        if(is_array($indexColumn)) $indexColumn = $indexColumn['data'];

                        $query->orWhere($indexColumn, 'LIKE', '%' . $where . '%');
                    }
                    $i++;
                }
            });
        }

        if(is_array($whereColumns))
        {
            $query->where(function($query) use ($whereColumns) {
                foreach($whereColumns as $whereColumn)
                {
                    // enable option to be null value, with NULL
                    if($whereColumn['value'] == 'NULL')
                        $whereColumn['value'] = null;

                    $query->where($whereColumn['column'], $whereColumn['operator'], $whereColumn['value']);
                }
            });
        }

        return $query;
    }

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


Question: Define benchmark cases

async function* run_table_cases(worker, data, test) {
    console.log(`Benchmarking \`${test}\``);
    try {
        for (let x = 0; x < ITERATIONS + TOSS_ITERATIONS; x++) {
            const start = performance.now();
            const table = worker.table(data.slice ? data.slice() : data);
            await table.size();
            if (x >= TOSS_ITERATIONS) {
                yield {
                    test,
                    time: performance.now() - start,
                    method: test,
                    row_pivots: "n/a",
                    column_pivots: "n/a",
                    aggregate: "n/a"
                };
            }
            await table.delete();
        }
    } catch (e) {
        console.error(`Benchmark ${test} failed`, e);
    }
}

public List<HistoricCaseInstance> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) {
    return commandContext
      .getHistoricCaseInstanceManager()
      .findHistoricCaseInstancesByNativeQuery(parameterMap, firstResult, maxResults);
  }

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


Question:
Returns Body.
@access		public
@param		string		$type		Body Type (TYPE_PLAIN | TYPE_HTML)
@return		string

protected function getBody( $type )
	{
		$count		= 0;
		$structure	= $this->getMessageStructure();
		foreach( $structure->parts as $part )
		{
			$count++;
			if( $part->type !== 0 )
				continue;
			if( $part->subtype == $type )
			{
				$body	= imap_fetchbody( $this->stream, $this->messageNumber, $count );
				$body	= $this->decodeBody( $body, $part->encoding );
				return $body;
			}
		}
	}

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question:
Builds locator from source using finite state machine.

@return $this
@throws DomainException

protected function buildLocator()
    {
        $this
            ->resetLocatorBuffer()
            ->getReferenceBuffer()
            ->reset();
        $state = self::STATE_POINTER_PART;
        while (true) {
            switch ($state) {
                case self::STATE_POINTER_PART:
                    // Expecting part of a pointer or end of text.
                    $state = $this->processPointerPartState();
                    break;

                case self::STATE_REFERENCE_PART:
                    // Expecting reference token part.
                    $state = $this->processReferencePartState();
                    break;

                case self::STATE_FINISH:
                    // End of text is found, parsing is finished successfully.
                    break 2;

                default:
                    throw new DomainException("Invalid parser state: {$state}");
            }
        }
        $this->locator = $this->getLocatorBuffer();
        return $this
            ->resetLocatorBuffer();
    }

public void addRegion(Region region) {
        if (!regions.contains(region)) {
            if (serviceConnected) {
                try {
                    beaconManager.startMonitoringBeaconsInRegion(region);
                } catch (RemoteException e) {
                    LogManager.e(e, TAG, "Can't add bootstrap region");
                }
            } else {
                LogManager.w(TAG, "Adding a region: service not yet Connected");
            }
            regions.add(region);
        }
    }

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


Question:
MelisCmsSiteRobot/src/MelisCmsSiteRobotFactory/Model/Tables/Factory/MelisCmsSiteRobotTableFactory.php
@param ServiceLocatorInterface $sl
@return MelisCmsSiteRobot

public function createService(ServiceLocatorInterface $sl)
    {
        $hydratingResultSet = new HydratingResultSet(new ObjectProperty(), new MelisCmsSiteRobot());
        $tableGateway       = new TableGateway('melis_cms_domain_robots', $sl->get('Zend\Db\Adapter\Adapter'), null, $hydratingResultSet);

        return new MelisCmsSiteRobotTable($tableGateway);
    }

private function find($ip = null)
    {
        // If IP not set, user remote IP
        $ip = $ip ?: $this->remote_ip;

        // Check cache for location
        if ($this->config('cache', 'none') !== 'none' && $location = $this->getCache()->get($ip)) {
            $location->cached = true;

            return $location;
        }

        // Check if the ip is not local or empty
        if ($this->isValid($ip)) {
            try {
                // Find location
                $location = $this->getService()->locate($ip);

                // Set currency if not already set by the service
                if (!$location->currency) {
                    $location->currency = $this->getCurrency($location->iso_code);
                }

                // Set default
                $location->default = false;

                return $location;
            }
            catch (\Exception $e) {
                if ($this->config('log_failures', true) === true) {
                    $log = new Logger('geoip');
                    $log->pushHandler(new StreamHandler(storage_path('logs/geoip.log'), Logger::ERROR));
                    $log->addError($e);
                }
            }
        }

        return $this->getService()->hydrate($this->default_location);
    }

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


Question: Add segments by ascending address.

def add(self, segment, overwrite=False):

        if self._list:
            if segment.minimum_address == self._current_segment.maximum_address:
                # Fast insertion for adjacent segments.
                self._current_segment.add_data(segment.minimum_address,
                                              segment.maximum_address,
                                              segment.data,
                                              overwrite)
            else:
                # Linear insert.
                for i, s in enumerate(self._list):
                    if segment.minimum_address <= s.maximum_address:
                        break

                if segment.minimum_address > s.maximum_address:
                    # Non-overlapping, non-adjacent after.
                    self._list.append(segment)
                elif segment.maximum_address < s.minimum_address:
                    # Non-overlapping, non-adjacent before.
                    self._list.insert(i, segment)
                else:
                    # Adjacent or overlapping.
                    s.add_data(segment.minimum_address,
                               segment.maximum_address,
                               segment.data,
                               overwrite)
                    segment = s

                self._current_segment = segment
                self._current_segment_index = i

            # Remove overwritten and merge adjacent segments.
            while self._current_segment is not self._list[-1]:
                s = self._list[self._current_segment_index + 1]

                if self._current_segment.maximum_address >= s.maximum_address:
                    # The whole segment is overwritten.
                    del self._list[self._current_segment_index + 1]
                elif self._current_segment.maximum_address >= s.minimum_address:
                    # Adjacent or beginning of the segment overwritten.
                    self._current_segment.add_data(
                        self._current_segment.maximum_address,
                        s.maximum_address,
                        s.data[self._current_segment.maximum_address - s.minimum_address:],
                        overwrite=False)
                    del self._list[self._current_segment_index+1]
                    break
                else:
                    # Segments are not overlapping, nor adjacent.
                    break
        else:
            self._list.append(segment)
            self._current_segment = segment
            self._current_segment_index = 0

def set_segs_names(self):
        """"""
        segs_names = np.zeros(self._adata.shape[0], dtype=np.int8)
        self.segs_names_unique = []
        for iseg, seg in enumerate(self.segs):
            segs_names[seg] = iseg
            self.segs_names_unique.append(iseg)
        self.segs_names = segs_names

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


Question:
// agentServiceWatch is used to watch for changes to a single service instance
// on the local agent. Note that this state is agent-local so the watch
// mechanism uses `hash` rather than `index` for deciding whether to block.

func agentServiceWatch(params map[string]interface{}) (WatcherFunc, error) {
	// We don't support consistency modes since it's agent local data

	var serviceID string
	if err := assignValue(params, "service_id", &serviceID); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		agent := p.client.Agent()
		opts := makeQueryOptionsWithContext(p, false)
		defer p.cancelFunc()

		svc, _, err := agent.Service(serviceID, &opts)
		if err != nil {
			return nil, nil, err
		}

		// Return string ContentHash since we don't have Raft indexes to block on.
		return WaitHashVal(svc.ContentHash), svc, err
	}
	return fn, nil
}

def get_actor(self, actor, aid, check_monitor=True):
        ''''''
        a = super().get_actor(actor, aid)
        if a is None:
            if aid in self.monitors:  # Check in monitors aid
                return self.monitors[aid]
            elif aid in self.managed_actors:
                return self.managed_actors[aid]
            elif aid in self.registered:
                return self.registered[aid]
            else:  # Finally check in workers in monitors
                for m in self.monitors.values():
                    a = m.get_actor(aid, check_monitor=False)
                    if a is not None:
                        return a
        else:
            return a

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


Question:
@deprecated

Since there is no valid Filter Query to filter this facets results this  method will be removed

@param  int   $facetValueLimit
@return $this

public function addFacetProgramId($facetValueLimit = self::DEFAULT_FACET_VALUE_LIMIT)
    {
        $this->getAffilinetClient()->getLog()->addDebug('Method addFacetProgramId is deprecated');
        $this->addFacet('ProgramId', $facetValueLimit);

        return $this;
    }

public function paginate($per_page = 5, $page = null, $page_name = 'imap_page'){
        $this->page = $page > $this->page ? $page : $this->page;
        $this->limit = $per_page;

        return $this->get()->paginate($per_page, $this->page, $page_name);
    }

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


Question: ParamTypeExpressionAnnotation := '{' ParamTypeExpression '}'

private Node parseParamTypeExpressionAnnotation(JsDocToken token) {
    checkArgument(token == JsDocToken.LEFT_CURLY);

    skipEOLs();

    Node typeNode = parseParamTypeExpression(next());
    if (typeNode != null) {
      if (!match(JsDocToken.RIGHT_CURLY)) {
        reportTypeSyntaxWarning("msg.jsdoc.missing.rc");
      } else {
        next();
      }
    }

    return typeNode;
  }

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

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

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

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

}

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


Question: ******************** Methods *******************************************

@Override protected void handleEvents(final String EVENT_TYPE) {
        super.handleEvents(EVENT_TYPE);

        if ("VISIBILITY".equals(EVENT_TYPE)) {
            Helper.enableNode(titleText, !tile.getTitle().isEmpty());
            Helper.enableNode(text, tile.isTextVisible());
            chartCanvas.setWidth(tile.isTextVisible() ? size * 0.68 : size * 0.795);
            chartCanvas.setHeight(tile.isTextVisible() ? size * 0.68 : size * 0.795);
        }
    }

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: Get the current interface layout file.

def uidump(self, local: _PATH = None) -> None:
        ''''''
        local = local if local else self._temp
        self._execute('-s', self.device_sn, 'shell', 'uiautomator',
                      'dump', '--compressed', '/data/local/tmp/uidump.xml')
        self.pull('/data/local/tmp/uidump.xml', local)
        ui = html.fromstring(open(local, 'rb').read())
        self._nodes = ui.iter(tag="node")

public function run(InputInterface $input, OutputInterface $output)
    {
        $this->setInput($input);
        $this->setOutput($output);

        return parent::run($input, $output);
    }

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


Question: A faster convert that works directly with a specific raster

public static void bufferedToInterleaved(DataBufferInt buffer, WritableRaster src, InterleavedU8 dst) {
		int[] srcData = buffer.getData();

		int srcStride = stride(src);
		int srcOffset = getOffset(src);

		int numBands = src.getNumBands();
		if( numBands == 3 ) {
			//CONCURRENT_BELOW BoofConcurrency.loopFor(0, dst.height, y -> {
			for (int y = 0; y < dst.height; y++) {
				int indexSrc = srcOffset + y*srcStride;
				int indexDst = dst.startIndex + y * dst.stride;
				for (int x = 0; x < dst.width; x++) {

					int rgb = srcData[indexSrc++];

					dst.data[indexDst++] = (byte) (rgb >>> 16);
					dst.data[indexDst++] = (byte) (rgb >>> 8);
					dst.data[indexDst++] = (byte) rgb;
				}
			}
			//CONCURRENT_ABOVE });
		} else if( numBands == 4 ) {

			//CONCURRENT_BELOW BoofConcurrency.loopFor(0, dst.height, y -> {
			for (int y = 0; y < dst.height; y++) {
				int indexSrc = srcOffset + y*srcStride;
				int indexDst = dst.startIndex + y * dst.stride;
				for (int x = 0; x < dst.width; x++) {

					int rgb = srcData[indexSrc++];

					dst.data[indexDst++] = (byte) (rgb >>> 24);
					dst.data[indexDst++] = (byte) (rgb >>> 16);
					dst.data[indexDst++] = (byte) (rgb >>> 8);
					dst.data[indexDst++] = (byte) rgb;
				}
			}
			//CONCURRENT_ABOVE });
		}
	}

def from_stream(cls, stream):

        parser = _TiffParser.parse(stream)

        px_width = parser.px_width
        px_height = parser.px_height
        horz_dpi = parser.horz_dpi
        vert_dpi = parser.vert_dpi

        return cls(px_width, px_height, horz_dpi, vert_dpi)

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


Question: // Unauthorized writes a response with status code 401.

func Unauthorized(w http.ResponseWriter, response interface{}) {
	Respond(w, http.StatusUnauthorized, response)
}

def unauthenticate(self):

        self.username = ""
        self.password = ""
        self.tenant_id = ""
        self.tenant_name = ""
        self.token = ""
        self.expires = None
        self.region = ""
        self._creds_file = None
        self.api_key = ""
        self.services = utils.DotDict()
        self.regions = utils.DotDict()
        self.authenticated = False

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


Question:
Append a footer/header to styles.xml/automatic-styles
@param util an util
@param appendable the destination
@param pageSectionType the type if pageSectionStyle is null.
@throws IOException if an I/O error occurs

public void appendFooterHeaderStyleXMLToAutomaticStyle(final XMLUtil util,
														   final Appendable appendable, final Type pageSectionType) throws IOException {
		appendable.append("<style:").append(pageSectionType.getTypeName())
				.append("-style>");
		appendable.append("<style:header-footer-properties");
		util.appendAttribute(appendable, "fo:min-height", this.minHeight.toString());
		this.margins.appendXMLContent(util, appendable);
		appendable.append("/></style:").append(pageSectionType.getTypeName())
				.append("-style>");
	}

public static void loadPageFlow(ServletRequest request, PageFlowController pageFlow) {
        if(pageFlow != null)
            request.setAttribute(PAGE_FLOW_IMPLICIT_OBJECT_KEY, pageFlow);

        Map map = InternalUtils.getPageInputMap(request);
        request.setAttribute(PAGE_INPUT_IMPLICIT_OBJECT_KEY, map != null ? map : Collections.EMPTY_MAP);
    }

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


Question:
Set the charset used by the SimpleHtmlDom object.
@param  string $charset
@return bool

public function setCharset($charset)
    {
        if (GenericValidator::validateCharset($charset)) {
            $this->charset = $charset;
            return true;
        }
        return false;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question: // DeleteCollection returns a function that will handle a collection deletion

func DeleteCollection(r rest.CollectionDeleter, checkBody bool, scope *RequestScope, admit admission.Interface) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		trace := utiltrace.New("Delete " + req.URL.Path)
		defer trace.LogIfLong(500 * time.Millisecond)

		if isDryRun(req.URL) && !utilfeature.DefaultFeatureGate.Enabled(features.DryRun) {
			scope.err(errors.NewBadRequest("the dryRun alpha feature is disabled"), w, req)
			return
		}

		// TODO: we either want to remove timeout or document it (if we document, move timeout out of this function and declare it in api_installer)
		timeout := parseTimeout(req.URL.Query().Get("timeout"))

		namespace, err := scope.Namer.Namespace(req)
		if err != nil {
			scope.err(err, w, req)
			return
		}

		ctx := req.Context()
		ctx = request.WithNamespace(ctx, namespace)
		ae := request.AuditEventFrom(ctx)

		outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)
		if err != nil {
			scope.err(err, w, req)
			return
		}

		listOptions := metainternalversion.ListOptions{}
		if err := metainternalversion.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, &listOptions); err != nil {
			err = errors.NewBadRequest(err.Error())
			scope.err(err, w, req)
			return
		}

		// transform fields
		// TODO: DecodeParametersInto should do this.
		if listOptions.FieldSelector != nil {
			fn := func(label, value string) (newLabel, newValue string, err error) {
				return scope.Convertor.ConvertFieldLabel(scope.Kind, label, value)
			}
			if listOptions.FieldSelector, err = listOptions.FieldSelector.Transform(fn); err != nil {
				// TODO: allow bad request to set field causes based on query parameters
				err = errors.NewBadRequest(err.Error())
				scope.err(err, w, req)
				return
			}
		}

		options := &metav1.DeleteOptions{}
		if checkBody {
			body, err := limitedReadBody(req, scope.MaxRequestBodyBytes)
			if err != nil {
				scope.err(err, w, req)
				return
			}
			if len(body) > 0 {
				s, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer)
				if err != nil {
					scope.err(err, w, req)
					return
				}
				defaultGVK := scope.Kind.GroupVersion().WithKind("DeleteOptions")
				obj, _, err := scope.Serializer.DecoderToVersion(s.Serializer, defaultGVK.GroupVersion()).Decode(body, &defaultGVK, options)
				if err != nil {
					scope.err(err, w, req)
					return
				}
				if obj != options {
					scope.err(fmt.Errorf("decoded object cannot be converted to DeleteOptions"), w, req)
					return
				}

				ae := request.AuditEventFrom(ctx)
				audit.LogRequestObject(ae, obj, scope.Resource, scope.Subresource, scope.Serializer)
			} else {
				if err := metainternalversion.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {
					err = errors.NewBadRequest(err.Error())
					scope.err(err, w, req)
					return
				}
			}
		}
		if errs := validation.ValidateDeleteOptions(options); len(errs) > 0 {
			err := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: "DeleteOptions"}, "", errs)
			scope.err(err, w, req)
			return
		}

		admit = admission.WithAudit(admit, ae)
		if admit != nil && admit.Handles(admission.Delete) {
			userInfo, _ := request.UserFrom(ctx)
			attrs := admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, "", scope.Resource, scope.Subresource, admission.Delete, dryrun.IsDryRun(options.DryRun), userInfo)
			if mutatingAdmission, ok := admit.(admission.MutationInterface); ok {
				err = mutatingAdmission.Admit(attrs, scope)
				if err != nil {
					scope.err(err, w, req)
					return
				}
			}

			if validatingAdmission, ok := admit.(admission.ValidationInterface); ok {
				err = validatingAdmission.Validate(attrs, scope)
				if err != nil {
					scope.err(err, w, req)
					return
				}
			}
		}

		result, err := finishRequest(timeout, func() (runtime.Object, error) {
			return r.DeleteCollection(ctx, options, &listOptions)
		})
		if err != nil {
			scope.err(err, w, req)
			return
		}

		// if the rest.Deleter returns a nil object, fill out a status. Callers may return a valid
		// object with the response.
		if result == nil {
			result = &metav1.Status{
				Status: metav1.StatusSuccess,
				Code:   http.StatusOK,
				Details: &metav1.StatusDetails{
					Kind: scope.Kind.Kind,
				},
			}
		}

		transformResponseObject(ctx, scope, trace, req, w, http.StatusOK, outputMediaType, result)
	}
}

function(toDelete, evtStck) {
    let len = toDelete.length
    for (let i = 0; len > i; len--) {
      evtStck.splice(toDelete[len - 1], 1)
    }
  }

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


Question:
Verify the tables are in the expected state for the Contents create

@param contents
contents
@throws SQLException
upon verify creation error

private void verifyCreate(Contents contents) throws SQLException {
		ContentsDataType dataType = contents.getDataType();
		if (dataType != null) {
			switch (dataType) {
			case FEATURES:

				// Features require Geometry Columns table (Spec Requirement 21)
				GeometryColumnsDao geometryColumnsDao = getGeometryColumnsDao();
				if (!geometryColumnsDao.isTableExists()) {
					throw new GeoPackageException(
							"A data type of "
									+ dataType.getName()
									+ " requires the "
									+ GeometryColumns.class.getSimpleName()
									+ " table to first be created using the GeoPackage.");
				}

				break;

			case TILES:
				verifyTiles(dataType);
				break;

			case GRIDDED_COVERAGE:
				verifyTiles(dataType);
				break;

			case ATTRIBUTES:
				break;

			default:
				throw new GeoPackageException("Unsupported data type: "
						+ dataType);
			}
		}

		// Verify the feature or tile table exists
		if (!db.tableExists(contents.getTableName())) {
			throw new GeoPackageException(
					"No table exists for Content Table Name: "
							+ contents.getTableName()
							+ ". Table must first be created.");
		}
	}

public JDBCAppendTableSink build() {
		Preconditions.checkNotNull(parameterTypes,
			"Types of the query parameters are not specified." +
			" Please specify types using the setParameterTypes() method.");

		JDBCOutputFormat format = JDBCOutputFormat.buildJDBCOutputFormat()
			.setUsername(username)
			.setPassword(password)
			.setDBUrl(dbURL)
			.setQuery(query)
			.setDrivername(driverName)
			.setBatchInterval(batchSize)
			.setSqlTypes(parameterTypes)
			.finish();

		return new JDBCAppendTableSink(format);
	}

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


Question:
Return a copy of this resolvable set but with built packages.

    :param dict built_packages: A mapping from a resolved package to its locally built package.
    :returns: A new resolvable set with built package replacements made.

def replace_built(self, built_packages):

    def map_packages(resolved_packages):
      packages = OrderedSet(built_packages.get(p, p) for p in resolved_packages.packages)
      return _ResolvedPackages(resolved_packages.resolvable, packages,
                               resolved_packages.parent, resolved_packages.constraint_only)

    return _ResolvableSet([map_packages(rp) for rp in self.__tuples])

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
Return the xml of the task list

@return string

public function toXML(){

            $oXMLout = new \XMLWriter();
            $oXMLout->openMemory();
            $oXMLout->setIndent(true);
            $oXMLout->setIndentString('    ');

        $oXMLout->startDocument("1.0", 'utf-8');
        $oXMLout->startElement('tasks');

        /**
         * @var \Dlin\Saasu\Task\Task $task
         */
        foreach($this->tasks as $task){
           $oXMLout->writeRaw("\n".$task->toXML());
        }
        $oXMLout->endElement();
        $oXMLout->endDocument();

        $xml = $oXMLout->outputMemory();

        return $xml;
    }

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

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


Question:
Construct an attributed tree for a cast of expression to target type,
unless it already has precisely that type.
@param tree    The expression tree.
@param target  The target type.

JCExpression cast(JCExpression tree, Type target) {
        int oldpos = make.pos;
        make.at(tree.pos);
        if (!types.isSameType(tree.type, target)) {
            if (!resolve.isAccessible(env, target.tsym))
                resolve.logAccessErrorInternal(env, tree, target);
            tree = make.TypeCast(make.Type(target), tree).setType(target);
        }
        make.pos = oldpos;
        return tree;
    }

private synchronized Collection<IResult> valuesToParameters(Process process, ValueMap<Output, OWLValue> values) throws NotYetImplementedException, OWLTranslationException
    {
        if (values.isEmpty())
        {
            return null;
        }
        Collection<IResult> parameters = new ArrayList<IResult>();
        Iterator<Entry<Output, OWLValue>> valuesIterator = values.iterator();
        while (valuesIterator.hasNext())
        {
            Entry<Output, OWLValue> valuesEntry = valuesIterator.next();
            final OWLSParameter parameter
                    = new OWLSParameter(
                            process.getOntology(),
                            valuesEntry.getKey().getName(),
                            valuesEntry.getValue());
            parameters.add(new IOutputValue()
            {
                @Override
                public IOutput getOutput()
                {
                    try
                    {
                        return output(parameter.name());
                    } catch (ModelException ex)
                    {
                        return null;
                    }
                }

                @Override
                public Object object() throws ModelException
                {
                    return parameter.object();
                }

                @Override
                public ISemanticIdentifier getSemanticAnnotation()
                {
                    return parameter.getSemanticAnnotation();
                }

                @Override
                public ISubject value() throws ModelException
                {
                    if (null != functionalityGrounding)
                    {
                        return functionalityGrounding.createOutput(parameter.object(), OWLSAtomicService.this).value();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        return parameters;
    }

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


Question:
Gets a sql builder for handling the database
@return Sql\Builder

public function SqlBuilder()
    {
        if (!$this->builder)
            $this->builder = new Sql\Builder($this->Connection());

        return $this->builder;
    }

public function alias(string $alias, ?string $table = null): IQueryBuilderHandler
    {
        if ($table === null && isset($this->statements['tables'][0]) === true) {
            $table = $this->statements['tables'][0];
        } else {
            $table = $this->tablePrefix . $table;
        }

        $this->statements['aliases'][$table] = \strtolower($alias);

        return $this;
    }

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


Question:
Initializes the state for AutoUpdate process
@returns {$.Deferred} - a jquery promise,
that is resolved with success or failure
of state initialization

function initializeState() {
        var result = $.Deferred();

        FileSystem.resolve(updateDir, function (err) {
            if (!err) {
                result.resolve();
            } else {
                var directory = FileSystem.getDirectoryForPath(updateDir);
                directory.create(function (error) {
                    if (error) {
                        console.error('AutoUpdate : Error in creating update directory in Appdata');
                        result.reject();
                    } else {
                        result.resolve();
                    }
                });
            }
        });

        return result.promise();
    }

function ProtoSet (defaultValues, opts) {
  var self = this
  self.object = []
  self.sources = []
  self.releases = []
  self.binder = LazyWatcher.call(self, self._update, self._listen, self._unlisten)
  self.binder.value = this.object

  if (opts && opts.nextTick) self.binder.nextTick = true
  if (opts && opts.idle) self.binder.idle = true

  if (defaultValues && defaultValues.length) {
    defaultValues.forEach(function (valueOrObs) {
      if (!~self.sources.indexOf(valueOrObs)) {
        self.sources.push(valueOrObs)
      }
    })
    this._update()
  }
}

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


Question:
lookup

@param array $queris
@param mixed $size
@param int $offset
@access public
@return void

public function lookup(array $queries = array())
    {
        try {
            $request  = $this->requestLookup($queries);
            $response = $this->getClient()->send($request);
        } catch(\Exception $ex) {
            throw new \RuntimeException('Failed to get response', 0, $ex);
        }

        // if success level,
        if(2 == floor($response->getStatusCode()/100)) {
            $contentType = $response->getHeader('Content-Type');

            switch($contentType) {
            case 'application/json':
                return $response->json();
            case 'application/xml':
                return $response->xml();
            default:
                //throw new UnsupportedFormatException(sprintf('Content-Type "%s" is not supported.', $response->getHeader('Content-Type')));
                throw new \RuntimeException(sprintf('Content-Type "%s" is not supported.', $contentType));
            }
        }

        throw new \RuntimeException(sprintf('Failed to get the response: StatusCode [%d]', $response->getStatusCode()));
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Write the widget markup into the Markup Writer
@param {aria.templates.MarkupWriter} out Markup Writer

function (out) {

            if (!this._cfgOk) {
                return aria.widgets.TemplateBasedWidget.superclass.writeMarkup.call(this, out);
            }

            // Prepare delegation id before to have it linked with this widget
            this._tplWidget._delegateId = aria.utils.Delegate.add({
                fn : this.delegate,
                scope : this
            });
            this._tplWidget.writeMarkup(out);

            this._domReady = true;
        }

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question:
Gets the repository for this entity

@return Table

protected function _repository()
    {
        $source = $this->getSource();
        if ($source === null) {
            list(, $class) = namespaceSplit(get_class($this));
            $source = Inflector::pluralize($class);
        }

        return TableRegistry::getTableLocator()->get($source);
    }

func (session *Session) CreateTable(bean interface{}) error {
	v := rValue(bean)
	session.Statement.setRefValue(v)

	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	return session.createOneTable()
}

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


Question: Throws an IllegalArgumentException if a type's kind is one of a set.

private void validateTypeNotIn(TypeMirror t, Set<TypeKind> invalidKinds) {
        if (invalidKinds.contains(t.getKind()))
            throw new IllegalArgumentException(t.toString());
    }

@Override
    public void setDType(DataType dtype) {
        assert dtype == DataType.DOUBLE || dtype == DataType.FLOAT
                        || dtype == DataType.INT : "Invalid opType passed, must be float or double";
        // this.dtype = dtype;
    }

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