Question:
Read a utf8 encoded line from a data input stream.
@param lineReader LineReader to read the line from.
@param out Text to read into
@return number of bytes read
@deprecated use
{@link StreamKeyValUtil#readLine(LineReader, Text)}
@throws IOException

@Deprecated
  public static int readLine(LineReader lineReader, Text out)
  throws IOException {
    return StreamKeyValUtil.readLine(lineReader, out);
  }

public static Buffer consumeAlphaNum(final Buffer buffer) throws IOException {
        final int count = getAlphaNumCount(buffer);
        if (count == 0) {
            return null;
        }
        return buffer.readBytes(count);
    }

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


Question:
/*
Merges the given change into a "PATCH"-change contained in the change set if possible.

@param {object} oChange The current change
@returns {boolean} Whether the current change is merged into a change in the change set

function mergePatch(oChange) {
			if (oChange.method !== "PATCH") {
				return false;
			}
			return aChangeSet.some(function (oCandidate) {
				if (oCandidate.method === "PATCH"
						&& oCandidate.headers["If-Match"] === oChange.headers["If-Match"]) {
					jQuery.extend(true, oCandidate.body, oChange.body);
					oChange.$resolve(oCandidate.$promise);
					return true;
				}
			});
		}

private function matchRelationship(
        Identity $identity,
        object $entity,
        Relationship $meta,
        MapInterface $changeset,
        Query $query
    ): Query {
        $name = $this->name->sprintf(\md5($identity->value()));
        $this->variables = $this->variables->put(
            $name,
            $this->buildProperties(
                $changeset,
                $meta->properties()
            )
        );

        return $query
            ->match()
            ->linkedTo()
            ->through(
                (string) $meta->type(),
                (string) $name
            )
            ->withProperty(
                $meta->identity()->property(),
                (string) $name
                    ->prepend('{')
                    ->append('_identity}')
            )
            ->withParameter(
                (string) $name->append('_identity'),
                $identity->value()
            );
    }

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


Question: // SetLayers sets the Layers field's value.

func (s *UpdateFunctionConfigurationInput) SetLayers(v []*string) *UpdateFunctionConfigurationInput {
	s.Layers = v
	return s
}

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

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


Question:
Helper method which sets up an iteration with the given vertex value.

@param iteration

private void setUpIteration(DeltaIteration<?, ?> iteration) {

		// set up the iteration operator
		if (this.configuration != null) {

			iteration.name(this.configuration.getName("Vertex-centric iteration (" + computeFunction + ")"));
			iteration.parallelism(this.configuration.getParallelism());
			iteration.setSolutionSetUnManaged(this.configuration.isSolutionSetUnmanagedMemory());

			// register all aggregators
			for (Map.Entry<String, Aggregator<?>> entry : this.configuration.getAggregators().entrySet()) {
				iteration.registerAggregator(entry.getKey(), entry.getValue());
			}
		}
		else {
			// no configuration provided; set default name
			iteration.name("Vertex-centric iteration (" + computeFunction + ")");
		}
	}

def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
                       config: TextProcessingConfig) -> Iterator[str]:
    # only called if docx loaded

    if in_order:
        for thing in docx_docx_iter_block_items(doc):
            if isinstance(thing, docx.text.paragraph.Paragraph):
                yield docx_process_simple_text(thing.text, config.width)
            elif isinstance(thing, docx.table.Table):
                yield docx_process_table(thing, config)
    else:
        for paragraph in doc.paragraphs:
            yield docx_process_simple_text(paragraph.text, config.width)
        for table in doc.tables:
            yield docx_process_table(table, config)

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


Question:
// parsePAXTime takes a string of the form %d.%d as described in the PAX
// specification. Note that this implementation allows for negative timestamps,
// which is allowed for by the PAX specification, but not always portable.

func parsePAXTime(s string) (time.Time, error) {
	const maxNanoSecondDigits = 9

	// Split string into seconds and sub-seconds parts.
	ss, sn := s, ""
	if pos := strings.IndexByte(s, '.'); pos >= 0 {
		ss, sn = s[:pos], s[pos+1:]
	}

	// Parse the seconds.
	secs, err := strconv.ParseInt(ss, 10, 64)
	if err != nil {
		return time.Time{}, ErrHeader
	}
	if len(sn) == 0 {
		return time.Unix(secs, 0), nil // No sub-second values
	}

	// Parse the nanoseconds.
	if strings.Trim(sn, "0123456789") != "" {
		return time.Time{}, ErrHeader
	}
	if len(sn) < maxNanoSecondDigits {
		sn += strings.Repeat("0", maxNanoSecondDigits-len(sn)) // Right pad
	} else {
		sn = sn[:maxNanoSecondDigits] // Right truncate
	}
	nsecs, _ := strconv.ParseInt(sn, 10, 64) // Must succeed
	if len(ss) > 0 && ss[0] == '-' {
		return time.Unix(secs, -1*int64(nsecs)), nil // Negative correction
	}
	return time.Unix(secs, int64(nsecs)), nil
}

public com.google.protobuf.Timestamp toProto() {
    return com.google.protobuf.Timestamp.newBuilder().setSeconds(seconds).setNanos(nanos).build();
  }

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


Question:
Normalize tree data
@param array $data
@param string $parentId
@return array

protected function normalizeData(array $data, $parentId = null) {
        $result = [];
        foreach ($data as $element) {
            if (ArrayHelper::getValue($element, $this->parentColumnName) === $parentId) {
                $result[] = $element;
                $children = $this->normalizeData($data, ArrayHelper::getValue($element, $this->keyColumnName));
                if ($children) {
                    $result = array_merge($result, $children);
                }
            }
        }
        return $result;
    }

private function renderPaths()
    {
        if (!$this->pathsTable) {
            $this->pathsTable = new Table($this->io);
            $style = clone Table::getStyleDefinition('symfony-style-guide');
            $this->pathsTable->setStyle($style);

            $this->pathsTable->setHeaders(['#', 'Name', 'Path']);

            $style = clone $style;
            $style->setCellHeaderFormat('<info>%s</info>');
            $this->pathsTable->setColumnStyle(0, $style);
        }

        $i = 0;
        $rows = [];
        $root = $this->resolver->resolve('root');
        foreach ($this->resolver->names() as $name) {
            $raw = $this->resolver->raw($name);
            $resolved = $this->resolver->resolve($name);
            $resolved = Path::makeRelative($resolved, $root);
            if ($resolved === '') {
                $resolved = '.';
            }
            $path = "<comment>$raw</comment>";
            if ($raw !== $resolved) {
                $path .= " ($resolved)";
            }
            $rows[] = ['<info>' . ++$i . '</info>', "<info>$name</info>", $path];
        }
        $this->pathsTable->setRows($rows);

        $this->pathsTable->overwrite();
    }

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


Question:
Determine if 'path' is an key or property of another object
@param {NodePath} path
@returns {Boolean}

function isPropertyOrKey(path) {
  return path.parentPath.get('key') === path || path.parentPath.get('property') === path;
}

public function andLeftnodeEquals($leftnode, $alias = null)
    {
        list($alias, $suffix) = $this->getAliasAndSuffix($alias);

        return $this->andWhere($alias.'._leftnode = :leftnode'.$suffix)
                        ->setParameter('leftnode'.$suffix, $leftnode);
    }

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


Question: Loads the RefasterJs template. This must be called before the scanner is used.

public void loadRefasterJsTemplate(String refasterjsTemplate) throws IOException  {
    checkState(
        templateJs == null, "Can't load RefasterJs template since a template is already loaded.");
    this.templateJs =
        Thread.currentThread().getContextClassLoader().getResource(refasterjsTemplate) != null
            ? Resources.toString(Resources.getResource(refasterjsTemplate), UTF_8)
            : Files.asCharSource(new File(refasterjsTemplate), UTF_8).read();
  }

function addUrl(when, feed) {
  if (!types.check(feed, 'feed') && !types.check(feed, ['feed']))
    throw Error('sandcrawler.spider.url(s): wrong argument.');

  var a = !(feed instanceof Array) ? [feed] : feed,
      c = !this.state.running ? this.initialBuffer.length : this.index,
      job,
      i,
      l;

  for (i = 0, l = a.length; i < l; i++) {
    job = createJob(a[i]);

    // Don't add if already at limit
    if (this.options.limit && c >= this.options.limit)
      break;

    if (!this.state.running) {
      this.initialBuffer[when === 'later' ? 'push' : 'unshift'](job);
    }
    else {
      this.queue[when === 'later' ? 'push' : 'unshift'](job);
      this.emit('job:add', job);
    }
  }

  return this;
}

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


Question:
Splits the given secret into {@code n} parts, of which any {@code k} or more can be combined to
recover the original secret.

@param secret the secret to split
@return a map of {@code n} part IDs and their values

public Map<Integer, byte[]> split(byte[] secret) {
    // generate part values
    final byte[][] values = new byte[n][secret.length];
    for (int i = 0; i < secret.length; i++) {
      // for each byte, generate a random polynomial, p
      final byte[] p = GF256.generate(random, k - 1, secret[i]);
      for (int x = 1; x <= n; x++) {
        // each part's byte is p(partId)
        values[x - 1][i] = GF256.eval(p, (byte) x);
      }
    }

    // return as a set of objects
    final Map<Integer, byte[]> parts = new HashMap<>(n());
    for (int i = 0; i < values.length; i++) {
      parts.put(i + 1, values[i]);
    }
    return Collections.unmodifiableMap(parts);
  }

def request(self, method, url, params=None, **aio_kwargs):
        """"""
        oparams = {
            'oauth_consumer_key': self.consumer_key,
            'oauth_nonce': sha1(str(RANDOM()).encode('ascii')).hexdigest(),
            'oauth_signature_method': self.signature.name,
            'oauth_timestamp': str(int(time.time())),
            'oauth_version': self.version,
        }
        oparams.update(params or {})

        if self.oauth_token:
            oparams['oauth_token'] = self.oauth_token

        url = self._get_url(url)

        if urlsplit(url).query:
            raise ValueError(
                'Request parameters should be in the "params" parameter, '
                'not inlined in the URL')

        oparams['oauth_signature'] = self.signature.sign(
            self.consumer_secret, method, url,
            oauth_token_secret=self.oauth_token_secret, **oparams)
        self.logger.debug("%s %s", url, oparams)

        return self._request(method, url, params=oparams, **aio_kwargs)

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


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

public EClass getIfcCircleHollowProfileDef() {
		if (ifcCircleHollowProfileDefEClass == null) {
			ifcCircleHollowProfileDefEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(77);
		}
		return ifcCircleHollowProfileDefEClass;
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
Perform multi-term search by splitting keyword into
individual words and searches for each of them.

@param string $keyword

protected function smartGlobalSearch($keyword)
    {
        collect(explode(' ', $keyword))
            ->reject(function ($keyword) {
                return trim($keyword) === '';
            })
            ->each(function ($keyword) {
                $this->globalSearch($keyword);
            });
    }

public function InExpression()
    {
        $inExpression = new AST\InExpression($this->ArithmeticExpression());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $inExpression->not = true;
        }

        $this->match(Lexer::T_IN);
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->subselect = $this->Subselect();
        } else {
            $literals   = [];
            $literals[] = $this->InParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
                $literals[] = $this->InParameter();
            }

            $inExpression->literals = $literals;
        }

        $this->match(Lexer::T_CLOSE_PARENTHESIS);

        return $inExpression;
    }

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


Question:
Prepare footer.

@param  \Arcanedev\LogViewer\Tables\StatsTable  $stats

@return array

private function prepareFooter(StatsTable $stats)
    {
        $files = [
            'count' => count($stats->rows()).' log file(s)'
        ];

        return $files + $stats->footer();
    }

public function generate()
    {
        if (count($this->functions) === 0) {
            throw new \Exception('function list empty');
        }

        $parts = [];
        foreach ($this->functions as $function) {
            $args = [];
            if ($function['args']) {
                $args = $this->generateArgs($function['args']);
            }
            $parts[] = $function['name'].'('.implode(', ', $args).')';
        }

        $class = $this->class['name'];
        $class .= count($this->class['args']) ? '('.implode(', ', $this->class['args']).')' : '';

        $result = $class.($this->isStatic() ? '::' : '->').implode($parts, '->');

        return $result;
    }

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


Question: // SetS3ResourcesUpdate sets the S3ResourcesUpdate field's value.

func (s *UpdateS3ResourcesInput) SetS3ResourcesUpdate(v []*S3ResourceClassificationUpdate) *UpdateS3ResourcesInput {
	s.S3ResourcesUpdate = v
	return s
}

def add_triple(self, subj, pred, obj):
        '''  '''
        subj_data, pred_data, obj_data = self.are_ilx([subj, pred, obj])
        # RELATIONSHIP PROPERTY
        if subj_data.get('id') and pred_data.get('id') and obj_data.get('id'):
            if pred_data['type'] != 'relationship':
                return self.test_check('Adding a relationship as formate \
                                       "term1_ilx relationship_ilx term2_ilx"')
            return self.add_relationship(term1=subj_data,
                                         relationship=pred_data,
                                         term2=obj_data)
        # ANNOTATION PROPERTY
        elif subj_data.get('id') and pred_data.get('id'):
            if pred_data['type'] != 'annotation':
                return self.test_check('Adding a relationship as formate \
                                       "term_ilx annotation_ilx value"')
            return self.add_annotation(entity=subj_data,
                                       annotation=pred_data,
                                       value=obj)
        # UPDATE ENTITY
        elif subj_data.get('id'):
            data = subj_data
            _pred = self.ttl2sci_map.get(pred)
            if not _pred:
                error = pred + " doesnt not have correct RDF format or It is not an option"
                return self.test_check(error)
            data = self.custom_update(data, _pred, obj)
            if data == 'failed':  # for debugging custom_update
                return data
            data = superclasses_bug_fix(data)
            url_base = self.base_path + 'term/edit/{id}'
            url = url_base.format(id=data['id'])
            return self.post(url, data)
        else:
            return self.test_check('The ILX ID(s) provided do not exist')

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


Question: // SetTags sets the Tags field's value.

func (s *ActivateGatewayInput) SetTags(v []*Tag) *ActivateGatewayInput {
	s.Tags = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Attributes::removeAttribute

@param string|array $attributes

public function removeAttribute($attributes)
    {
        if (is_string($attributes)) {
            $attributes = explode(',', $attributes);
        }

        $attributes = array_map('trim', $attributes);
        $attributes = array_filter($attributes);

        foreach ($attributes as $attribute) {
            if (array_key_exists($attribute, $this->storage)) {
                unset($this->storage[ $attribute ]);
            } elseif (strpos($attribute, '*') !== false) {
                $attribute = str_replace('*', '', $attribute);
                foreach ($this->storage as $key => $value) {
                    if (preg_match("/\b$attribute\b/i", $key)) {
                        unset($this->storage[ $key ]);
                    }
                }
            }
        }
    }

public function attr()
    {
        $args = func_get_args();

        $this->each(function ($item) use ($args) {
            if (count($args) >= 2) {
                $item->attr($args[0], $args[1]);
            } else {
                $item->attr($args[0]);
            }
        });

        return $this;
    }

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


Question:
// NetworkConnect connects the container to the specified network
// FIXME(vdemeester) will be refactor with Container refactoring

func (s *Service) NetworkConnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error {
	containerID := c.ID()
	client := s.clientFactory.Create(s)
	internalLinks, err := s.getLinks()
	if err != nil {
		return err
	}
	links := []string{}
	// TODO(vdemeester) handle link to self (?)
	for k, v := range internalLinks {
		links = append(links, strings.Join([]string{v, k}, ":"))
	}
	for _, v := range s.serviceConfig.ExternalLinks {
		links = append(links, v)
	}
	aliases := []string{}
	if !oneOff {
		aliases = []string{s.Name()}
	}
	aliases = append(aliases, net.Aliases...)
	if len(net.Aliases) >= 1 {
		logrus.Infof("connect")
		client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{
			Aliases:   aliases,
			Links:     links,
			IPAddress: net.IPv4Address,
			IPAMConfig: &network.EndpointIPAMConfig{
				IPv4Address: net.IPv4Address,
				IPv6Address: net.IPv6Address,
			},
		})
		logrus.Infof("disconnect")
		client.NetworkDisconnect(ctx, net.RealName, containerID, true)
	}
	return client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{
		Aliases:   aliases,
		Links:     links,
		IPAddress: net.IPv4Address,
		IPAMConfig: &network.EndpointIPAMConfig{
			IPv4Address: net.IPv4Address,
			IPv6Address: net.IPv6Address,
		},
	})
}

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Returns our current runtime statistics. Note: don't call this method too
frequently as it is synchronized and will contend with the network I/O thread.

public synchronized ConMgrStats getStats ()
    {
        // fill in our snapshot values
        _stats.connectionCount = _connections.size();
        _stats.handlerCount = _handlers.size();
        _stats.deathQueueSize = _deathq.size();
        _stats.outQueueSize = _outq.size();
        if (_oflowqs.size() > 0) {
            _stats.overQueueSize = 0;
            for (OverflowQueue oq : _oflowqs.values()) {
                _stats.overQueueSize += oq.size();
            }
        }
        return _stats.clone();
    }

public void endTiming(String name, float elapsed) {
		for (ICounters counter : _counters) {
			if (counter instanceof ITimingCallback)
				((ITimingCallback) counter).endTiming(name, elapsed);
		}
	}

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


Question: Translates a dictdiffer conflict into a json_merger one.

def patch_to_conflict_set(patch):
    """"""
    patch_type, patched_key, value = patch
    if isinstance(patched_key, list):
        key_path = tuple(patched_key)
    else:
        key_path = tuple(k for k in patched_key.split('.') if k)

    conflicts = set()
    if patch_type == REMOVE:
        conflict_type = ConflictType.REMOVE_FIELD
        for key, obj in value:
            conflicts.add(Conflict(conflict_type, key_path + (key, ), None))
    elif patch_type == CHANGE:
        conflict_type = ConflictType.SET_FIELD
        first_val, second_val = value
        conflicts.add(Conflict(conflict_type, key_path, second_val))
    elif patch_type == ADD:
        conflict_type = ConflictType.SET_FIELD
        for key, obj in value:
            conflicts.add(Conflict(conflict_type, key_path + (key, ), obj))

    return conflicts

private static void checkNoConflictInValueBucket(
      Object value, Entry<?, ?> entry, @Nullable ImmutableMapEntry<?, ?> valueBucketHead) {
    for (; valueBucketHead != null; valueBucketHead = valueBucketHead.getNextInValueBucket()) {
      checkNoConflict(!value.equals(valueBucketHead.getValue()), "value", entry, valueBucketHead);
    }
  }

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


Question:
Clear/remove any existing loss variables, and set the loss variables to the specified variable names.<br>
See {@link #addLossVariable(String)} for more details
@param lossVariableNames Names of variables to be loss function variables

public void setLossVariables(String... lossVariableNames){
        this.lossVariables.clear();
        for(String s : lossVariableNames){
            addLossVariable(s);
        }
        //After changing loss function variables, we (probably) need to recreate gradient function - as gradient
        // function is defined with respect to specific loss function variables
        sameDiffFunctionInstances.remove("grad");
    }

def load_scalars(filename, strict_type_checks=True):

    # Parse the scalar definitions from the YAML file.
    scalars = None
    try:
        with open(filename, 'r') as f:
            scalars = yaml.safe_load(f)
    except IOError as e:
        raise ParserError('Error opening ' + filename + ': ' + e.message)
    except ValueError as e:
        raise ParserError('Error parsing scalars in {}: {}'
                          '.\nSee: {}'.format(filename, e.message, BASE_DOC_URL))

    scalar_list = []

    # Scalars are defined in a fixed two-level hierarchy within the definition file.
    # The first level contains the category name, while the second level contains the
    # probe name (e.g. "category.name: probe: ...").
    for category_name in scalars:
        category = scalars[category_name]

        # Make sure that the category has at least one probe in it.
        if not category or len(category) == 0:
            raise ParserError('Category "{}" must have at least one probe in it' +
                              '.\nSee: {}'.format(category_name, BASE_DOC_URL))

        for probe_name in category:
            # We found a scalar type. Go ahead and parse it.
            scalar_info = category[probe_name]
            scalar_list.append(
                ScalarType(category_name, probe_name, scalar_info, strict_type_checks))

    return scalar_list

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


Question: // Get searches option from flag/env/config/remote/default. It returns nil if option is not found.

func (m *Manager) Get(key string) interface{} {
	// ensure loaded
	if !m.loaded {
		err := m.load(false)
		if err != nil {
			panic(err)
		}
	}

	opt := m.options.Find(key)
	def := m.defaults.Find(key)
	if def == nil {
		return opt
	} else if opt == nil {
		return def
	} else if v, err := cast.TryToValue(opt, reflect.TypeOf(def)); err == nil {
		return v
	}
	return opt
}

function getOptions () {
  return {
    compress: ('compress' in program) ? program.compress : false,
    debug: ('debug' in program) ? program.debug : false,
    deploy: false,
    grep: ('grep' in program) ? program.grep : false,
    invert: ('invert' in program) ? program.invert : false,
    maps: ('maps' in program) ? program.maps : false,
    reload: ('reload' in program) ? program.reload : false,
    script: ('script' in program) ? program.script : false,
    serve: ('serve' in program) ? program.serve : false,
    watch: false
  };
}

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


Question:
@param string   $name
@param array    $parameters
@param bool|int $relative

@return string

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

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

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

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

        return '';
    }

public static void configureQueryOptions(DatabaseClient client)
    throws FailedRequestException, ForbiddenUserException, ResourceNotFoundException, ResourceNotResendableException
  {
    // create a manager for writing query options
    QueryOptionsManager optionsMgr = client.newServerConfigManager().newQueryOptionsManager();

    // create the query options
    String options =
      "<search:options "+
        "xmlns:search='http://marklogic.com/appservices/search'>"+
        "<search:constraint name='industry'>"+
        "<search:value>"+
        "<search:element name='industry' ns=''/>"+
        "</search:value>"+
        "</search:constraint>"+
        "<search:return-aggregates>false</search:return-aggregates>"+
        "<search:return-constraints>false</search:return-constraints>"+
        "<search:return-facets>false</search:return-facets>"+
        "<search:return-frequencies>false</search:return-frequencies>"+
        "<search:return-metrics>false</search:return-metrics>"+
        "<search:return-plan>false</search:return-plan>"+
        "<search:return-qtext>false</search:return-qtext>"+
        "<search:return-query>false</search:return-query>"+
        "<search:return-similar>true</search:return-similar>"+
        "<search:return-values>false</search:return-values>"+
        "<search:return-results>false</search:return-results>"+
        "<search:transform-results apply='empty-snippet'/>"+
        "</search:options>";

    // create a handle to send the query options
    StringHandle writeHandle = new StringHandle(options);

    // write the query options to the database
    optionsMgr.writeOptions(OPTIONS_NAME, writeHandle);

    System.out.println("Configured the query options on the server");
  }

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


Question:
Closes existing database connection.

@return  void

public function closeConnection(): void
    {
        if ($this->isConnected) {
            @$this->currentLink->close();
            $this->isConnected = false;
            $this->currentLink = null;
            $this->currentDB = null;
            $this->selectedDB = '';
        }
    }

def _cleanup(self):
        '''

        '''
        self._pending_consumers = None
        self._consumer_cb = None
        self._get_cb = None
        self._recover_cb = None
        self._cancel_cb = None
        self._return_listener = None
        super(BasicClass, self)._cleanup()

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


Question: Update document counter

private function _updateDocCount()
    {
        $this->_docCount = 0;
        foreach ($this->_segmentInfos as $segInfo) {
            $this->_docCount += $segInfo->count();
        }
    }

@NonNull
    @Override
    public MutableDocument setInt(@NonNull String key, int value) {
        return setValue(key, value);
    }

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


Question: Function for `Translate()` pseudo-builder

def _translate(env, target=None, source=SCons.Environment._null, *args, **kw):

    if target is None: target = []
    pot = env.POTUpdate(None, source, *args, **kw)
    po = env.POUpdate(target, pot, *args, **kw)
    return po

protected function compileParsers($value)
    {
        foreach ($this->parsers as $parser) {
            $value = call_user_func($parser, $value, $this);
        }

        return $value;
    }

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


Question:
Returns the fields in cache.

@return array|null The fields in cache, or null if there is not.

public function getFieldsCache()
    {
        $cache = $this->repository->getMandango()->getCache()->get($this->hash);

        return ($cache && isset($cache['fields'])) ? $cache['fields'] : null;
    }

public function set($key, $data, $expire = 0) {
		if ($data instanceof ModelArray) {
			$modelArray = explode('\\', get_class($data[0]));
			$modelName = count($data) == 0 ? '': end($modelArray);
			$data = [
				'__fsm' => [
					'm' => $modelName,
					'a' => 1
				],
				'data' => $data->toArray()
			];
		} else if ($data instanceof Model) {
			$modelArray = explode('\\', get_class($data));
			$modelName = count($data) == 0 ? '': end($modelArray);
			$data = [
				'__fsm' => [
					'm' => $modelName,
					'a' => 0
				],
				'data' => $data->toArray()
			];
		}
		//print_r($data);
		CacheFactory::getCache()->set($key, $data, $expire);
	}

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


Question:
Gets all properties set on this element.

@return  array|Property[]

public function getProperties()
    {
        $properties = [];

        // URL must precede all other properties
        if ($this->url !== null) {
            $properties[] = new Property(Property::IMAGE_URL, $this->url);
        }

        if ($this->height !== null) {
            $properties[] = new Property(Property::IMAGE_HEIGHT, $this->height);
        }

        if ($this->secureUrl !== null) {
            $properties[] = new Property(Property::IMAGE_SECURE_URL, $this->secureUrl);
        }

        if ($this->type !== null) {
            $properties[] = new Property(Property::IMAGE_TYPE, $this->type);
        }

        if ($this->width !== null) {
            $properties[] = new Property(Property::IMAGE_WIDTH, $this->width);
        }

        if ($this->userGenerated !== null) {
            $properties[] = new Property(Property::IMAGE_USER_GENERATED, $this->userGenerated);
        }

        return $properties;
    }

private function setSettings($settings)
    {
        if ($settings) {
            foreach ($this->settings as $key => &$value) {
                if (!empty($settings->{$key}) && $settings->{$key}) {
                    $value = $settings->{$key};
                }
            }
        }
    }

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


Question: Swoole UDP Client Demo

public function udpClient()
    {
        $this->writeln('Starting demo swoole udp client...');

        $client = new TcpClient(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);

        $client->on(
            'connect', function ($cli) {
                //发送数据中不能包含'\r\n\r\n'
                $cli->send(JsonHelper::encode(['handler' => SwooleTcpJob::class]) . self::EOF);
            }
        );
        $client->on(
            'receive', function ($cli, $data) {
                $this->writeln('Received: '.$data);
            }
        );
        $client->on(
            'error', function ($cli) {
                $this->writeln('Connect failed');
            }
        );
        $client->on(
            "close", function ($cli) {
                $this->writeln('Connection close');
            }
        );

        $client->connect(
            $this->swooleConfig['udp']['host'] ?? self::DEFAULT_SWOOLE_HOST,
            $this->swooleConfig['udp']['port'] ?? self::DEFAULT_SWOOLE_PORT,
            $this->swooleConfig['udp']['timeout'] ?? self::DEFAULT_SWOOLE_TIMEOUT
        );
    }

def listen_loop(self):

        while self.listening:
            try:
                data, address = self.sock.recvfrom(self.bufsize)
                self.receive_datagram(data, address)
                if self.stats_enabled:
                    self.stats['bytes_recieved'] += len(data)
            except socket.error as error:
                if error.errno == errno.WSAECONNRESET:
                    logger.info("connection reset")
                else:
                    raise

        logger.info("Shutting down the listener...")

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


Question:
Build a key from the "important" parts of a selector: elements,
        classes, ids.

def lookup_key(self):

        parts = set()
        for node in self.simple_selectors:
            for token in node.tokens:
                if token[0] not in ':[':
                    parts.add(token)

        if not parts:
            # Should always have at least ONE key; selectors with no elements,
            # no classes, and no ids can be indexed as None to avoid a scan of
            # every selector in the entire document
            parts.add(None)

        return frozenset(parts)

function listRegionKeys() {
  const regionKeys = new Array(regionKeysByRegion.size);
  const iter = regionKeysByRegion.values();
  let v = iter.next();
  let i = -1;
  while (!v.done) {
    regionKeys[++i] = v.value;
    v = iter.next();
  }
  return regionKeys;
}

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


Question:
Calculate the start-of-year point of a supplied {@link Calendar}.

<p>
The returned {@link Calendar} has its fields unsynced. Note: if {@code origin} has
unsynced field, it may cause side-effect.
</p>

@param origin
@return

public static Calendar startOfYear(Calendar origin) {
        Calendar cal = (Calendar) origin.clone();
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.DAY_OF_YEAR, 1);
        return cal;
    }

public static IssueCategoryModel loadFromGraph(GraphContext graphContext, IssueCategory issueCategory)
    {
        return loadFromGraph(graphContext.getFramed(), issueCategory.getCategoryID());
    }

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


Question:
Append Path

- manipulate current path

@param iUriSequence $appendUri

@return $this

function append(iUriSequence $appendUri)
    {
        $appendPath = $appendUri->getPath();
        /*if ($appendUri->isAbsolute())
            $appendPath = $this->_makeNoneAbsolutePathSequence($appendPath);*/

        $finalPath = array_merge($this->getPath(), $appendPath);
        $this->setPath($finalPath);

        return $this;
    }

function (data) {
            var temp = addPath(validUrls, url.parse(data.href), bs.options.get("mode"));
            methods.sendUpdatedIfChanged(validUrls, temp, ui.socket);
        }

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


Question:
Create URL with parameters

@param   array $parameters - merge parameters from this parameters
@return  string

public function createUrl(array $parameters = array())
    {
        $final_parameters = $this->getFinalParameters();
        $path = $this->getBaseURL();

        // Override default parameters
        $final_parameters = array_merge($final_parameters, $parameters);

        return $path . "?" . http_build_query($final_parameters, null, '&') . $this->buildFragment();
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question:
Returns the DataObject related to the token
that sent the authenticated request

@param  HTTPRequest          $request    HTTP API request
@return null|DataObject                     null if failed or the DataObject token owner related to the request

public function getOwner(HTTPRequest $request)
    {
        $owner = null;

        //get the token
        $token = $request->getHeader($this->tokenConfig['header']);
        if (!$token) {
            $token = $request->requestVar($this->tokenConfig['queryVar']);
        }

        if ($token) {
            $SQLToken = Convert::raw2sql($token);

            $owner = DataObject::get_one(
                $this->tokenConfig['owner'],
                "\"" . $this->tokenConfig['DBColumn'] . "\"='" . $SQLToken . "'",
                false
            );

            if (!$owner) {
                $owner = null;
            }
        }

        return $owner;
    }

@Override
    @Path("/{dataType}")
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        String dataType = getSegment(path, 1);
        if (dataType == null)
            throw new ServiceException("Missing path segment: {dataType}");
        try {
            BaselineData baselineData = DataAccess.getBaselineData();
            if (dataType.equals("VariableTypes")) {
                List<VariableType> variableTypes = baselineData.getVariableTypes();
                JSONArray jsonArray = new JSONArray();
                for (VariableType variableType : variableTypes)
                    jsonArray.put(variableType.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else if (dataType.equals("TaskCategories")) {
                List<TaskCategory> taskCats = new ArrayList<TaskCategory>();
                taskCats.addAll(baselineData.getTaskCategories().values());
                Collections.sort(taskCats);
                JSONArray jsonArray = new JSONArray();
                for (TaskCategory taskCat : taskCats)
                    jsonArray.put(taskCat.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else {
                throw new ServiceException("Unsupported dataType: " + dataType);
            }
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }

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


Question: // SetManufacturerHardwareCertificate sets the ManufacturerHardwareCertificate field's value.

func (s *Certificates) SetManufacturerHardwareCertificate(v string) *Certificates {
	s.ManufacturerHardwareCertificate = &v
	return s
}

private static String CertificateIDToString(CertificateID certificateID)
  {
    return String.format("CertID. NameHash: %s, KeyHash: %s, Serial Number: %s",
                         byteToHexString(certificateID.getIssuerNameHash()),
                         byteToHexString(certificateID.getIssuerKeyHash()),
                         MessageFormat.format("{0,number,#}",
                                              certificateID.getSerialNumber()));

  }

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


Question:
Public method:
Checks if query was valid and returns how may fields returns
this->columnCount( void ):Void

function columnCount() {
		$result = 0;
		if(!is_null($this->__connection))
			$result = sasql_num_fields($this->__connection);
		return $result;
	}

protected function getDeletedAtColumn(Builder $builder)
    {
        if (count($builder->getQuery()->joins) > 0) {
            return $builder->getModel()->getQualifiedDeletedAtColumn();
        }

        return $builder->getModel()->getDeletedAtColumn();
    }

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


Question:
Gets the source code of a function.

@private
@param {Function} fn The function.
@param {String} altSource A string used when a function's source code is unretrievable.
@returns {String} The function's source code.

function getSource(fn, altSource) {
    var result = altSource;
    if (isStringable(fn)) {
      result = String(fn);
    } else if (support.decompilation) {
      // escape the `{` for Firefox 1
      result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
    }
    return (result || '').replace(/^\s+|\s+$/g, '');
  }

def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False):
        """"""
        if len(tokens) == 1:
            decorators, funcdef = "", tokens[0]
        elif len(tokens) == 2:
            decorators, funcdef = tokens
        else:
            raise CoconutInternalException("invalid function definition tokens", tokens)

        # extract information about the function
        raw_lines = funcdef.splitlines(True)
        def_stmt = raw_lines.pop(0)
        func_name, func_args, func_params = None, None, None
        with self.complain_on_err():
            func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt)

        undotted_name = None  # the function __name__ if func_name is a dotted name
        if func_name is not None:
            if "." in func_name:
                undotted_name = func_name.rsplit(".", 1)[-1]
                def_stmt = def_stmt.replace(func_name, undotted_name)

        # handle async functions
        if is_async:
            if not self.target:
                raise self.make_err(
                    CoconutTargetError,
                    "async function definition requires a specific target",
                    original, loc,
                    target="sys",
                )
            elif self.target_info >= (3, 5):
                def_stmt = "async " + def_stmt
            else:
                decorators += "@_coconut.asyncio.coroutine\n"

            # only Python 3.3+ supports returning values inside generators
            if self.target_info < (3, 3):
                func_code = self.transform_returns(raw_lines, is_async=True)
            else:
                func_code = "".join(raw_lines)

        # handle normal functions
        else:
            # tre does not work with decorators, though tco does
            attempt_tre = func_name is not None and not decorators
            if attempt_tre:
                use_mock = func_args and func_args != func_params[1:-1]
                func_store = tre_store_var + "_" + str(self.tre_store_count)
                self.tre_store_count += 1
                tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock)
            else:
                use_mock = func_store = tre_return_grammar = None

            func_code, tco, tre = self.transform_returns(
                raw_lines,
                tre_return_grammar,
                use_mock,
            )

            if tre:
                comment, rest = split_leading_comment(func_code)
                indent, base, dedent = split_leading_trailing_indent(rest, 1)
                base, base_dedent = split_trailing_indent(base)
                docstring, base = self.split_docstring(base)
                func_code = (
                    comment + indent
                    + (docstring + "\n" if docstring is not None else "")
                    + (
                        "def " + tre_mock_var + func_params + ": return " + func_args + "\n"
                        if use_mock else ""
                    ) + "while True:\n"
                        + openindent + base + base_dedent
                        + ("\n" if "\n" not in base_dedent else "") + "return None"
                        + ("\n" if "\n" not in dedent else "") + closeindent + dedent
                    + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n"
                )
            if tco:
                decorators += "@_coconut_tco\n"  # binds most tightly

        out = decorators + def_stmt + func_code
        if undotted_name is not None:
            out += func_name + " = " + undotted_name + "\n"
        return out

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


Question: // ValidateBasic performs basic validation.

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

protected function getValidationRule($inputName)
    {
        $rules = $this->getValidationRules();

        return is_array($rules[$inputName]) ? $rules[$inputName] : explode('|', $rules[$inputName]);
    }

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


Question:
// fromSignedBytes sets the value of n to the big-endian two's complement
// value stored in the given data. If data[0]&80 != 0, the number
// is negative. If data is empty, the result will be 0.

func fromSignedBytes(n *big.Int, data []byte) {
	n.SetBytes(data)
	if len(data) > 0 && data[0]&0x80 > 0 {
		n.Sub(n, new(big.Int).Lsh(one, uint(len(data))*8))
	}
}

public static int pixelTypeToGL(
    final JCGLPixelFormat p)
  {
    switch (p) {
      case PIXEL_COMPONENT_BYTE:
        return GL11.GL_BYTE;
      case PIXEL_COMPONENT_FLOAT:
        return GL11.GL_FLOAT;
      case PIXEL_COMPONENT_INT:
        return GL11.GL_INT;
      case PIXEL_COMPONENT_SHORT:
        return GL11.GL_SHORT;
      case PIXEL_COMPONENT_UNSIGNED_BYTE:
        return GL11.GL_UNSIGNED_BYTE;
      case PIXEL_COMPONENT_UNSIGNED_INT:
        return GL11.GL_UNSIGNED_INT;
      case PIXEL_COMPONENT_UNSIGNED_SHORT:
        return GL11.GL_UNSIGNED_SHORT;
      case PIXEL_PACKED_UNSIGNED_INT_1010102:
        return GL12.GL_UNSIGNED_INT_10_10_10_2;
      case PIXEL_PACKED_UNSIGNED_SHORT_4444:
        return GLES20.GL_UNSIGNED_SHORT_4_4_4_4;
      case PIXEL_PACKED_UNSIGNED_SHORT_5551:
        return GLES20.GL_UNSIGNED_SHORT_5_5_5_1;
      case PIXEL_PACKED_UNSIGNED_SHORT_565:
        return GLES20.GL_UNSIGNED_SHORT_5_6_5;
      case PIXEL_COMPONENT_HALF_FLOAT:
        return GL30.GL_HALF_FLOAT;
      case PIXEL_PACKED_UNSIGNED_INT_24_8:
        return GL30.GL_UNSIGNED_INT_24_8;
    }

    throw new UnreachableCodeException();
  }

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


Question: Display warning message via stderr or GUI.

def warning(*args):
    """"""
    if sys.stdin.isatty():
        print('WARNING:', *args, file=sys.stderr)
    else:
        notify_warning(*args)

protected function err($msg, $url = null)
    {
        $this->saveDataInSession();
        return $this->msg($msg, self::MSG_BAD, $url);
    }

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


Question: // AndWhere concatenates a new WHERE condition with the existing one (if any) using "AND".

func (s *SelectQuery) AndWhere(e Expression) *SelectQuery {
	s.where = And(s.where, e)
	return s
}

private function getBaseSelect($storeId, $type)
    {
        $connection = $this->getConnection();
        $select     = $connection->select();

        $select->from(['thesaurus' => $this->getMainTable()], [])
            ->join(
                ['terms' => $this->getTable(ThesaurusInterface::EXPANSION_TABLE_NAME)],
                'thesaurus.thesaurus_id = terms.thesaurus_id',
                []
            )
            ->join(
                ['store' => $this->getTable(ThesaurusInterface::STORE_TABLE_NAME)],
                'store.thesaurus_id = thesaurus.thesaurus_id',
                []
            )
            ->group(['thesaurus.thesaurus_id', 'terms.term_id'])
            ->where("thesaurus.type = ?", $type)
            ->where('thesaurus.is_active = 1')
            ->where('store.store_id IN (?)', [0, $storeId]);

        return $select;
    }

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


Question:
A target specified by a query.

Generated from protobuf field <code>.google.firestore.v1.Target.QueryTarget query = 2;</code>
@param \Google\Cloud\Firestore\V1\Target\QueryTarget $var
@return $this

public function setQuery($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Firestore\V1\Target_QueryTarget::class);
        $this->writeOneof(2, $var);

        return $this;
    }

public void marshall(CreateBackupVaultRequest createBackupVaultRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(createBackupVaultRequest.getBackupVaultName(), BACKUPVAULTNAME_BINDING);
            protocolMarshaller.marshall(createBackupVaultRequest.getBackupVaultTags(), BACKUPVAULTTAGS_BINDING);
            protocolMarshaller.marshall(createBackupVaultRequest.getEncryptionKeyArn(), ENCRYPTIONKEYARN_BINDING);
            protocolMarshaller.marshall(createBackupVaultRequest.getCreatorRequestId(), CREATORREQUESTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Delete a compiled for all environment
@throws Server500
@throws \Exception

private function deleteAllCompiled()
    {
        $env = array("dev", "prod");
        Output::displayAsSuccess("Hey, I delete compiled for all environment", "none");
        for ($i = 0; $i < count($env); $i++) {
            $this->callDelCreaServer($env[$i]);
        }
        if (in_array("--noexit", $this->options["options"])) {
            Output::displayAsEndSuccess("Compiled was deleted for all environment.", "none");
        } else {
            Output::displayAsNormal("Compiled was deleted for all environment.");
        }
    }

func (v VirtualMachine) RemoveSnapshot(ctx context.Context, name string, removeChildren bool, consolidate *bool) (*Task, error) {
	snapshot, err := v.FindSnapshot(ctx, name)
	if err != nil {
		return nil, err
	}

	req := types.RemoveSnapshot_Task{
		This:           snapshot.Reference(),
		RemoveChildren: removeChildren,
		Consolidate:    consolidate,
	}

	res, err := methods.RemoveSnapshot_Task(ctx, v.c, &req)
	if err != nil {
		return nil, err
	}

	return NewTask(v.c, res.Returnval), nil
}

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


Question:
// FromStdWithNext receives a standar handler - middleware form - and returns a
// compatible context.Handler wrapper.

func FromStdWithNext(h func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)) context.Handler {
	return func(ctx context.Context) {
		next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx.Next()
		})

		h(ctx.ResponseWriter(), ctx.Request(), next)
	}
}

protected function processMime($mime)
    {
        $vendor             = $this->getContainer()->get(Application::CONTAINER_ID_VENDOR);
        $apiVersion         = $this->getContainer()->get(Application::CONTAINER_ID_API_VERSION);
        $apiVersionRegExp   = Application::API_VERSION_REG_EXP;
        $format             = null;

        if (preg_match(
            '#application/vnd\.' . $vendor . '-v' . $apiVersionRegExp . '\+(xml|json)#',
            $mime,
            $matches
        )) {
            list($mime, $apiVersion, $format) = $matches;
        } elseif (preg_match(
            '#application/vnd\.' . $vendor . '\+(xml|json).*?version=' . $apiVersionRegExp . '#',
            $mime,
            $matches
        )) {
            list($mime, $format, $apiVersion) = $matches;
        } elseif ('application/json' === $mime) {
            $format = 'json';
            $mime   = 'application/vnd.' . $vendor . '-v' . $apiVersion . '+json';
        } elseif ('application/xml' === $mime) {
            $format = 'xml';
            $mime   = 'application/vnd.' . $vendor . '-v' . $apiVersion . '+xml';
        }

        return new MimeProcessResult($mime, $vendor, $apiVersion, $format);
    }

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


Question:
This method creates the Deployment structure with all it's BDAs.

@param application
@param extensionArchives
@return
@throws CDIException

private WebSphereCDIDeployment createWebSphereCDIDeployment(Application application,
                                                                Set<ExtensionArchive> extensionArchives) throws CDIException {
        WebSphereCDIDeployment webSphereCDIDeployment = new WebSphereCDIDeploymentImpl(application, cdiRuntime);

        DiscoveredBdas discoveredBdas = new DiscoveredBdas(webSphereCDIDeployment);

        if (application.hasModules()) {

            Collection<CDIArchive> libraryArchives = application.getLibraryArchives();
            Collection<CDIArchive> moduleArchives = application.getModuleArchives();

            ClassLoader applicationClassLoader = application.getClassLoader();
            webSphereCDIDeployment.setClassLoader(applicationClassLoader);

            processLibraries(webSphereCDIDeployment,
                             discoveredBdas,
                             libraryArchives);

            processModules(webSphereCDIDeployment,
                           discoveredBdas,
                           moduleArchives);

            //discoveredBdas has the full map, let's go through them all to make sure the wire is complete
            discoveredBdas.makeCrossBoundaryWiring();

            //and finally the runtime extensions
            addRuntimeExtensions(webSphereCDIDeployment,
                                 discoveredBdas);
        }

        return webSphereCDIDeployment;
    }

protected function init_dependency_type( $type ) {
		$array = [ ];
		$data  = $this->getConfigKey( $type );
		foreach ( $data as $dependency ) {
			$handle           = array_key_exists( 'handle',
				$dependency ) ? $dependency['handle'] : '';
			$array[ $handle ] = $dependency;
		}
		return $array;
	}

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


Question:
Get new vector clock based on this clock but incremented on index nodeId

@param nodeId The id of the node to increment
@return A vector clock equal on each element execept that indexed by
nodeId

public VectorClock incremented(int nodeId, long time) {
        VectorClock copyClock = this.clone();
        copyClock.incrementVersion(nodeId, time);
        return copyClock;
    }

public function fetch(ElementVersion $elementVersion, $language, TreeNodeInterface $node = null)
    {
        /* @var $links ElementLink[] */
        $links = $this->linkManager->findBy(['elementVersion' => $elementVersion, 'language' => $language]);

        if ($node) {
            foreach ($this->linkManager->findBy(['type' => 'link-internal', 'language' => $language, 'target' => $node->getId()]) as $link) {
                $incomingLink = clone $link;
                $incomingLink->setType('link-incoming');
                $links[] = $incomingLink;
            }
        }

        $results = array();

        foreach ($links as $link) {
            $data = [
                'id' => $link->getId(),
                'iconCls' => 'p-element-component-icon',
                'language' => $link->getLanguage(),
                'type' => $link->getType(),
                'title' => $link->getField(),
                'content' => $link->getTarget(),
                'link' => [],
                'raw' => $link->getTarget(),
                'payload' => [],
            ];

            $results[] = $this->linkTransformer->transform($link, $data);
        }

        return $results;
    }

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


Question:
::: PRIVATE FUNCTIONS /*
Traverses the root node to locate links that match filters.

function findLinks(rootNode, callback)
{
	var attrName,i,link,linkAttrs,numAttrs,url;

	walk(rootNode, function(node)
	{
		linkAttrs = maxFilterLevel[node.nodeName];

		// If a supported element
		if (linkAttrs != null)
		{
			numAttrs = node.attrs.length;

			// Faster to loop through Arrays than Objects
			for (i=0; i<numAttrs; i++)
			{
				attrName = node.attrs[i].name;
				url = null;

				// If a supported attribute
				if (linkAttrs[attrName] === true)
				{
					// Special case for `<meta http-equiv="refresh" content="5; url=redirect.html">`
					if (node.nodeName==="meta" && attrName==="content")
					{
						if (node.attrMap["http-equiv"]!=null && node.attrMap["http-equiv"].toLowerCase()==="refresh")
						{
							url = parseMetaRefresh( node.attrMap[attrName] ).url;
						}
					}
					else
					{
						// https://html.spec.whatwg.org/multipage/infrastructure.html#valid-url-potentially-surrounded-by-spaces
						url = node.attrMap[attrName].trim();
					}

					if (url != null)
					{
						callback(node, attrName, url);
					}
				}
			}
		}
	});
}

def _pruned(self, path):
    """"""
    if path[0] == '/':
      path = path[1:]
    for rule in reversed(self.pruneRules):
      if isinstance(rule, six.string_types):
        if fnmatch(path, rule):
          return True
      elif rule(path):
        return True
    return False

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


Question:
Convert the localization object into a function in case we need to support nested keys.

@param {Object} localization the language object,
@param {Boolean} nested

@returns {Function}

function makeLocalizeFunction(localization, nested) {
  return function localizeFunction(key) {
    return nested ? byString(localization, key) : localization[key];
  };
}

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: Marshall the given parameter object.

public void marshall(ThingAttribute thingAttribute, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(thingAttribute.getThingName(), THINGNAME_BINDING);
            protocolMarshaller.marshall(thingAttribute.getThingTypeName(), THINGTYPENAME_BINDING);
            protocolMarshaller.marshall(thingAttribute.getThingArn(), THINGARN_BINDING);
            protocolMarshaller.marshall(thingAttribute.getAttributes(), ATTRIBUTES_BINDING);
            protocolMarshaller.marshall(thingAttribute.getVersion(), VERSION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
/*
Compute default Serializable fields from all members of ClassSymbol.

Since the fields of ClassDocImpl might not contain private or
package accessible fields, must walk over all members of ClassSymbol.

private void computeDefaultSerializableFields(DocEnv env,
                                                  ClassSymbol def,
                                                  ClassDocImpl cd) {
        for (Scope.Entry e = def.members().elems; e != null; e = e.sibling) {
            if (e.sym != null && e.sym.kind == Kinds.VAR) {
                VarSymbol f = (VarSymbol)e.sym;
                if ((f.flags() & Flags.STATIC) == 0 &&
                    (f.flags() & Flags.TRANSIENT) == 0) {
                    //### No modifier filtering applied here.
                    FieldDocImpl fd = env.getFieldDoc(f);
                    //### Add to beginning.
                    //### Preserve order used by old 'javadoc'.
                    fields.prepend(fd);
                }
            }
        }
    }

public void detail(MethodNode methodNode, MethodAttributes attrs, StringBuilder output) {
        Validate.notNull(methodNode);
        Validate.notNull(attrs);
        Validate.notNull(output);

        int methodId = attrs.getSignature().getMethodId();

        output.append("Class Name: ").append(attrs.getSignature().getClassName().replace('/', '.')).append('\n');
        output.append("Method Name: ").append(attrs.getSignature().getMethodName()).append('\n');
        output.append("Method Params: ").append(attrs.getSignature().getMethodDescriptor()).append('\n');
        output.append("Method Return: ").append(attrs.getSignature().getReturnType()).append('\n');
        output.append("Method ID: ").append(methodId).append('\n');
        output.append("------------------------------------\n");

        UnmodifiableList<ContinuationPoint> cps = attrs.getContinuationPoints();
        for (int i = 0; i < cps.size(); i++) {
            ContinuationPoint cp = cps.get(i);

            int line = cp.getLineNumber() == null ? -1 : cp.getLineNumber();
            String header = String.format("Continuation Point ID: %-4d Line: %-4d Type: %s",
                    i,
                    line,
                    cp.getClass().getSimpleName());
            output.append(header).append('\n');

            // Check out PackStateGenerators class for how things are organized. Brief overview follows...
            // container[0] has local variables that are bytes/shorts/ints
            // container[1] has local variables that are floats
            // container[2] has local variables that are longs
            // container[3] has local variables that are doubles
            // container[4] has local variables that are Objects
            // container[5] has operands that are bytes/shorts/ints
            // container[6] has operands that are floats
            // container[7] has operands that are longs
            // container[8] has operands that are doubles
            // container[9] has operands that are Objects
            detailLocals(cp, methodNode, output);
            detailOperands(cp, output);

            output.append('\n');
        }

        output.append('\n');
    }

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


Question:
Starts listening to the socket

        :return: True if the socket has been created

def start(self):

        # Create the multicast socket (update the group)
        self._socket, self._group = create_multicast_socket(self._group,
                                                            self._port)

        # Start the listening thread
        self._stop_event.clear()
        self._thread = threading.Thread(
            target=self.__read,
            name="MulticastReceiver-{0}".format(self._port))
        self._thread.start()

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

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


Question: see if cookiename is a jwtsso cookie based on the name.

protected boolean isJwtCookie(String baseName, String cookieName) {
        if (baseName.equalsIgnoreCase(cookieName))
            return true;
        if (!(cookieName.startsWith(baseName))) {
            return false;
        }
        if (cookieName.length() != baseName.length() + 2) {
            return false;
        }
        String lastTwoChars = cookieName.substring(baseName.length());
        return lastTwoChars.matches("\\d\\d");
    }

function isExactDomainMatch(part: string, debuggeeHost: string): boolean {
  return part.startsWith("www.")
    ? part.substr("www.".length) === debuggeeHost
    : part === debuggeeHost;
}

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


Question: Start api initialization.

async def start(self):
        """"""
        _LOGGER.debug('Initializing pyEight Version: %s', __version__)
        await self.fetch_token()
        if self._token is not None:
            await self.fetch_device_list()
            await self.assign_users()
            return True
        else:
            # We couldn't authenticate
            return False

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

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


Question:
Register the service provider for Orchestra Platform asset publisher.

@return void

protected function registerAssetPublisher()
    {
        $this->app->singleton('orchestra.publisher.asset', function (Application $app) {
            return new AssetManager($app, $app->make('asset.publisher'));
        });
    }

public function initialize(Server $server)
    {
        $this->server = $server;
        $server->on('method:GET', [$this, 'httpGet'], 90);
        $server->on('propFind', [$this, 'propFind']);

        $server->xml->namespaceMap[self::NS_CALENDARSERVER] = 'cs';
        $server->resourceTypeMapping['\\Sabre\\CalDAV\\Notifications\\ICollection'] = '{'.self::NS_CALENDARSERVER.'}notification';

        array_push($server->protectedProperties,
            '{'.self::NS_CALENDARSERVER.'}notification-URL',
            '{'.self::NS_CALENDARSERVER.'}notificationtype'
        );
    }

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


Question:
Prepare the curl request

@param string $apiCall the API call function
@param array $payload Parameters
@return array

public function request($method, $apiCall, $payload = [])
    {
        $url = rtrim($this->baseUrl . $apiCall, '/?');
        $curl = $this->prepareCurl();
        $browser = new Browser($curl);
        $headers = [
            "Authorization" => "Bearer ".$this->token,
            "Content-type"  => "application/json"
        ];
        $response = $browser->call($url, $method, $headers, json_encode($payload));

        return $response->getContent();
    }

private function buildAuthorizationHeader($signatureParameters) {
        $authorizationHeader = 'OAuth realm=""';

        foreach ($signatureParameters as $key=>$value) {
            $authorizationHeader.=','.$key."=".'"'.urlencode($value).'"';
        }
        return $authorizationHeader;
    }

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


Question:
Public: Reboot a virtual machine

 id       - ID of the virtual machine
 recovery - Set to true to reboot in recovery, defaults to false

 Returns a Hash.

def reboot(id, recovery=false)
      response = request(:post, "/virtual_machines/#{id}/reboot.json", { query: recovery ? { mode: :recovery } : nil })
      response['virtual_machine']
    end

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question:
See if the file is empty, if it exists, or if it's readable.
@param $file
@return bool

protected function isValidFile($file): bool
    {
        // If there's no file we can't do anything with it...
        if (empty($file)) {
            return false;
        }

        // If the file doesn't exist, no need to try and get it.
        if (!file_exists($file)) {
            // We should probably log here...
            return false;
        }

        // If we can't read the file... Why try...
        if (!is_readable($file)) {
            // We should probably log or something here...
            return false;
        }

        return true;
    }

def isempty(path):

    if op.isdir(path):
        return [] == os.listdir(path)
    elif op.isfile(path):
        return 0 == os.stat(path).st_size
    return None

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


Question:
This is a special method - If the db doesn't allow multiple keys indexes,
see if this field is a first field on an index (non-primary).
@return true if true.

public boolean checkIndexField(BaseField field)
    {
        for (int iKeySeq = 0; iKeySeq < this.getRecord().getKeyAreaCount(); iKeySeq++)
        {
            KeyArea keyArea = this.getRecord().getKeyArea(iKeySeq);
            if (keyArea.getField(0) == field)
                if (field != this.getRecord().getCounterField())
                    return true;
        }
        return false;
    }

protected boolean shouldBindCollectionWithForeignKey(ToMany property) {
        return ((property instanceof org.grails.datastore.mapping.model.types.OneToMany) && property.isBidirectional() ||
                !shouldCollectionBindWithJoinColumn(property)) &&
                !Map.class.isAssignableFrom(property.getType()) &&
                !(property instanceof ManyToMany) &&
                !(property instanceof Basic);
    }

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


Question:
// DwarfEndian determines the endianness of the DWARF by using the version number field in the debug_info section
// Trick borrowed from "debug/dwarf".New()

func DwarfEndian(infoSec []byte) binary.ByteOrder {
	if len(infoSec) < 6 {
		return binary.BigEndian
	}
	x, y := infoSec[4], infoSec[5]
	switch {
	case x == 0 && y == 0:
		return binary.BigEndian
	case x == 0:
		return binary.BigEndian
	case y == 0:
		return binary.LittleEndian
	default:
		return binary.BigEndian
	}
}

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question:
logout the user from its social network

@param string $site
@return boolean

public static function disconnectSocialProfile($site = 'facebook')
    {
        $config = \Phalcon\DI::getDefault()->getConfig()->social_config->toArray(); //dirname(dirname(dirname(__FILE__ ))) . "/config/social_config.php";
        $hybridauth = new \Hybridauth\Hybridauth($config);
        return $hybridauth->logoutAllProviders();
        //$adapter = $hybridauth->authenticate( "Google" );
        $adapter = $hybridauth->authenticate($site);

        // request user profile
        return $adapter->logout();
    }

def after_sign_out_path_for(resource_or_scope)

    if ::Milia.signout_to_root
      root_path        # return to index page
    else
        # or return to sign-in page
     scope = Devise::Mapping.find_scope!(resource_or_scope)
     send(:"new_#{scope}_session_path")
    end

  end

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


Question: Collect data into fixed-length chunks or blocks.

def _groups_of_size(iterable, n, fillvalue=None):
    """"""
    # _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)

@Override
	public final int[] selectChannels(SerializationDelegate<T> record, int numberOfChannels) {
		switch (strategy) {
		case FORWARD:
		case PARTITION_RANDOM:
			return robin(numberOfChannels);
		case PARTITION_HASH:
		case PARTITION_LOCAL_HASH:
			return hashPartitionDefault(record.getInstance(), numberOfChannels);
		case PARTITION_RANGE:
			return rangePartition(record.getInstance(), numberOfChannels);
		case BROADCAST:
			return broadcast(numberOfChannels);
		default:
			throw new UnsupportedOperationException("Unsupported distribution strategy: " + strategy.name());
		}
	}

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


Question:
Init method.

@return void

protected function init() {
        $this->data['crud'] = 'd';
        $this->data['edulevel'] = self::LEVEL_OTHER;
        $this->data['objecttable'] = template::TABLE;;
    }

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question:
// intersectsFace reports whether a given directed line L intersects the cube face F.
// The line L is defined by its normal N in the (u,v,w) coordinates of F.

func (p pointUVW) intersectsFace() bool {
	// L intersects the [-1,1]x[-1,1] square in (u,v) if and only if the dot
	// products of N with the four corner vertices (-1,-1,1), (1,-1,1), (1,1,1),
	// and (-1,1,1) do not all have the same sign. This is true exactly when
	// |Nu| + |Nv| >= |Nw|. The code below evaluates this expression exactly.
	u := math.Abs(p.X)
	v := math.Abs(p.Y)
	w := math.Abs(p.Z)

	// We only need to consider the cases where u or v is the smallest value,
	// since if w is the smallest then both expressions below will have a
	// positive LHS and a negative RHS.
	return (v >= w-u) && (u >= w-v)
}

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

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

        return $hints;
    }

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


Question: // GetHeader returns the request header's value based on its name.

func (ctx *context) GetHeader(name string) string {
	return ctx.request.Header.Get(name)
}

public static function UrlExsist ($url, $timeout = 30, $protocol_version = self::VERSION_1_1) {
		$result = static::HeadRequest($url, $timeout, $protocol_version);
		return isset($result['http']['status']['code']) && $result['http']['status']['code'] !== '404';
	}

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


Question:
Gather all require and define calls from unbundled JavaScript source
    files and yield all module names.  The imports can either be of the
    CommonJS or AMD syntax.

def yield_module_imports(root, checks=string_imports()):

    if not isinstance(root, asttypes.Node):
        raise TypeError('provided root must be a node')

    for child in yield_function(root, deep_filter):
        for f, condition in checks:
            if condition(child):
                for name in f(child):
                    yield name
                continue

function getInitialModel(routeInfo, page) {
    var initModelDeps = {
        appName:    routeInfo.appName,
        tokens:     routeInfo.tokens,
        routeInfo:  routeInfo,
        defaults:   page.defaults,
        activeUser: routeInfo.activeUser || {},
        currentScope: {}
    };

    // if no model, just return empty object
    if (!page.model) {
        return Q.when({});
    }
    // if function, inject and the returned value is the model
    else if (_.isFunction(page.model)) {
        return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps }));
    }
    else {
        throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model);
    }
}

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


Question:
Prepare string to apply it inside SQL query

@return string

protected function prepareOrderBy(): string
    {
        if (empty($this->orderBy)) {
            return '';
        }
        $orders = [];
        foreach ($this->orderBy as $column => $order) {
            $orders[] = $column . ' ' . $order;
        }
        return ' ORDER BY ' . implode(', ', $orders);
    }

private function connect($selectDb = true)
    {
        if (!$this->isPhpEnvironmentSupported()) {
            throw new ConnectionException("Function pg_connect doesn't exist");
        }

        //Can throw warning, if have incorrect connection params
        //So we need '@'
        $this
            ->getLogger()
            ->startConnection('Pgsql connection');
        $connectString  = $this->generateConnectionString($selectDb);
        $this->resource = @\pg_connect($connectString);
        $this
            ->getLogger()
            ->stopConnection();

        if (!$this->resource) {
            $error = \error_get_last();
            throw new ConnectionException('Error ' . $error['message']);
        }
    }

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


Question:
Everything below IE9 doesn't know how to treat HTML5 tags

@param {Object} context The document object on which to check HTML5 support

@example
wysihtml5.browser.supportsHTML5Tags(document);

function(context) {
      var element = context.createElement("div"),
          html5   = "
foo
";
      element.innerHTML = html5;
      return element.innerHTML.toLowerCase() === html5;
    }

@Override
    public boolean isEnabled(String name, Locale locale) {

        CmsXmlHtmlValue value = (CmsXmlHtmlValue)getValue(name, locale);

        if (value != null) {
            Element element = value.getElement();
            Attribute enabled = element.attribute(ATTRIBUTE_ENABLED);
            return ((enabled == null) || Boolean.valueOf(enabled.getValue()).booleanValue());
        }

        return false;
    }

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


Question:
Get the dict with the basic fields used to describe a metrics: id, name and desc
        :return: a dict with the definition

def get_definition(self):

        def_ = {
            "id": self.id,
            "name": self.name,
            "desc": self.desc
        }
        return def_

def jsonFormat(output, statDict = None, query = None, pretty = False):
  """"""
  statDict = statDict or scales.getStats()
  if query:
    statDict = runQuery(statDict, query)
  indent = 2 if pretty else None
  # At first, assume that strings are in UTF-8. If this fails -- if, for example, we have
  # crazy binary data -- then in order to get *something* out, we assume ISO-8859-1,
  # which maps each byte to a unicode code point.
  try:
    serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent)
  except UnicodeDecodeError:
    serialized = json.dumps(statDict, cls=scales.StatContainerEncoder, indent=indent, encoding='iso-8859-1')

  output.write(serialized)
  output.write('\n')

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


Question:
Adds the tags information.

@param doc the doc for which the tags will be generated
@param htmltree the documentation tree to which the tags will be added

protected void addTagsInfo(Doc doc, Content htmltree) {
        if (configuration.nocomment) {
            return;
        }
        Content dl = new HtmlTree(HtmlTag.DL);
        if (doc instanceof MethodDoc) {
            addMethodInfo((MethodDoc) doc, dl);
        }
        Content output = new ContentBuilder();
        TagletWriter.genTagOuput(configuration.tagletManager, doc,
            configuration.tagletManager.getCustomTaglets(doc),
                getTagletWriterInstance(false), output);
        dl.addContent(output);
        htmltree.addContent(dl);
    }

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

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


Question: Reconstructs URL and points browser to the requested node path.

public void loadNodeSpecifiedByURL() {
        repositoriesList.select(jcrURL.getRepository(), jcrURL.getWorkspace(), jcrURL.getPath(), true);
    }

public function handleRequest($parent, $upstream)
    {
        $req = $this->beginRequest($parent, $upstream);
        return $req ?: $parent;
    }

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


Question:
Adds Columns to the specified table.

@param Table $table The Table model class to add columns to.

protected function addColumns(Table $table)
    {
        $stmt = $this->dbh->query(sprintf('SHOW COLUMNS FROM %s', $this->getPlatform()->doQuoting($table->getName())));

        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $column = $this->getColumnFromRow($row, $table);
            $table->addColumn($column);
        }
    }

private void appendNullCriteria(TableAlias alias, PathInfo pathInfo, NullCriteria c, StringBuffer buf)
    {
        appendColName(alias, pathInfo, c.isTranslateAttribute(), buf);
        buf.append(c.getClause());
    }

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


Question:
Creates the CampaignChain app configuration files based on the default
files or overwrites existing ones with the default.

public static function initKernel()
    {
        $configFiles = self::getConfigFiles();

        $fs = new Filesystem();

        if(!$fs->exists($configFiles['bundles'])){
            $fs->copy($configFiles['bundles_dist'], $configFiles['bundles'], true);
        }
        if(!$fs->exists($configFiles['config'])){
            $fs->copy($configFiles['config_dist'], $configFiles['config'], true);
        }
        if(!$fs->exists($configFiles['routing'])){
            $fs->copy($configFiles['routing_dist'], $configFiles['routing'], true);
        }
        if(!$fs->exists($configFiles['security'])){
            $fs->copy($configFiles['security_dist'], $configFiles['security'], true);
        }
    }

def get_conf_path_from_env():
    '''

    '''
    config_path = os.environ.get('PECAN_CONFIG')
    if not config_path:
        error = "PECAN_CONFIG is not set and " \
                "no config file was passed as an argument."
    elif not os.path.isfile(config_path):
        error = "PECAN_CONFIG was set to an invalid path: %s" % config_path
    else:
        return config_path

    raise RuntimeError(error)

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


Question:
Truncates the trace by howTruncateTrace options

@param mixed $thrower

private function truncateTrace($thrower): void
    {
        /** @noinspection PhpUndefinedFieldInspection */
        /** @noinspection PhpUndefinedMethodInspection */
        $this->truncatedTrace = new ExceptionTrace($this->getTrace(), $this->file, $this->line);
        $options = $this->createOptionsForTruncateTrace($thrower);
        if (!$options) {
            return;
        }
        $this->truncatedTrace->truncate($options);
        /** @noinspection PhpUndefinedFieldInspection */
        $this->file = $this->truncatedTrace->file;
        /** @noinspection PhpUndefinedFieldInspection */
        $this->line = $this->truncatedTrace->line;
    }

def delete_ptr_records(self, device, ip_address=None):

        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        if ip_address:
            uri = "%s&ip=%s" % (uri, ip_address)
        resp, resp_body = self._async_call(uri, method="DELETE",
                has_response=False,
                error_class=exc.PTRRecordDeletionFailed)
        return resp_body.get("status") == "COMPLETED"

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


Question: Special HTML encoding check.

def header_check(self, content):
        """"""

        encode = None

        # Look for meta charset
        m = RE_HTML_ENCODE.search(content)
        if m:
            enc = m.group(1).decode('ascii')

            try:
                codecs.getencoder(enc)
                encode = enc
            except LookupError:
                pass
        else:
            encode = self._has_xml_encode(content)
        return encode

def pattern(self, pattern):

        enc_pattern = _converters[type(pattern)](pattern)
        if (enc_pattern, True) not in self._refs:
            ch = _Sender(self, enc_pattern,
                         is_pattern=True)
            self._refs[(enc_pattern, True)] = ch
        return self._refs[(enc_pattern, True)]

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


Question:
返回数组中指定元素所在位置，未找到返回{@link #INDEX_NOT_FOUND}

@param array 数组
@param value 被检查的元素
@return 数组中指定元素所在位置，未找到返回{@link #INDEX_NOT_FOUND}
@since 3.0.7

public static int indexOf(short[] array, short value) {
		if (null != array) {
			for (int i = 0; i < array.length; i++) {
				if (value == array[i]) {
					return i;
				}
			}
		}
		return INDEX_NOT_FOUND;
	}

public function getList(array $options = array())
    {
        $result = null;
        $this->hook->attach('sku.list.before', $options, $result, $this);

        if (isset($result)) {
            return $result;
        }

        $sql = 'SELECT ps.*, p.title, p.currency';

        if (!empty($options['count'])) {
            $sql = 'SELECT COUNT(ps.product_sku_id)';
        }

        $sql .= ' FROM product_sku ps LEFT JOIN product p ON(ps.product_id = p.product_id)';

        $conditions = array();

        if (isset($options['product_sku_id'])) {
            $sql .= ' WHERE ps.product_sku_id = ?';
            $conditions[] = $options['product_sku_id'];
        } else {
            $sql .= ' WHERE ps.product_sku_id IS NOT NULL';
        }

        if (isset($options['sku'])) {
            $sql .= ' AND ps.sku=?';
            $conditions[] = $options['sku'];
        }

        if (isset($options['store_id'])) {
            $sql .= ' AND p.store_id=?';
            $conditions[] = $options['store_id'];
        }

        if (isset($options['title_sku'])) {
            $sql .= ' AND (p.title LIKE ? OR ps.sku LIKE ?)';
            $conditions[] = "%{$options['title_sku']}%";
            $conditions[] = "%{$options['title_sku']}%";
        }

        if (isset($options['product_id'])) {
            $sql .= ' AND ps.product_id=?';
            $conditions[] = $options['product_id'];
        }

        if (isset($options['combination_id'])) {
            $sql .= ' AND ps.combination_id=?';
            $conditions[] = $options['combination_id'];
        }

        if (isset($options['status'])) {
            $sql .= ' AND ps.status=?';
            $conditions[] = (int) $options['status'];
        }

        $sql .= " ORDER BY ps.sku ASC";

        if (!empty($options['limit'])) {
            $sql .= ' LIMIT ' . implode(',', array_map('intval', $options['limit']));
        }

        if (empty($options['count'])) {
            $list = $this->db->fetchAll($sql, $conditions, array('index' => 'product_sku_id'));
            $result = $this->prepareList($list);
        } else {
            $result = (int) $this->db->fetchColumn($sql, $conditions);
        }

        $this->hook->attach('sku.list.after', $options, $result, $this);
        return $result;
    }

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