Question:
// cadvisorInfoToContainerStats returns the statsapi.ContainerStats converted
// from the container and filesystem info.

func cadvisorInfoToContainerStats(name string, info *cadvisorapiv2.ContainerInfo, rootFs, imageFs *cadvisorapiv2.FsInfo) *statsapi.ContainerStats {
	result := &statsapi.ContainerStats{
		StartTime: metav1.NewTime(info.Spec.CreationTime),
		Name:      name,
	}
	cstat, found := latestContainerStats(info)
	if !found {
		return result
	}

	cpu, memory := cadvisorInfoToCPUandMemoryStats(info)
	result.CPU = cpu
	result.Memory = memory

	if rootFs != nil {
		// The container logs live on the node rootfs device
		result.Logs = buildLogsStats(cstat, rootFs)
	}

	if imageFs != nil {
		// The container rootFs lives on the imageFs devices (which may not be the node root fs)
		result.Rootfs = buildRootfsStats(cstat, imageFs)
	}

	cfs := cstat.Filesystem
	if cfs != nil {
		if cfs.BaseUsageBytes != nil {
			if result.Rootfs != nil {
				rootfsUsage := *cfs.BaseUsageBytes
				result.Rootfs.UsedBytes = &rootfsUsage
			}
			if cfs.TotalUsageBytes != nil && result.Logs != nil {
				logsUsage := *cfs.TotalUsageBytes - *cfs.BaseUsageBytes
				result.Logs.UsedBytes = &logsUsage
			}
		}
		if cfs.InodeUsage != nil && result.Rootfs != nil {
			rootInodes := *cfs.InodeUsage
			result.Rootfs.InodesUsed = &rootInodes
		}
	}

	for _, acc := range cstat.Accelerators {
		result.Accelerators = append(result.Accelerators, statsapi.AcceleratorStats{
			Make:        acc.Make,
			Model:       acc.Model,
			ID:          acc.ID,
			MemoryTotal: acc.MemoryTotal,
			MemoryUsed:  acc.MemoryUsed,
			DutyCycle:   acc.DutyCycle,
		})
	}

	result.UserDefinedMetrics = cadvisorInfoToUserDefinedMetrics(info)

	return result
}

public static void printMountInfo(Map<String, MountPointInfo> mountTable) {
    for (Map.Entry<String, MountPointInfo> entry : mountTable.entrySet()) {
      String mMountPoint = entry.getKey();
      MountPointInfo mountPointInfo = entry.getValue();

      long capacityBytes = mountPointInfo.getUfsCapacityBytes();
      long usedBytes = mountPointInfo.getUfsUsedBytes();

      String usedPercentageInfo = "";
      if (capacityBytes > 0) {
        int usedPercentage = (int) (100L * usedBytes / capacityBytes);
        usedPercentageInfo = String.format("(%s%%)", usedPercentage);
      }

      String leftAlignFormat = getAlignFormat(mountTable);

      System.out.format(leftAlignFormat, mountPointInfo.getUfsUri(), mMountPoint,
          mountPointInfo.getUfsType(), FormatUtils.getSizeFromBytes(capacityBytes),
          FormatUtils.getSizeFromBytes(usedBytes) + usedPercentageInfo,
          mountPointInfo.getReadOnly() ? "" : "not ",
          mountPointInfo.getShared() ? "" : "not ");
      System.out.println("properties=" + mountPointInfo.getProperties() + ")");
    }
  }

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


Question:
Read longest possible sequence of special characters and convert
to token.

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

private static String decode(final CharSequence txt) {
        try {
            return URLDecoder.decode(
                txt.toString(), Charset.defaultCharset().name()
            );
        } catch (final UnsupportedEncodingException ex) {
            throw new IllegalStateException(ex);
        }
    }

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


Question:
Print Facebook Open Graph tags.

@param array $ogData The Open Graph information
@return string The HTML

public function facebookOgData(array $ogData = array()) {
        $html = '';
        $metaTemplate = '<meta property="%s" content="%s">';
        $ini = Zend_Registry::get('config');

        if (!array_key_exists('admins', $ogData)) {
            if ($ini->auth->adapters->facebook->admins) {
                $ogData['admins'] = $ini->auth->adapters->facebook->admins;
            } else {
                throw new Exception(
                    'The auth.adapters.facebook.admins configuration parameter is missing. ' .
                    'Please use a numeric id, not a username.'
                );
            }
        }

        if (!array_key_exists('app_id', $ogData)) {
            if ($ini->auth->adapters->facebook->appId) {
                $ogData['app_id'] = $ini->auth->adapters->facebook->appId;
            }
        }

        // Set some defaults
        if (empty($ogData['url']) && isset($_SERVER['REQUEST_URI'])) {
            $ogData['url'] = $this->view->fullUrl($_SERVER['REQUEST_URI']);
        }
        if (empty($ogData['type'])) {
            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] == '/') {
                $ogData['type'] = 'website';
            } else {
                $ogData['type'] = 'article';
            }
        }
        if (empty($ogData['title'])) {
            if ($this->view->title) {
                $title = $this->view->title;
            } else if (!empty($this->view->config()->app->name)) {
                $title = $this->view->config()->app->name;
            }

            if ($title) {
                $ogData['title'] = $title;
            }
        }

        if (empty($ogData['image']) && !empty($this->view->config()->app->image)) {
            if (basename($this->view->config()->app->image) === $this->view->config()->app->image) {
                $ogData['image'] = $this->view->image()->getUrl($this->view->config()->app->image);
            } else {
                $ogData['image'] = $this->view->fullUrl($this->view->config()->app->image);
            }
        }
        if (empty($ogData['description'])) {
            if ($this->view->description) {
                $ogData['description'] = __($this->view->description);
            } elseif (!empty($this->view->config()->app->description)) {
                $ogData['description'] = __($this->view->config()->app->description);
            }
        }
        if (empty($ogData['locale']) && !empty($this->view->config()->app->locale)) {
            $ogData['locale'] = $this->view->config()->app->locale;
        }

        if (!empty($this->view->config()->app->name)) {
            $ogData['site_name'] = $this->view->config()->app->name;
        }

        foreach ($ogData as $ogKey => $ogValue) {
            $prefix = in_array($ogKey, array('admins', 'app_id')) ? 'fb' : 'og';
            $metaHtml = sprintf(
                $metaTemplate,
                $this->view->escape($prefix . ':' . $ogKey),
                $this->view->escape($ogValue)
            );
            $html .= "$metaHtml\n";
        }
        return $html;
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('BulkOperationResponse');
        $visitor->setHeader('Content-Type', $generator->getMediaType('BulkOperationResponse'));
        $visitor->setStatus(Response::HTTP_OK);

        $generator->startHashElement('operations');

        foreach ($data->operations as $operationId => $operation) {
            $generator->startObjectElement($operationId, 'OperationResponse');

            $generator->startValueElement('statusCode', $operation->statusCode);
            $generator->endValueElement('statusCode');

            $generator->startHashElement('headers');

            foreach ($operation->headers as $name => $header) {
                $generator->startValueElement($name, $header[0]);
                $generator->endValueElement($name);
            }
            $generator->endHashElement('headers');

            $generator->startValueElement('content', $operation->content);
            $generator->endValueElement('content');

            $generator->endObjectElement($operationId);
        }
        $generator->endHashElement('operations');
        $generator->endObjectElement('BulkOperationResponse');
    }

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


Question:
Generate the data for the Overview section in the report
        :return:

def sec_overview(self):

        """ Data sources overview: table with metric summaries"""
        metrics = self.config['overview']['activity_metrics']
        file_name = self.config['overview']['activity_file_csv']

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, file_name)

        logger.debug("CSV file %s generation in progress", file_name)

        csv = 'metricsnames,netvalues,relativevalues,datasource\n'
        for metric in metrics:
            # comparing current metric month count with previous month
            es_index = self.get_metric_index(metric)
            ds = metric.ds.name
            m = metric(self.es_url, es_index, start=self.start, end=self.end)
            (last, percentage) = m.get_trend()
            csv += "%s,%i,%i,%s" % (metric.name, last, percentage, ds)
            csv += "\n"
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            # Hack, we need to fix LaTeX escaping in a central place
            csv = csv.replace("_", r"\_")
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

        """
        Git Authors:

        description: average number of developers per month by quarters
        (so we have the average number of developers per month during
        those three months). If the approach is to work at the level of month,
        then just the number of developers per month.
        """

        author = self.config['overview']['author_metrics'][0]
        csv_labels = 'labels,' + author.id
        file_label = author.ds.name + "_" + author.id
        title_label = author.name + " per " + self.interval
        self.__create_csv_eps(author, None, csv_labels, file_label, title_label)

        logger.debug("CSV file %s generation in progress", file_name)

        bmi = []
        ttc = []  # time to close

        csv_labels = ''
        for m in self.config['overview']['bmi_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            bmi.append(metric.get_agg())

        for m in self.config['overview']['time_to_close_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            ttc.append(metric.get_agg())

        csv = csv_labels[:-1] + "\n"  # remove last comma
        csv = csv.replace("_", "")
        for val in bmi:
            csv += "%s," % (self.str_val(val))
        for val in ttc:
            csv += "%s," % (self.str_val(val))
        if csv[-1] == ',':
            csv = csv[:-1]

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, 'efficiency.csv')
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

def write_summary_cnts(self, go_ids):
        """"""
        obo = self.obo
        cnts = self.get_cnts_levels_depths_recs([obo.get(GO) for GO in go_ids])
        self._write_summary_cnts(cnts)

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


Question:
Ensure the string starts with a given value

@param string $ensure Value to ensure the string begins with

@return $this

public function ensureBeginsWith(string $ensure): Utility
    {
        if (!$this->beginsWith($ensure)) {
            return $this->prepend($ensure);
        }

        return $this;
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

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


Question:
// Sync prepare Comments to receive comments.
// Use Next to receive comments.
//
// See example: examples/media/commentsSync.go

func (comments *Comments) Sync() {
	endpoint := fmt.Sprintf(urlCommentSync, comments.item.ID)
	comments.endpoint = endpoint
	return
}

public static int parseBlockComment(final char[] query, int offset) {
    if (offset + 1 < query.length && query[offset + 1] == '*') {
      // /* /* */ */ nest, according to SQL spec
      int level = 1;
      for (offset += 2; offset < query.length; ++offset) {
        switch (query[offset - 1]) {
          case '*':
            if (query[offset] == '/') {
              --level;
              ++offset; // don't parse / in */* twice
            }
            break;
          case '/':
            if (query[offset] == '*') {
              ++level;
              ++offset; // don't parse * in /*/ twice
            }
            break;
          default:
            break;
        }

        if (level == 0) {
          --offset; // reset position to last '/' char
          break;
        }
      }
    }
    return offset;
  }

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


Question:
Extract data type name for each column as SQLite names.

        :param tabledata.TableData table_data:
        :return: { column_number : column_data_type }
        :rtype: dictionary

def __extract_col_type_from_tabledata(table_data):

        typename_table = {
            typepy.Typecode.INTEGER: "INTEGER",
            typepy.Typecode.REAL_NUMBER: "REAL",
            typepy.Typecode.STRING: "TEXT",
        }

        return dict(
            [
                [col_idx, typename_table.get(col_dp.typecode, "TEXT")]
                for col_idx, col_dp in enumerate(table_data.column_dp_list)
            ]
        )

static public HsqlName getAutoColumnName(int i) {

        if (i < autoColumnNames.length) {
            return autoColumnNames[i];
        }

        return new HsqlName(staticManager, makeAutoColumnName("C_", i), 0, false);
    }

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


Question: Restores project original configuration after compilation with SCoverage instrumentation.

@Override
    public void execute()
    {
        if ( "pom".equals( project.getPackaging() ) )
        {
            return;
        }

        if ( skip )
        {
            return;
        }

        long ts = System.currentTimeMillis();

        Properties projectProperties = project.getProperties();

        restoreProperty( projectProperties, "sbt._scalacOptions" );
        restoreProperty( projectProperties, "sbt._scalacPlugins" );
        restoreProperty( projectProperties, "addScalacArgs" );
        restoreProperty( projectProperties, "analysisCacheFile" );
        restoreProperty( projectProperties, "maven.test.failure.ignore" );

        long te = System.currentTimeMillis();
        getLog().debug( String.format( "Mojo execution time: %d ms", te - ts ) );
    }

func (self *Scheme) fromScope(s conversion.Scope) (inVersion, outVersion string, scheme *Scheme) {
	scheme = self
	inVersion = s.Meta().SrcVersion
	outVersion = s.Meta().DestVersion
	return inVersion, outVersion, scheme
}

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


Question:
Returns an instance of {@link CloudBlobClient} based on available authentication mechanism.
@return an instance of {@link CloudBlobClient}.
@throws IOException

@Override
  public CloudBlobClient getCloudBlobClient() throws IOException {
    String connectionString =  String.format(AZURE_STORAGE_CONNECTION_STRING_FORMAT,
        this.azureStorageAccountName, this.azureStorageAccountKey);
    try {
      return CloudStorageAccount.parse(connectionString).createCloudBlobClient();
    } catch (URISyntaxException | InvalidKeyException e) {
      throw new IOException("Failed to create a Cloud Storage Account.", e);
    }
  }

function(credentials){
      var socialLogin = false;
      if (credentials == undefined){
        credentials = {
          userid: $('#login_email').val(),
          password: $('#login_password').val()
        };
      } else if (typeof credentials === 'string'){
        socialLogin = true;
      }

      // Alter the UI to indicate that the login request is pending
      $('#login_button').attr('value', 'Logging in...');
      $('#register_button, #or').hide();

      var login = socialLogin ? cm.loginSocial.bind(cm) : cm.login.bind(cm);

      function loginError(msg){
        $('#login_button').attr('value', 'Login');
        $('#register_button, #or').show();
        todo.error('login', msg);
      }

      // Run CloudMine login request.
      login(credentials)
        .on('success', function(data){
          var services = data.profile.__services__;
          if(services){
            console.log("linked services:", services);
            data.profile.__services__.forEach(function(service){
              $('a.auth.' + service).hide();
            });
          }
          todo.process_login(data);
        })
        .on('unauthorized', function(data){
          loginError(data.errors[0]);
        })
        .on('error', function(data){
          loginError(data.errors ? data.errors[0] : "Error Logging in");
        })
    }

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


Question:
Copies a Workspace.

@param Workspace $workspace    - the original workspace to copy
@param Workspace $newWorkspace - the copy
@param bool      $model        - if true, the new workspace will be a model

@return Workspace

public function copy(Workspace $workspace, Workspace $newWorkspace, $model = false)
    {
        $transferManager = $this->container->get('claroline.manager.workspace.transfer');

        $fileBag = new FileBag();
        //these are the new workspace datas
        $data = $transferManager->serialize($workspace);
        $data = $transferManager->exportFiles($data, $fileBag, $workspace);

        if ($this->logger) {
            $transferManager->setLogger($this->logger);
        }

        if ($newWorkspace->getCode()) {
            unset($data['code']);
        }

        if ($newWorkspace->getName()) {
            unset($data['name']);
        }

        $options = [Options::LIGHT_COPY, Options::REFRESH_UUID];
        // gets entity from raw data.
        $workspace = $transferManager->deserialize($data, $newWorkspace, $options, $fileBag);
        $workspace->setIsModel($model);

        //set the manager
        $managerRole = $this->roleManager->getManagerRole($workspace);

        if ($managerRole && $workspace->getCreator()) {
            $user = $workspace->getCreator();
            $user->addRole($managerRole);
            $this->om->persist($user);
        }

        $root = $this->resourceManager->getWorkspaceRoot($workspace);

        if ($root) {
            $this->resourceManager->createRights($root);
        }

        $this->om->persist($workspace);
        $this->om->flush();

        return $workspace;
    }

func NewCmdObserve(fullName string, f kcmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewObserveOptions(streams)

	cmd := &cobra.Command{
		Use:     "observe RESOURCE [-- COMMAND ...]",
		Short:   "Observe changes to resources and react to them (experimental)",
		Long:    fmt.Sprintf(observeLong, fullName),
		Example: fmt.Sprintf(observeExample, fullName),
		Run: func(cmd *cobra.Command, args []string) {
			if err := o.Complete(f, cmd, args); err != nil {
				cmdutil.CheckErr(err)
			}

			if err := o.Validate(args); err != nil {
				cmdutil.CheckErr(cmdutil.UsageErrorf(cmd, err.Error()))
			}

			if err := o.Run(); err != nil {
				cmdutil.CheckErr(err)
			}
		},
	}

	// flags controlling what to select
	cmd.Flags().BoolVarP(&o.allNamespaces, "all-namespaces", "A", o.allNamespaces, "If true, list the requested object(s) across all projects. Project in current context is ignored.")
	cmd.Flags().StringVarP(&o.selector, "selector", "l", o.selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")

	// to perform deletion synchronization
	cmd.Flags().VarP(&o.deleteCommand, "delete", "d", "A command to run when resources are deleted. Specify multiple times to add arguments.")
	cmd.Flags().Var(&o.nameSyncCommand, "names", "A command that will list all of the currently known names, optional. Specify multiple times to add arguments. Use to get notifications when objects are deleted.")

	// add additional arguments / info to the server
	cmd.Flags().StringVar(&o.templateType, "output", o.templateType, "Controls the template type used for the --argument flags. Supported values are gotemplate and jsonpath.")
	cmd.Flags().BoolVar(&o.strictTemplates, "strict-templates", o.strictTemplates, "If true return an error on any field or map key that is not missing in a template.")
	cmd.Flags().VarP(&o.templates, "argument", "a", "Template for the arguments to be passed to each command in the format defined by --output.")
	cmd.Flags().StringVar(&o.typeEnvVar, "type-env-var", "", "The name of an env var to set with the type of event received ('Sync', 'Updated', 'Deleted', 'Added') to the reaction command or --delete.")
	cmd.Flags().StringVar(&o.objectEnvVar, "object-env-var", "", "The name of an env var to serialize the object to when calling the command, optional.")

	// control retries of individual commands
	cmd.Flags().IntVar(&o.maximumErrors, "maximum-errors", o.maximumErrors, "Exit after this many errors have been detected with. May be set to -1 for no maximum.")
	cmd.Flags().IntVar(&o.retryExitStatus, "retry-on-exit-code", o.retryExitStatus, "If any command returns this exit code, retry up to --retry-count times.")
	cmd.Flags().IntVar(&o.retryCount, "retry-count", o.retryCount, "The number of times to retry a failing command before continuing.")

	// control observe program behavior
	cmd.Flags().BoolVar(&o.once, "once", o.once, "If true, exit with a status code 0 after all current objects have been processed.")
	cmd.Flags().DurationVar(&o.exitAfterPeriod, "exit-after", o.exitAfterPeriod, "Exit with status code 0 after the provided duration, optional.")
	cmd.Flags().DurationVar(&o.resyncPeriod, "resync-period", o.resyncPeriod, "When non-zero, periodically reprocess every item from the server as a Sync event. Use to ensure external systems are kept up to date.")
	cmd.Flags().BoolVar(&o.printMetricsOnExit, "print-metrics-on-exit", o.printMetricsOnExit, "If true, on exit write all metrics to stdout.")
	cmd.Flags().StringVar(&o.listenAddr, "listen-addr", o.listenAddr, "The name of an interface to listen on to expose metrics and health checking.")

	// additional debug output
	cmd.Flags().BoolVar(&o.noHeaders, "no-headers", o.noHeaders, "If true, skip printing information about each event prior to executing the command.")

	return cmd
}

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


Question:
The method that will be used as a `sanitize_callback`.

@static
@access public
@since 1.0
@param array $value The value to be sanitized.
@return array The value.

public static function sanitize( $value ) {
		if ( ! is_array( $value ) ) {
			return [];
		}
		foreach ( $value as $key => $val ) {
			$value[ $key ] = Color::sanitize( $val );
		}
		return $value;
	}

private function normalizeParameters($parameters, $parentKey = '')
    {
        if (empty($parameters)) {
            return '';
        }

        $normalized = array();
        foreach ($parameters as $key => $value) {
            if (empty($value)) {
                continue;
            }

            if ($parentKey !== '') {
                // Multidimensional array; using foo=bar&foo=baz rather than foo[bar]=baz&foo[baz]=bar
                $key = $parentKey;
            }

            if (is_array($value)) {
                $normalized[] = $this->normalizeParameters($value, $key);
            } else {
                $normalized[] = $this->encode($key) . '=' . $this->encode($value);
            }
        }

        $normalized = array_filter($normalized);
        sort($normalized, SORT_STRING);

        return implode('&', $normalized);
    }

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


Question:
Validates the password.
This method serves as the inline validation for password.

@param string $attribute the attribute currently being validated
@param array $params the additional name-value pairs given in the rule

public function validateReNewPassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            if ($this->new_password != $this->re_new_password) {
                $this->addError($attribute, Yii::t('app', 'Confirm new password error.'));
            }
        }
    }

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: // RegisterGRPCServerAPI registers GRPC API service in provided GRPC server.

func RegisterGRPCServerAPI(n *centrifuge.Node, server *grpc.Server, config GRPCAPIServiceConfig) error {
	RegisterCentrifugoServer(server, newGRPCAPIService(n, config))
	return nil
}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: Starts the comms server communications.

public static void startServerComms() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "startServerComms");

        try {
            ServerConnectionManager.initialise(new AcceptListenerFactoryImpl());
        } catch (Throwable t) {
            FFDCFilter.processException(t, CLASS_NAME + ".startServerComms",
                                        CommsConstants.SERVERTRANSPORTFACTORY_INIT_02,
                                        null);

            SibTr.error(tc, "SERVER_FAILED_TO_START_SICO2004", t);
        }

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

public function execute(Input $input): void
    {
        $this->bus->handle(
            $this->messageCreator->create($this->command, $input)
        );
    }

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


Question:
Get all the searchable fields for a given set of classes
@param type $classNames

public function getAllSearchableFieldsFor($classNames) {
		$allfields = array();
		foreach ($classNames as $className) {
			$fields = $this->getSearchableFieldsFor($className);
			$allfields = array_merge($allfields, $fields);
		}

		return $allfields;
	}

public function tryGetOptionsForValues(array $values): array
    {
        if ($this->specificFieldOptionLoader) {
            return array_filter(array_map($this->specificFieldOptionLoader, $values));
        } else {
            return (new ArrayFieldOptions(call_user_func($this->fieldOptionsLoader)))->tryGetOptionsForValues($value);
        }
    }

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


Question:
Return a relative part of the URL.

        scheme, user, password, host and port are removed.

def relative(self):

        if not self.is_absolute():
            raise ValueError("URL should be absolute")
        val = self._val._replace(scheme="", netloc="")
        return URL(val, encoded=True)

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - quiz_id
        """ID"""
        path["quiz_id"] = quiz_id

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/reports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/reports".format(**path), data=data, params=params, all_pages=True)

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


Question: Simple PUT operation for a given path.

def _put(self, uri, data):

        headers = self._get_headers()

        logging.debug("URI=" + str(uri))
        logging.debug("BODY=" + json.dumps(data))

        response = self.session.put(uri, headers=headers,
                data=json.dumps(data))
        if response.status_code in [201, 204]:
            return data
        else:
            logging.error(response.content)
            response.raise_for_status()

public boolean upload(String text, String filePath) {
        WebLocator upload = new WebLocator(this).setTag("input").setLabel(text).setLabelPosition("//following-sibling::").setLabelTag("span").setType("file");
        return upload(upload, filePath);
    }

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


Question: Show the `xs` (inputs) and `ys` (targets).

def show_xys(self, xs, ys)->None:
        ""
        from IPython.display import display, HTML
        items,names = [], xs[0].names + ['target']
        for i, (x,y) in enumerate(zip(xs,ys)):
            res = []
            cats = x.cats if len(x.cats.size()) > 0 else []
            conts = x.conts if len(x.conts.size()) > 0 else []
            for c, n in zip(cats, x.names[:len(cats)]):
                res.append(x.classes[n][c])
            res += [f'{c:.4f}' for c in conts] + [y]
            items.append(res)
        items = np.array(items)
        df = pd.DataFrame({n:items[:,i] for i,n in enumerate(names)}, columns=names)
        with pd.option_context('display.max_colwidth', -1):
            display(HTML(df.to_html(index=False)))

def render_source(output_dir, package_spec):

    path, name = package_spec.filepath
    destination_filename = '%s/%s.proto' % (output_dir, name)
    pb_template = JENV.get_template(MESSAGES_TEMPLATE_NAME)
    includes = [include[:-5] if include.endswith('.yaml') else include for include in package_spec.includes]
    if 'types' in includes:
        includes.remove('types')
    with open(destination_filename, 'w') as f:
        f.write(pb_template.render(
            name=name,
            package=package_spec.identifier,
            messages=package_spec.definitions,
            includes=includes,
            description=package_spec.description,
        ))

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


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

@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case AfplibPackage.ATTRIBUTE_VALUE__RESERVED0:
				setReserved0(RESERVED0_EDEFAULT);
				return;
			case AfplibPackage.ATTRIBUTE_VALUE__ATT_VAL:
				setAttVal(ATT_VAL_EDEFAULT);
				return;
		}
		super.eUnset(featureID);
	}

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: // WriteAnalog writes PWM aka analog to the GrovePi. Not yet working.

func (d *GrovePiDriver) WriteAnalog(pin byte, val byte) error {
	buf := []byte{CommandWriteAnalog, pin, val, 0}
	_, err := d.connection.Write(buf)

	time.Sleep(2 * time.Millisecond)

	data := make([]byte, 1)
	_, err = d.connection.Read(data)

	return err
}

function Logger(logger, options) {
    options = options || {};

    /**
     * ### Logger.logger
     *
     * The Winston logger
     *
     * @see Winston
     */
    this.logger = winston.loggers.get(logger);

    /**
     * ### Logger.name
     *
     * The name of the logger (might be the name of the channel).
     *
     * @see ServerChannel
     */
    this.name = options.name;

    // Set the appropriate log function.
    if (logger === 'messages') this.log = this.logMsg;
    else this.log = this.logText;
}

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


Question:
Signal handler.

@param int $signal

public static function signalHandler($signal)
    {
        switch ($signal) {
            // Stop.
            case SIGINT:
                static::$_gracefulStop = false;
                static::stopAll();
                break;
            // Graceful stop.
            case SIGTERM:
                static::$_gracefulStop = true;
                static::stopAll();
                break;
            // Reload.
            case SIGQUIT:
            case SIGUSR1:
                if($signal === SIGQUIT){
                    static::$_gracefulStop = true;
                }else{
                    static::$_gracefulStop = false;
                }
                static::$_pidsToRestart = static::getAllWorkerPids();
                static::reload();
                break;
            // Show status.
            case SIGUSR2:
                static::writeStatisticsToStatusFile();
                break;
            // Show connection status.
            case SIGIO:
                static::writeConnectionsStatisticsToStatusFile();
                break;
        }
    }

def handle_error(self, error=None):
        """"""
        if _debug: TCPServer._debug("handle_error %r", error)

        # core does not take parameters
        asyncore.dispatcher.handle_error(self)

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


Question:
Output debug trace

@param \Throwable $e

@return string

public function output( \Throwable $e )
    {
        list( $file, $line ) = Util::caller(0);

        $title = 'CharcoalPHP: Exception List';

        return $this->_output( $e, $title, $file, $line );
    }

public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}

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


Question: Do basic audit check - configuration, collector error, no data

private static Audit doBasicAuditCheck(JSONArray jsonArray, JSONArray global, AuditType auditType) {
        Audit audit = new Audit();
        audit.setType(auditType);
        if (!isConfigured(auditType, global)) {
            audit.setDataStatus(DataStatus.NOT_CONFIGURED);
            audit.setAuditStatus(AuditStatus.NA);
            return audit;
        }
        if (jsonArray == null || CollectionUtils.isEmpty(jsonArray)) {
            audit.setAuditStatus(AuditStatus.NA);
            audit.setDataStatus(DataStatus.NO_DATA);
            return audit;
        }
        if (isCollectorError(jsonArray)) {
            audit.setAuditStatus(AuditStatus.NA);
            audit.setDataStatus(DataStatus.ERROR);
            return audit;
        }
        return null;
    }

@Override
   void processModelNode(OperationContext context, ModelNode counter,
         CounterConfiguration.Builder builder) throws OperationFailedException {
      super.processModelNode(context, counter, builder);

      Integer concurrency = WeakCounterResource.CONCURRENCY_LEVEL.resolveModelAttribute(context, counter).asInt();
      builder.concurrencyLevel(concurrency);
   }

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


Question:
Sets the tags for the HTTP message.

@param tags the new tags.
@throws IllegalArgumentException if the given parameter is {@code null}.
@since 2.7.0
@see #addTag(String)
@see #deleteTag(String)

public void setTags(List<String> tags) {
		if (tags == null) {
			throw new IllegalArgumentException("Parameter tags must not be null.");
		}

		for (String tag : tags) {
			if (!this.tags.contains(tag)) {
				insertTagDb(tag);
			}
		}

		for (String tag : this.tags) {
			if (!tags.contains(tag)) {
				deleteTagDb(tag);
			}
		}

		this.tags = new ArrayList<>(tags);
		notifyEvent(HistoryReferenceEventPublisher.EVENT_TAGS_SET);
	}

public void removeAttribute(String arg0) {
        // 321485
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"removeAttribute", "this->"+this+": "+" name --> " + arg0);
        }
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        Object oldValue = _srtRequestHelper._attributes.remove(arg0);
        if (oldValue != null) {
            this.attributeRemoved(arg0, oldValue);
        }
    }

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


Question:
Задаёт заголовок сайта

@param string $title  новый заголовок

@throws Eresus_Exception_InvalidArgumentType
@since 3.01

public function setTitle($title)
    {
        if (!is_string($title))
        {
            throw Eresus_Exception_InvalidArgumentType::factory(__METHOD__, 1, 'string', $title);
        }
        $this->title = $title;
    }

function (arg) {
    var self = this;

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

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

    return argCode;
  }

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


Question:
generate Error-classes based on ErrozError

@param error
@returns {Function}

function erroz(error) {

    var errorFn = function (data) {

        //apply all attributes on the instance
        for (var errKey in errorFn.prototype) {
            if (errorFn.prototype.hasOwnProperty(errKey)) {
                this[errKey] = errorFn.prototype[errKey];
            }
        }

        //overwrite message if invoked with string
        if (typeof data === "string") {
            this.message = data;
            data = {};
        }

        this.data = data || {};

        this.message = this.message || erroz.options.renderMessage(error.template || "", this.data);

        errorFn.super_.call(this, this.constructor);
    };

    util.inherits(errorFn, AbstractError);

    //add static error properties (name, status, etc)
    for (var errKey in error) {
        if (error.hasOwnProperty(errKey)) {
            errorFn.prototype[errKey] = error[errKey];
        }
    }

    /**
     * return an object containing only JSend attributes
     * @returns {{status: *, code: *, message: *, data: (*|string|Object[]|Object|String)}}
     */
    errorFn.prototype.toJSend = function () {
        var data = this.data;

        if (erroz.options.includeStack && this.stack) {
            data.stack = this.stack;
        }

        if (!this.status) {
            this.status = deriveStatusFromStatusCode(this.statusCode);
        }

        return {
            status: this.status,
            code: this.code,
            message: this.message,
            data: data
        };
    };

    return errorFn;
}

public function addRoute($route)
    {
        if (!$route instanceof Route && !is_array($route)) {
            throw new \LogicException('Route invalid. Expected Route instance or array.');
        } elseif ($route instanceof Route) {
            $name = $route->getName();
            if (isset($this->routes[$name])) {
                throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name));
            }
            $this->routes[$route->getName()] = $route;
        } elseif (is_array($route) && !count($route) == 4) {
            throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).');
        } else {
            list($methods, $patternUri, $action, $name) = array_values($route);

            $this->routes[$name] = new Route($methods, $patternUri, $action, $name);
        }

        return $this;
    }

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


Question: // updatePhysicalHost updates an existing physical host in the database.

func updatePhysicalHost(c context.Context, h *crimson.PhysicalHost, mask *field_mask.FieldMask) (*crimson.PhysicalHost, error) {
	if err := validatePhysicalHostForUpdate(h, mask); err != nil {
		return nil, err
	}
	update := false
	updateState := false
	stmt := squirrel.Update("physical_hosts")
	for _, path := range mask.Paths {
		switch path {
		case "machine":
			stmt = stmt.Set("machine_id", squirrel.Expr("(SELECT id FROM machines WHERE name = ?)", h.Machine))
			update = true
		case "os":
			stmt = stmt.Set("os_id", squirrel.Expr("(SELECT id FROM oses WHERE name = ?)", h.Os))
			update = true
		case "state":
			updateState = true
		case "vm_slots":
			stmt = stmt.Set("vm_slots", h.VmSlots)
			update = true
		case "virtual_datacenter":
			stmt = stmt.Set("virtual_datacenter", h.VirtualDatacenter)
			update = true
		case "description":
			stmt = stmt.Set("description", h.Description)
			update = true
		case "deployment_ticket":
			stmt = stmt.Set("deployment_ticket", h.DeploymentTicket)
			update = true
		}
	}
	var query string
	var args []interface{}
	var err error
	if update {
		stmt = stmt.Where("hostname_id = (SELECT id FROM hostnames WHERE name = ?)", h.Name)
		query, args, err = stmt.ToSql()
		if err != nil {
			return nil, errors.Annotate(err, "failed to generate statement").Err()
		}
	}

	tx, err := database.Begin(c)
	if err != nil {
		return nil, errors.Annotate(err, "failed to begin transaction").Err()
	}
	defer tx.MaybeRollback(c)

	if query != "" && len(args) > 0 {
		_, err = tx.ExecContext(c, query, args...)
		if err != nil {
			switch e, ok := err.(*mysql.MySQLError); {
			case !ok:
				// Type assertion failed.
			case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'machine_id'"):
				// e.g. "Error 1062: Duplicate entry '1' for key 'machine_id'".
				return nil, status.Errorf(codes.AlreadyExists, "duplicate physical host for machine %q", h.Machine)
			case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"):
				// e.g. "Error 1048: Column 'machine_id' cannot be null".
				return nil, status.Errorf(codes.NotFound, "machine %q does not exist", h.Machine)
			case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'os_id'"):
				// e.g. "Error 1048: Column 'os_id' cannot be null".
				return nil, status.Errorf(codes.NotFound, "operating system %q does not exist", h.Os)
			}
			return nil, errors.Annotate(err, "failed to update physical host").Err()
		}
		// The number of rows affected cannot distinguish between zero because the physical host didn't exist
		// and zero because the row already matched, so skip looking at the number of rows affected.
	}
	if updateState {
		_, err = tx.ExecContext(c, `
			UPDATE machines
			SET state = ?
			WHERE id = (SELECT machine_id FROM physical_hosts WHERE hostname_id = (SELECT id FROM hostnames WHERE name = ?))
		`, h.State, h.Name)
		if err != nil {
			return nil, errors.Annotate(err, "failed to update machine").Err()
		}
	}

	hosts, err := listPhysicalHosts(c, tx, &crimson.ListPhysicalHostsRequest{
		Names: []string{h.Name},
	})
	switch {
	case err != nil:
		return nil, errors.Annotate(err, "failed to fetch updated physical host").Err()
	case len(hosts) == 0:
		return nil, status.Errorf(codes.NotFound, "physical host %q does not exist", h.Name)
	}

	if err := tx.Commit(); err != nil {
		return nil, errors.Annotate(err, "failed to commit transaction").Err()
	}
	return hosts[0], nil
}

func (*SwitchesTable) needsUpdate(row, cfg *Switch) bool {
	return row.Ports != cfg.Ports || row.Description != cfg.Description || row.State != cfg.State || row.RackId != cfg.RackId
}

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


Question:
Remove the model

@param  Model $model
@param  array $options
@return bool
@throws Exceptions\OperationError

protected function removeModel(Model $model, array $options = []) {
		if (! isset($model->_id)) {
			throw new Exceptions\OperationError('The model has no ID');
		}

		$id = $this->normalizeId($model->_id);

		return $this->getAdapter()->remove(
			$this->getTableName(),
			['_id' => $id],
			$options
		);
	}

protected function prepareOptions($name)
    {
        return [
            'addc' => $this->additionalCode,
            'dely' => $this->prepareOptionDelay(),
            'ercl' => $this->prepareOption('errorClass'),
            'erst' => $this->prepareOption('errorStyle'),
            'hecl' => $this->prepareOption('headerClass'),
            'hest' => $this->prepareOption('headerStyle'),
            'jsev' => $this->prepareOptionBool('jsEventsCallback'),
            'keyt' => $this->prepareOptionBool('keyTrigger'),
            'loca' => $this->prepareOptionLocal(),
            'locl' => $this->prepareOption('loadingClass'),
            'lost' => $this->prepareOption('loadingStyle'),
            'mabe' => $this->prepareOption('markBegin'),
            'maen' => $this->prepareOption('markEnd'),
            'minq' => $this->prepareOptionMinQuery(),
            'name' => $name,
            'nebe' => $this->prepareOption('nextBegin'),
            'necl' => $this->prepareOption('nextClass'),
            'neen' => $this->prepareOption('nextEnd'),
            'nest' => $this->prepareOption('nextStyle'),
            'nrcl' => $this->prepareOption('noRecordsClass'),
            'nrst' => $this->prepareOption('noRecordsStyle'),
            'onrm' => $this->onRemove,
            'onsl' => $this->onSelect,
            'pabe' => $this->prepareOption('pagerBegin'),
            'paen' => $this->prepareOption('pagerEnd'),
            'prbe' => $this->prepareOption('previousBegin'),
            'prcl' => $this->prepareOption('previousClass'),
            'pren' => $this->prepareOption('previousEnd'),
            'prst' => $this->prepareOption('previousStyle'),
            'prba' => $this->prepareOptionProgressBar(),
            'recl' => $this->prepareOption('recordClass'),
            'rest' => $this->prepareOption('recordStyle'),
            'rmcl' => $this->prepareOption('removeClass'),
            'rmla' => $this->prepareOption('removeLabel'),
            'rmst' => $this->prepareOption('removeStyle'),
            'rscl' => $this->prepareOption('resultClass'),
            'rsst' => $this->prepareOption('resultStyle'),
            'smbt' => $this->prepareOptionBool('singleModeBottom'),
            'smod' => $this->prepareOptionBool('singleMode'),
            'swcl' => $this->prepareOption('switchClass'),
            'swst' => $this->prepareOption('switchStyle'),
            'url'  => $this->source,
        ];
    }

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


Question:
Removes all the members contained in v from this membership

@param v a list of all the members to be removed

public Membership remove(Collection<Address> v) {
        if(v != null) {
            synchronized(members) {
                members.removeAll(v);
            }
        }
        return this;
    }

public function setHeaders(array $headers)
    {
        $this->headerRemove();

        foreach ($headers as $name => $values) {
            foreach ((array)$values as $value) {
                $this->header("$name: $value", false);
            }
        }
    }

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


Question:
adds a special operator like $maxScan or $returnKey
e.g. addSpecial( "$returnKey" , 1 )
e.g. addSpecial( "$maxScan" , 100 )

@param name The name
@param o    The object
@return This object

public DBCursor<T> addSpecial(String name, Object o) {
        cursor.addSpecial(name, o);
        return this;
    }

public Observable<ServiceResponse<Void>> deleteValueWithServiceResponseAsync(String tagName, String tagValue) {
        if (tagName == null) {
            throw new IllegalArgumentException("Parameter tagName is required and cannot be null.");
        }
        if (tagValue == null) {
            throw new IllegalArgumentException("Parameter tagValue is required and cannot be null.");
        }
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteValue(tagName, tagValue, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteValueDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: Lookup function used when value is not found.

def _missing_(cls, value):
        """"""
        if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF):
            raise ValueError('%r is not a valid %s' % (value, cls.__name__))
        if 0x0000 <= value <= 0x05DC:
            # [Neil_Sembower]
            extend_enum(cls, 'IEEE802.3 Length Field [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x0101 <= value <= 0x01FF:
            # [Neil_Sembower]
            extend_enum(cls, 'Experimental [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x0888 <= value <= 0x088A:
            # [Neil_Sembower]
            extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x1001 <= value <= 0x100F:
            # [Neil_Sembower]
            extend_enum(cls, 'Berkeley Trailer encap/IP [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x6008 <= value <= 0x6009:
            # [Neil_Sembower]
            extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x6010 <= value <= 0x6014:
            # [Neil_Sembower]
            extend_enum(cls, '3Com Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x7020 <= value <= 0x7029:
            # [Neil_Sembower]
            extend_enum(cls, 'LRT [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8039 <= value <= 0x803C:
            # [Neil_Sembower]
            extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8040 <= value <= 0x8042:
            # [Neil_Sembower]
            extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x806E <= value <= 0x8077:
            # [Neil_Sembower]
            extend_enum(cls, 'Landmark Graphics Corp. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x807D <= value <= 0x807F:
            # [Neil_Sembower]
            extend_enum(cls, 'Vitalink Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8081 <= value <= 0x8083:
            # [Neil_Sembower]
            extend_enum(cls, 'Counterpoint Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x809C <= value <= 0x809E:
            # [Neil_Sembower]
            extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80A4 <= value <= 0x80B3:
            # [Neil_Sembower]
            extend_enum(cls, 'Siemens Gammasonics Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80C0 <= value <= 0x80C3:
            # [Neil_Sembower]
            extend_enum(cls, 'DCA Data Exchange Cluster [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80C8 <= value <= 0x80CC:
            # [Neil_Sembower]
            extend_enum(cls, 'Intergraph Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80CD <= value <= 0x80CE:
            # [Neil_Sembower]
            extend_enum(cls, 'Harris Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80CF <= value <= 0x80D2:
            # [Neil_Sembower]
            extend_enum(cls, 'Taylor Instrument [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80D3 <= value <= 0x80D4:
            # [Neil_Sembower]
            extend_enum(cls, 'Rosemount Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80DE <= value <= 0x80DF:
            # [Neil_Sembower]
            extend_enum(cls, 'Integrated Solutions TRFS [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80E0 <= value <= 0x80E3:
            # [Neil_Sembower]
            extend_enum(cls, 'Allen-Bradley [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80E4 <= value <= 0x80F0:
            # [Neil_Sembower]
            extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x80F4 <= value <= 0x80F5:
            # [Neil_Sembower]
            extend_enum(cls, 'Kinetics [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8101 <= value <= 0x8103:
            # [Neil_Sembower]
            extend_enum(cls, 'Wellfleet Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8107 <= value <= 0x8109:
            # [Neil_Sembower]
            extend_enum(cls, 'Symbolics Private [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8132 <= value <= 0x8136:
            # [Neil_Sembower]
            extend_enum(cls, 'Bridge Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8137 <= value <= 0x8138:
            # [Neil_Sembower]
            extend_enum(cls, 'Novell, Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8139 <= value <= 0x813D:
            # [Neil_Sembower]
            extend_enum(cls, 'KTI [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8151 <= value <= 0x8153:
            # [Neil_Sembower]
            extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x815C <= value <= 0x815E:
            # [Neil_Sembower]
            extend_enum(cls, 'Computer Protocol Pty Ltd [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8164 <= value <= 0x8166:
            # [Neil_Sembower]
            extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8184 <= value <= 0x818C:
            # [Neil_Sembower]
            extend_enum(cls, 'Silicon Graphics prop. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x819A <= value <= 0x81A3:
            # [Neil_Sembower]
            extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81A5 <= value <= 0x81AE:
            # [Neil_Sembower]
            extend_enum(cls, 'RAD Network Devices [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81B7 <= value <= 0x81B9:
            # [Neil_Sembower]
            extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81CC <= value <= 0x81D5:
            # [Neil_Sembower]
            extend_enum(cls, 'Apricot Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81D6 <= value <= 0x81DD:
            # [Neil_Sembower]
            extend_enum(cls, 'Artisoft [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81E6 <= value <= 0x81EF:
            # [Neil_Sembower]
            extend_enum(cls, 'Polygon [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81F0 <= value <= 0x81F2:
            # [Neil_Sembower]
            extend_enum(cls, 'Comsat Labs [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81F3 <= value <= 0x81F5:
            # [Neil_Sembower]
            extend_enum(cls, 'SAIC [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x81F6 <= value <= 0x81F8:
            # [Neil_Sembower]
            extend_enum(cls, 'VG Analytical [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8203 <= value <= 0x8205:
            # [Neil_Sembower]
            extend_enum(cls, 'Quantum Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8221 <= value <= 0x8222:
            # [Neil_Sembower]
            extend_enum(cls, 'Ascom Banking Systems [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x823E <= value <= 0x8240:
            # [Neil_Sembower]
            extend_enum(cls, 'Advanced Encryption Syste [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x827F <= value <= 0x8282:
            # [Neil_Sembower]
            extend_enum(cls, 'Athena Programming [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8263 <= value <= 0x826A:
            # [Neil_Sembower]
            extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x829A <= value <= 0x829B:
            # [Neil_Sembower]
            extend_enum(cls, 'Inst Ind Info Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x829C <= value <= 0x82AB:
            # [Neil_Sembower]
            extend_enum(cls, 'Taurus Controls [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x82AC <= value <= 0x8693:
            # [Neil_Sembower]
            extend_enum(cls, 'Walker Richer & Quinn [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8694 <= value <= 0x869D:
            # [Neil_Sembower]
            extend_enum(cls, 'Idea Courier [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x869E <= value <= 0x86A1:
            # [Neil_Sembower]
            extend_enum(cls, 'Computer Network Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x86A3 <= value <= 0x86AC:
            # [Neil_Sembower]
            extend_enum(cls, 'Gateway Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x86E0 <= value <= 0x86EF:
            # [Neil_Sembower]
            extend_enum(cls, 'Landis & Gyr Powers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8700 <= value <= 0x8710:
            # [Neil_Sembower]
            extend_enum(cls, 'Motorola [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0x8A96 <= value <= 0x8A97:
            # [Neil_Sembower]
            extend_enum(cls, 'Invisible Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        if 0xFF00 <= value <= 0xFF0F:
            # [Neil_Sembower]
            extend_enum(cls, 'ISC Bunker Ramo [0x%s]' % hex(value)[2:].upper().zfill(4), value)
            return cls(value)
        super()._missing_(value)

func (i *Import) GetVCS() string {
	if i == nil || i.VCS == nil {
		return ""
	}
	return *i.VCS
}

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


Question: // SetNextToken sets the NextToken field's value.

func (s *ListPolicyAttachmentsOutput) SetNextToken(v string) *ListPolicyAttachmentsOutput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
Check if session-variable exists.

@param string $name
@param string $namespace Default '*'.
@return bool

public static function has(string $name, string $namespace = '*'): bool
    {
        self::initialize();
        return isset($_SESSION[$namespace]) && array_key_exists($name, $_SESSION[$namespace]);
    }

func (s *StartSessionInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "StartSessionInput"}
	if s.Target == nil {
		invalidParams.Add(request.NewErrParamRequired("Target"))
	}
	if s.Target != nil && len(*s.Target) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("Target", 1))
	}

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

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


def process_business_card(image_path, options = {})
      RestClient.post("#{url}/processBusinessCard", options.merge(:upload => { :file => File.new(image_path, 'r') }))
    end

public function getSecondOperation()
    {
        $returnValue = null;

        if(empty($this->secondOperation)){
        	$property = new core_kernel_classes_Property(RulesRdf::PROPERTY_OPERATION_SECOND_OP);
        	$resource = $this->getUniquePropertyValue($property);
        	$this->secondOperation = new core_kernel_rules_Term($resource->getUri());
        }
        $returnValue = $this->secondOperation;

        return $returnValue;
    }

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


Question:
CSV
---

Converts an array of array or array of objects into a correct
CSV string for exports purposes.

Exposes some handful options such as choice of delimiters or order
of keys to handle.
 Convert an object into an array of its properties

function objectToArray(o, order) {
    order = order || Object.keys(o);

    return order.map(function(k) {
      return o[k];
    });
  }

public function download()
    {
        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ignore_user_abort();

        $datatable = app(ActivityLogs::class);

        list($headers, $data) = $this->prepareHeadersAndKeys($datatable);
        $items = $this->prepareContent($datatable, $data);

        $top      = implode(self::separator, $headers);
        $content  = implode("\n", $items);
        $csv      = implode("\n", [$top, $content]);
        $date     = date('Y_m_d_H_i_s', time());
        $filename = "activity_log_{$date}.csv";

        return response($csv, 200, [
            'Content-Type'              => 'text/csv',
            'Content-Description'       => 'File Transfer',
            'Content-Disposition'       => 'attachment; filename=' . $filename,
            'Content-Transfer-Encoding' => 'binary',
            'Connection'                => 'Keep-Alive',
            'Expires'                   => '0',
            'Cache-Control'             => 'must-revalidate, post-check=0, pre-check=0',
            'Pragma'                    => 'public',
            'Content-Length'            => strlen($csv)]);
    }

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


Question:
@param $values

@return array

private function getMostFrequentValues($values)
    {
        // remove false values (while keeping zeros)
        $values = array_filter($values, 'strlen');

        // array_count_values requires strings or integer, convert floats to string (mysqli)
        foreach ($values as &$value) {
            if (is_numeric($value)) {
                $value = (string)round($value, 3);
            }
        }
        // we have a list of all values. let's show the most frequently used first.
        $values = array_count_values($values);

        // Sort this list by converting and sorting the array with custom method, so the result doesn't differ between PHP versions
        $sortArray = [];

        foreach ($values as $value => $count) {
            $sortArray[] = [
                'value' => $value,
                'count' => $count
            ];
        }

        usort($sortArray, function($a, $b) {
            if ($a['count'] == $b['count']) {
                return strcmp($a['value'], $b['value']);
            }

            return $a['count'] > $b['count'] ? -1 : 1;
        });

        return array_column($sortArray, 'value');
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question: Get the dataset's pip requirements

def reqs(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    (print)(data(dataset, **ctx.obj).reqs(**kwargs))

def _isvalid(self, datatype):
        ''''''
        if datatype in self.meta:
            return bool(Dap._meta_valid[datatype].match(self.meta[datatype]))
        else:
            return datatype in Dap._optional_meta

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


Question:
Adds a new constant.
@param \Peg\Lib\Definitions\Element\Constant $constant
@param string $namespace

public function AddConstant(
        \Peg\Lib\Definitions\Element\Constant $constant,
        $namespace = "\\"
    )
    {
        $this->CreateNamespace($namespace);

        $constant->header =& $this;
        $constant->namespace =& $this->namespaces[$namespace];

        $this->namespaces[$namespace]->constants[$constant->name] = $constant;
    }

def output_header(code)
      if header = @grammar.directives['header']
        code << header.action.strip
        code << "\n"
      end

      pre_class = @grammar.directives['pre-class']

      if @standalone
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name}\n"

        cp  = standalone_region("compiled_parser.rb")
        cpi = standalone_region("compiled_parser.rb", "INITIALIZE")
        pp  = standalone_region("position.rb")

        cp.gsub!(/^\s*include Position/, pp)
        code << "  # :stopdoc:\n"
        code << cpi << "\n" unless @grammar.variables['custom_initialize']
        code << cp  << "\n"
        code << "  # :startdoc:\n"
      else
        code << "require 'kpeg/compiled_parser'\n\n"
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name} < KPeg::CompiledParser\n"
      end

      @grammar.setup_actions.each do |act|
        code << "\n#{act.action}\n\n"
      end
    end

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


Question:
Get the sort order SQL for a sort method.

@param int|null  $sortmethod
@param bool|null $includefavourites
@return string

private function get_sort_order(?int $sortmethod, bool $includefavourites = true) : string {

        $alias = $this->get_table_alias();
        // TODO consider user favourites...
        $keyfield = $this->get_keyfield($sortmethod);
        $direction = $this->get_sort_direction($sortmethod);

        $favouritesort = '';
        if ($includefavourites) {
            $favalias = $this->get_favourite_alias();
            // Since we're joining on the favourite table any discussion that isn't favourited will have
            // null in the favourite columns. Nulls behave differently in the sorting for different databases.
            // We can ensure consistency between databases by explicitly deprioritising any null favourite field
            // using a case statement.
            $favouritesort = ", CASE WHEN {$favalias}.id IS NULL THEN 0 ELSE 1 END DESC";
            // After the null favourite fields are deprioritised and appear below the favourited discussions we
            // need to order the favourited discussions by id so that the most recently favourited discussions
            // appear at the top of the list.
            $favouritesort .= ", {$favalias}.itemtype DESC";
        }

        return "{$alias}.pinned DESC $favouritesort , {$keyfield} {$direction}";
    }

public SDVariable unsortedSegmentSum(@NonNull SDVariable data, @NonNull SDVariable segmentIds, int numSegments) {
        return unsortedSegmentSum(null, data, segmentIds, numSegments);
    }

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


Question:
Sets the source region (AOI) for the new image.

@param pRegion the source region

public void setSourceRegion(final Rectangle pRegion) {
        // Re-fetch everything, if region changed
        if (x != pRegion.x || y != pRegion.y || width != pRegion.width || height != pRegion.height) {
            dispose();
        }

        x = pRegion.x;
        y = pRegion.y;
        width = pRegion.width;
        height = pRegion.height;
    }

func (b *Bmattermost) handleDownloadAvatar(userid string, channel string) {
	rmsg := config.Message{
		Username: "system",
		Text:     "avatar",
		Channel:  channel,
		Account:  b.Account,
		UserID:   userid,
		Event:    config.EventAvatarDownload,
		Extra:    make(map[string][]interface{}),
	}
	if _, ok := b.avatarMap[userid]; !ok {
		data, resp := b.mc.Client.GetProfileImage(userid, "")
		if resp.Error != nil {
			b.Log.Errorf("ProfileImage download failed for %#v %s", userid, resp.Error)
			return
		}
		err := helper.HandleDownloadSize(b.Log, &rmsg, userid+".png", int64(len(data)), b.General)
		if err != nil {
			b.Log.Error(err)
			return
		}
		helper.HandleDownloadData(b.Log, &rmsg, userid+".png", rmsg.Text, "", &data, b.General)
		b.Remote <- rmsg
	}
}

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


Question:
activate custom debugging
registers error handler and exception handler

@param integer $reportingLevel
@param boolean $displayErrors

public static function enable($reportingLevel = NULL, $displayErrors = NULL) {

		if (!static::$enabled) {

			static::$enabled = true;
			error_reporting(E_ALL);

			ErrorHandler::register($reportingLevel, $displayErrors);

			if (PHP_SAPI !== 'cli') {
				ExceptionHandler::register($reportingLevel, $displayErrors);
			}
			elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) {
				ini_set('display_errors', 1);
			}
		}

	}

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

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

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

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

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

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


Question:
//
// Int64
//
// Int64 creates a valid NullInt64

func Int64(i int64) NullInt64 {
	return NullInt64{
		sql.NullInt64{
			Int64: i,
			Valid: true,
		},
	}
}

@Nonnull
  public BootstrapDisplayBuilder display (@Nonnull final EBootstrapDisplayType eDisplay)
  {
    ValueEnforcer.notNull (eDisplay, "eDisplay");
    m_eDisplay = eDisplay;
    return this;
  }

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


Question: // EncodeTLSInfoToText returns a human readable string, suitable for certigo console output.

func EncodeTLSInfoToText(tcs *tls.ConnectionState, cri *tls.CertificateRequestInfo) string {
	version := lookup(tlsVersions, tcs.Version)
	cipher := lookup(cipherSuites, tcs.CipherSuite)
	description := TLSDescription{
		Version: tlscolor(version),
		Cipher:  tlscolor(explainCipher(cipher)),
	}
	tlsInfoContext := tlsInfoContext{
		Conn: &description,
	}
	if cri != nil {
		criDesc, err := EncodeCRIToObject(cri)
		if err == nil {
			tlsInfoContext.CRI = criDesc.(*CertificateRequestInfo)
		}
	}

	funcMap := sprig.TxtFuncMap()
	extras := template.FuncMap{
		"printCommonName": PrintCommonName,
		"printShortName":  PrintShortName,
		"greenify":        greenify,
	}
	for k, v := range extras {
		funcMap[k] = v
	}

	t := template.New("TLS template").Funcs(funcMap)
	t, err := t.Parse(tlsLayout)
	if err != nil {
		// Should never happen
		panic(err)
	}
	var buffer bytes.Buffer
	w := bufio.NewWriter(&buffer)
	err = t.Execute(w, tlsInfoContext)
	if err != nil {
		// Should never happen
		panic(err)
	}
	w.Flush()
	return string(buffer.Bytes())
}

func printEndpointLabels(lbls *labels.OpLabels) {
	log.WithField(logfields.Labels, logfields.Repr(*lbls)).Debug("All Labels")
	w := tabwriter.NewWriter(os.Stdout, 2, 0, 3, ' ', 0)

	for _, v := range lbls.IdentityLabels() {
		text := color.Green("Enabled")
		fmt.Fprintf(w, "%s\t%s\n", v, text)
	}

	for _, v := range lbls.Disabled {
		text := color.Red("Disabled")
		fmt.Fprintf(w, "%s\t%s\n", v, text)
	}
	w.Flush()
}

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


Question:
Terminate all the connections associated with the chain

@param chainName
@throws Exception

public void terminateConnectionsAssociatedWithChain(String chainName) throws Exception {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(this, tc, "terminateConnectionsAssociatedWithChain", chainName);

        synchronized (endPointToGroupMap) {

            try {
                final HashMap<EndPointDescriptor, ConnectionDataGroup> endPointToGroupMapClone = (HashMap<EndPointDescriptor, ConnectionDataGroup>) endPointToGroupMap.clone();
                Iterator<EndPointDescriptor> it = endPointToGroupMapClone.keySet().iterator();
                while (it.hasNext()) {
                    EndPointDescriptor ed = it.next();

                    if ((((HostPortEndPointDescriptor) ed).chainName).equals(chainName)) {

                        ConnectionDataGroup cdGroup = endPointToGroupMapClone.get(ed);

                        final List connectionData = cdGroup.getConnections();

                        for (final Iterator connectionDataIterator = connectionData.iterator(); connectionDataIterator.hasNext();)
                        {
                            final ConnectionData thisConnectionData = (ConnectionData) connectionDataIterator.next();
                            final OutboundConnection oc = thisConnectionData.getConnection();
                            //close all the conservations associated with the OC
                            Conversation[] conv = oc.getConversations();
                            for (Conversation c : conv) {
                                try {
                                    c.fastClose();
                                } catch (Exception e) {//Don't let the exception mess up closing other remaining conservations
                                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                        SibTr.debug(tc, "Error while fast closing the conversation", e);
                                }

                            }
                            try {
                                // terminate the physical connection
                                purgeFromInvalidateImpl(oc, false);
                            } catch (Exception e) {//Don't let the exception mess up closing other remaining connection
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                    SibTr.debug(tc, "Error while purging the physical connection", e);
                            }
                        }

                        try {
                            // destroy the OutboundVirtualConnection associated with the chainName
                            cdGroup.getNetworkConnectionFactory().getOutboundVirtualConFactory().destroy();
                        } catch (Exception e) {//Don't let the exception mess up closing other remaining connection
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                                SibTr.debug(tc, "Error while destroying the outbound virtual connection", e);
                        }
                        // in fastClose() the entry is removed but still we do a remove
                        endPointToGroupMap.remove(ed);

                    }
                }

            } catch (Exception e) {
                throw e;
            } finally {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                    Tr.exit(this, tc, "terminateConnectionsAssociatedWithChain");
            }

        }
    }

public static void tearDownExample(String host, int port, String user, String password, Authentication authType) {
    DatabaseClient client = DatabaseClientFactory.newClient(host, port, user, password, authType);

    ResourceExtensionsManager resourceMgr = client.newServerConfigManager().newResourceExtensionsManager();

    resourceMgr.deleteServices(HelloWorld.NAME);

    client.release();
  }

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


Question:
Helper function to determine if a user is part
of this team

@param Model $user
@return bool

public function hasUser( Model $user )
    {
        return $this->users()->where( $user->getKeyName(), "=", $user->getKey() )->first() ? true : false;
    }

func CheckFollowing(c *context.APIContext) {
	u := GetUserByParams(c)
	if c.Written() {
		return
	}
	target := GetUserByParamsName(c, ":target")
	if c.Written() {
		return
	}
	checkUserFollowing(c, u, target.ID)
}

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


Question:
@param string $code

@return int

public static function getHierarchyLevel($code)
    {
        if ($code === '') {
            return 0;
        }

        $current_length = 0;
        $code_length = strlen($code);
        foreach (static::getHierarchyLengths() as $i => $length) {
            $current_length += $length;
            if ($current_length === $code_length) {
                return $i + 1;
            }
        }

        return -1;
    }

func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN {
	p.StrLen_or_IndPtr = v
	return &p.StrLen_or_IndPtr

}

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


Question: Constructs an instance of BigtableInstanceAdminClient with the given project id and stub.

public static BigtableInstanceAdminClient create(
      @Nonnull String projectId, @Nonnull BigtableInstanceAdminStub stub) {
    return new BigtableInstanceAdminClient(projectId, stub);
  }

protected function registerBitbucketFactory()
    {
        $this->app->singleton('bitbucket.factory', function (Container $app) {
            $auth = $app['bitbucket.authfactory'];
            $cache = $app['cache'];

            return new BitbucketFactory($auth, $cache);
        });

        $this->app->alias('bitbucket.factory', BitbucketFactory::class);
    }

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


Question:
Returns another PropertyFilter instance which is bound to the given constant value.

@throws IllegalArgumentException if value is not compatible with property type

public PropertyFilter<S> constant(Object value) {
        if (mBindID == BOUND_CONSTANT) {
            if (mConstant == null) {
                if (value == null) {
                    return this;
                }
            } else if (mConstant.equals(value)) {
                return this;
            }
        }
        return getCanonical(mProperty, mOp, adaptValue(value));
    }

private function initialize()
    {
        $params = $this->getParameters();
        if ($params !== null) {
            foreach ($params as $param) {
                if (self::CONTAINS_KEY === $param->getType()) {
                    $cont = new Contains();
                    $cont->setValue($param->getValue());
                    $this->contains[] = $cont;
                } elseif (self::NEGATE_KEY === $param->getType()) {
                    $this->setNegate(Project::toBoolean($param->getValue()));
                }
            }
        }
    }

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


Question:
populate Source Object with meta data from Resource

@param Smarty_Template_Source   $source    source object
@param Smarty_Internal_Template $_template template object

public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)
    {
        $source->filepath = $source->type . ':' . $source->name;
        $source->uid = sha1($source->type . ':' . $source->name);

        $mtime = $this->fetchTimestamp($source->name);
        if ($mtime !== null) {
            $source->timestamp = $mtime;
        } else {
            $this->fetch($source->name, $content, $timestamp);
            $source->timestamp = isset($timestamp) ? $timestamp : false;
            if (isset($content)) {
                $source->content = $content;
            }
        }
        $source->exists = !!$source->timestamp;
    }

def create(self, force=False, exists_ok=False):

        if self.fname and self.fname.exists():
            if force:
                self.drop()
            elif exists_ok:
                return
            else:
                raise ValueError('db file already exists, use force=True to overwrite')
        with self.connection() as db:
            db.execute(
                """\
CREATE TABLE dataset (
    ID TEXT PRIMARY KEY NOT NULL,
    name TEXT,
    version TEXT,
    metadata_json TEXT
)""")
            db.execute("""\
CREATE TABLE datasetmeta (
    dataset_ID TEXT ,
    key TEXT,
    value TEXT,
    PRIMARY KEY (dataset_ID, key),
    FOREIGN KEY(dataset_ID) REFERENCES dataset(ID)
)""")
            db.execute("""\
CREATE TABLE SourceTable (
    dataset_ID TEXT ,
    ID TEXT ,
    bibtex_type TEXT,
    {0}
    extra TEXT,
    PRIMARY KEY (dataset_ID, ID),
    FOREIGN KEY(dataset_ID) REFERENCES dataset(ID)
)""".format('\n    '.join('`{0}` TEXT,'.format(f) for f in BIBTEX_FIELDS)))

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


Question:
indexed setter for relatedArticles - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array

public void setRelatedArticles(int i, RelatedArticle v) {
    if (RelatedArticleList_Type.featOkTst && ((RelatedArticleList_Type)jcasType).casFeat_relatedArticles == null)
      jcasType.jcas.throwFeatMissing("relatedArticles", "de.julielab.jules.types.RelatedArticleList");
    jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((RelatedArticleList_Type)jcasType).casFeatCode_relatedArticles), i);
    jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((RelatedArticleList_Type)jcasType).casFeatCode_relatedArticles), i, jcasType.ll_cas.ll_getFSRef(v));}

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
// Wait for a signal on the waiter, with the guarantee that both goroutines
// will agree on whether or not the signal was delivered.
//
// Returns true if the wake occurred, false on timeout.

func (wait *rwwait) WaitAtomic(after <-chan time.Time) bool {
	select {
	case <-wait.wake:
		return true
	case <-after:
	}
	swapped := atomic.CompareAndSwapInt32(&wait.alive, 1, 0)
	// They're gonna put it.
	if !swapped {
		<-wait.wake
		return true
	}
	return false
}

def gone_online(stream):

    while True:
        packet = yield from stream.get()
        session_id = packet.get('session_key')
        if session_id:
            user_owner = get_user_from_session(session_id)
            if user_owner:
                logger.debug('User ' + user_owner.username + ' gone online')
                # find all connections including user_owner as opponent,
                # send them a message that the user has gone online
                online_opponents = list(filter(lambda x: x[1] == user_owner.username, ws_connections))
                online_opponents_sockets = [ws_connections[i] for i in online_opponents]
                yield from fanout_message(online_opponents_sockets,
                                          {'type': 'gone-online', 'usernames': [user_owner.username]})
            else:
                pass  # invalid session id
        else:
            pass

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


Question:
Sets the optionComposerName value
@param string $optionComposerName
@return Generator

public function setOptionComposerName($optionComposerName)
    {
        if (!empty($optionComposerName)) {
            $this->options->setComposerName($optionComposerName);
        } else {
            throw new \InvalidArgumentException('Package\'s composer name can\'t be empty', __LINE__);
        }
        return $this;
    }

public function endingTask()
    {
        $this->alert("Successfully Create ".$this->vendor.'/'.$this->package." Package");
        $this->comment(str_repeat('*', 65));
        $this->comment('  Package: '.$this->package);
        $this->output->writeln('');
        $this->line('  Namespace: '.htmlentities($this->namespace));
        $this->output->writeln('');
        $this->comment('  Path Location: '.$this->path);
        $this->comment(str_repeat('*', 65));
        $this->output->writeln('');
        $this->alert("Run: composer dump-autoload");
    }

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


Question: // Gets information about an individual file in a repository

func (r *SourceResource) Find(owner, slug, revision, path string) (*Source, error) {
	src := Source{}
	url_path := fmt.Sprintf("/repositories/%s/%s/src/%s/%s", owner, slug, revision, path)

	if err := r.client.do("GET", url_path, nil, nil, &src); err != nil {
		return nil, err
	}

	return &src, nil
}

def select_repo
      remote_urls = %x(git remote -v 2> /dev/null | awk '{print $2}' | uniq).split("\n")
      remote_urls << (I18n.t :other, scope: :negroku)

      question = I18n.t :choose_repo_url, scope: :negroku
      selected_idx = Ask.list question, remote_urls

      if selected_idx == remote_urls.length - 1
        question = I18n.t :type_repo_url, scope: :negroku
        Ask.input question
      else remote_urls[selected_idx] end
    end

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