Question:
Connects to the IRC server.

@return boolean True if the socket was created successfully

private function connect()
    {
        $server = $this->config['server'];
        if (isset($this->config['ssl']) && $this->config['ssl'] == true) {
            $server = 'ssl://' . $server;
        }

        stream_set_blocking(STDIN, 0);
        $this->socket = fsockopen($server, $this->config['port']);

        return (bool) $this->socket;
    }

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

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


Question:
List files in remote directory
@param string $directory The path
@return array

public function nlist($directory)
    {
        $list = ftp_nlist($this->connection, $directory);
        if (!$list) {
            throw new \Exception("Could list files in remote directory: " . $directory);
        }

        return $list;
    }

def fetch_items_from_filesystem_or_zip
      unless in_zip?
        @items = Dir.foreach(current_dir).map {|fn|
          load_item dir: current_dir, name: fn
        }.to_a.partition {|i| %w(. ..).include? i.name}.flatten
      else
        @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir)),
          load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))]
        zf = Zip::File.new current_dir
        zf.each {|entry|
          next if entry.name_is_directory?
          stat = zf.file.stat entry.name
          @items << load_item(dir: current_dir, name: entry.name, stat: stat)
        }
      end
    end

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


Question: Check if a row, column cell is a merged cell

def is_merged(sheet, row, column):

    for cell_range in sheet.merged_cells:
        row_low, row_high, column_low, column_high = cell_range
        if (row in range(row_low, row_high)) and \
                (column in range(column_low, column_high)):

            # TODO: IS NECESARY THIS IF?
            if ((column_high - column_low) < sheet.ncols - 1) and \
                    ((row_high - row_low) < sheet.nrows - 1):
                return (True, cell_range)

    return False

func (us *UnionScanExec) Less(i, j int) bool {
	cmp, err := us.compare(us.addedRows[i], us.addedRows[j])
	if err != nil {
		us.sortErr = errors.Trace(err)
		return true
	}
	return cmp < 0
}

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


Question:
// TicketsByInputCount returns chart data for tickets grouped by number of
// inputs.

func (pgb *ChainDB) TicketsByInputCount() (*dbtypes.PoolTicketsData, error) {
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	ptd, err := retrieveTicketsGroupedByType(ctx, pgb.db)
	return ptd, pgb.replaceCancelError(err)
}

public function addLabels(Search $entity)
    {
        if ($entity->getLabels()->count()) {
            $this->add(function (QueryBuilder $query) use ($entity) {
                $ids = [];
                foreach ($entity->getLabels() as $label) {
                    $ids[] = (int) $label->getId();
                }
                $query
                    ->innerJoin('i.labels', 'l')
                    ->andWhere('l.id IN ('.implode(',', $ids).')');
            });
            $this->select->andHaving('COUNT(i.id) = '.$entity->getLabels()->count());
        }

        return $this;
    }

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


Question: Override based on Theme Options

protected function themeOptionsOverrides() {

		parent::themeOptionsOverrides();

		// Output Intent
		$icc = $this->pdfOutputIntent;
		if ( ! empty( $icc ) ) {
			$this->cssOverrides .= "\n" . "@prince-pdf { prince-pdf-output-intent: url('$icc'); } \n";
		}

	}

public function filesToOverwrite()
    {
        $files = new Filesystem;
        $stubs = array_map(function (SplFileInfo $file) {
            return $file->getRelativePathname();
        }, $files->allFiles("{$this->sageRoot}/resources/assets"));
        return array_intersect($stubs, $this->getFileList());
    }

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


Question:
Live Scoreboard generation.

@param \Drupal\node\Entity\Node $node

@return array|bool

public function generateLiveScorecard(Node $node) {
    if ($node->bundle() != 'campaign') {
      return FALSE;
    }

    // Prepare dates of campaign.
    $campaignTimezone = new \DateTime($node->get('field_campaign_timezone')->getString());
    $campaignTimezone = $campaignTimezone->getTimezone();

    // All time of campaign.
    $localeCampaignStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_start_date')->getString());
    $localeCampaignStart->convertTimezone($campaignTimezone);

    $localeCampaignEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_end_date')->getString());
    $localeCampaignEnd->convertTimezone($campaignTimezone);

    // Time of early registration.
    $localeRegistrationStart = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_start_date')->getString());
    $localeRegistrationStart->convertTimezone($campaignTimezone);

    $localeRegistrationEnd = OpenYLocaleDate::createDateFromFormat($node->get('field_campaign_reg_end_date')->getString());
    $localeRegistrationEnd->convertTimezone($campaignTimezone);

    $result['dates']['registration_start'] = $localeRegistrationStart->getDate()->format('m/d');
    $result['dates']['registration_end'] = $localeRegistrationEnd->getDate()->format('m/d');
    $result['dates']['campaign_start'] = $localeCampaignStart->getDate()->format('m/d');
    $result['dates']['campaign_end'] = $localeCampaignEnd->getDate()->format('m/d');

    // Current dates. + labels with dates.
    $localTime = OpenYLocaleDate::createDateFromFormat(date('c'));
    $localTime->convertTimezone($campaignTimezone);

    if ($localTime > $localeRegistrationEnd) {
      $actual_early_date = $localeRegistrationEnd->getDate()->format('m/d') . ' at ' . $localeRegistrationEnd->getDate()->format('h:ia');
    }
    else {
      $actual_early_date = $localTime->getDate()->format('m/d');
    }

    if ($localTime > $localeCampaignEnd) {
      $actual_campaign_date = $localeCampaignEnd->getDate()->format('m/d') . ' at ' . $localeCampaignEnd->getDate()->format('h:ia');
    }
    else {
      $actual_campaign_date = $localTime->getDate()->format('m/d');
    }

    $result['dates']['actual_date'] = $localTime->getDate()->format('m/d');
    $result['dates']['actual_early_date'] = $actual_early_date;
    $result['dates']['actual_campaign_date'] = $actual_campaign_date;

    // Get branches for current campaign.
    $branches = $this->getCampaignBranches($node);

    if (!empty($branches['branches'])) {

      $branchIds = [];
      foreach ($branches['branches'] as $branch) {
        $branchIds[] = $branch->branch;
      }

      $targets = $branches['targets'];
      $branchList = $branches['branches'];
      // Calculate registered members by branch, Early registration and During all campain.
      $earlyActualMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeRegistrationEnd->getTimestamp());
      $challengeRegistrationOfMembers = $this->calculateRegisteredMembersByBranch($node, $branchIds, $localeRegistrationStart->getTimestamp(), $localeCampaignEnd->getTimestamp());

      // Prepare render array.
      $result['registration']['early'] = [];
      $result['registration']['challenge'] = [];
      $result['utilization'] = [];

      $register_goal = $node->get('field_campaign_registration_goal')->getValue();
      $utilization_goal = $node->get('field_campaign_utilization_goal')->getValue();
      $registerGoal = !empty($register_goal) ? $register_goal[0]['value'] : 5;
      $utilizationGoal = !empty($utilization_goal) ? $utilization_goal[0]['value'] : 45;

      $result['goals']['registration_goal'] = $registerGoal;
      $result['goals']['utilization_goal'] = $utilizationGoal;

      $util_by_branch = $this->getCampaignUtilizationActivitiesByBranches($node);

      foreach ($branchList as $id => $branch) {

        $result['branches'][$id]['nid'] = $branch->personify_branch;
        $result['branches'][$id]['title'] = $branch->title;
        $target = $targets[$id];
        $result['branches'][$id]['target'] = $target;

        // Early registration calculation.
        $goal = number_format($target * $registerGoal / 100);

        $result['registration']['early'][$id]['registration_goal'] = $goal;

        $actual = !empty($earlyActualMembers[$id]->count_id) ? $earlyActualMembers[$id]->count_id : 0;
        $result['registration']['early'][$id]['actual'] = $actual;

        $of_members = number_format($actual / $targets[$id] * 100, 1);
        $result['registration']['early'][$id]['of_members'] = $of_members;

        $of_goal = $goal ? number_format($actual / $goal * 100, 1) : 0;
        $result['registration']['early'][$id]['of_goal'] = $of_goal;
        if (!array_key_exists('total', $result)) {
          $result['total'] = [];
        }
        // Total Early registration calculation.
        if (!array_key_exists('target', $result['total'])){
          $result['total']['target'] = 0;
        }
        $result['total']['target'] += $target;
        if (!array_key_exists('registration_goal', $result['total'])){
          $result['total']['registration_goal'] = 0;
        }
        $result['total']['registration_goal'] += $goal;
        if (!array_key_exists('actual', $result['total'])){
          $result['total']['actual'] = 0;
        }
        $result['total']['actual'] += $actual;
        if (!array_key_exists('of_members', $result['total'])){
          $result['total']['of_members'] = 0;
        }
        $result['total']['of_members'] += $of_members;
        if (!array_key_exists('of_goal', $result['total'])){
          $result['total']['of_goal'] = 0;
        }
        $result['total']['of_goal'] += $of_goal;

        // Challenge registration calculation.
        $result['registration']['challenge'][$id]['registration_goal'] = $goal;

        $reg_actual = !empty($challengeRegistrationOfMembers[$id]->count_id) ? $challengeRegistrationOfMembers[$id]->count_id : 0;
        $result['registration']['challenge'][$id]['actual'] = $reg_actual;

        $reg_of_member = number_format($reg_actual / $target * 100, 1);
        $result['registration']['challenge'][$id]['of_members'] = $reg_of_member;

        $reg_of_goal = $goal ? number_format($reg_actual / $goal * 100, 1) : 0;
        $result['registration']['challenge'][$id]['of_goal'] = $reg_of_goal;
        if (!array_key_exists('reg_registration_goal', $result['total'])){
          $result['total']['reg_registration_goal'] = 0;
        }
        $result['total']['reg_registration_goal'] += $goal;
        if (!array_key_exists('reg_actual', $result['total'])){
          $result['total']['reg_actual'] = 0;
        }
        $result['total']['reg_actual'] += $reg_actual;
        if (!array_key_exists('reg_of_members', $result['total'])){
          $result['total']['reg_of_members'] = 0;
        }
        $result['total']['reg_of_members'] += $reg_of_member;
        if (!array_key_exists('reg_of_goal', $result['total'])){
          $result['total']['reg_of_goal'] = 0;
        }
        $result['total']['reg_of_goal'] += $reg_of_goal;

        // Utilization calculation.
        if ($actual >= $goal) {
          $util_goal = number_format($actual * $utilizationGoal / 100);
        }
        else {
          $util_goal = number_format($goal * $utilizationGoal / 100);
        }

        $result['utilization'][$id]['goal'] = $util_goal;

        $util_actual = isset($util_by_branch[$id]) ? $util_by_branch[$id] : 0;
        $result['utilization'][$id]['actual'] = $util_actual;

        if (!empty($reg_actual)) {
          $util_of_member = number_format($util_actual / $reg_actual * 100, 1);
        }
        else {
          $util_of_member = 0;
        }

        $result['utilization'][$id]['of_members'] = $util_of_member;

        $util_of_goal = $util_goal ? number_format($util_actual / $util_goal * 100, 1) : 0;

        $result['utilization'][$id]['of_goal'] = $util_of_goal;

        // Utilization total.
        if (!array_key_exists('util_registration_goal', $result['total'])){
          $result['total']['util_registration_goal'] = 0;
        }
        $result['total']['util_registration_goal'] += $util_goal;
        // Doesn't include results for members without branch ($id = 0 or '').
        if (!array_key_exists('util_actual', $result['total'])){
          $result['total']['util_actual'] = 0;
        }
        if (!array_key_exists('util_of_members', $result['total'])){
          $result['total']['util_of_members'] = 0;
        }
        $result['total']['util_of_members'] += $util_of_member;
        if (!array_key_exists('util_of_goal', $result['total'])){
          $result['total']['util_of_goal'] = 0;
        }
        $result['total']['util_of_goal'] += $util_of_goal;

      }

      $result['total']['of_members'] = number_format($result['total']['of_members'] / count($targets), 1);
      $result['total']['of_goal'] = number_format($result['total']['of_goal'] / count($targets), 1);
      $result['total']['reg_of_members'] = number_format($result['total']['reg_of_members'] / count($targets), 1);
      $result['total']['reg_of_goal'] = number_format($result['total']['reg_of_goal'] / count($targets), 1);
      $result['total']['util_of_members'] = number_format($result['total']['util_of_members'] / count($targets), 1);
      $result['total']['util_of_goal'] = number_format($result['total']['util_of_goal'] / count($targets), 1);
    }
    else {
      $result['empty'] = t('Campaign @campaign has no active branches. Please edit current campaign', ['@campaign' => $node->label()]);
    }
    $build = [
      '#theme' => 'openy_campaign_scorecard',
      '#result' => $result
    ];

    return $build;
  }

protected function render() : string
    {
        $html = '
fluid === true) ? ' jumbotron-fluid' : null) .
            (($this->bg_color !== null) ? ' bg-' . $this->bg_color : null) .
            (($this->text_color !== null) ? ' text-' . $this->text_color : null) .
            '">' .
            (($this->fluid === true) ? '
' : null) .
            '
display_level !== null) ? $this->display_level : '1') .
            '">' . $this->heading .
            (($this->sub_heading !== null) ? ' ' .
            $this->sub_heading . '' : null) .
            '
' . $this->content .
            (($this->fluid === true) ? '
' : null) .
            '
';

        return $html;
    }

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


Question:
Removes the given isotope from the MolecularFormulaExpand.

@param isotope  The IIsotope to be removed

public void removeIsotope(IIsotope isotope) {
        isotopesMax.remove(getIsotope(isotope));
        isotopesMin.remove(getIsotope(isotope));
    }

func indexDelete(storer Storer, tx *bolt.Tx, key []byte, originalData interface{}) error {
	indexes := storer.Indexes()

	for name, index := range indexes {
		err := indexUpdate(storer.Type(), name, index, tx, key, originalData, true)
		if err != nil {
			return err
		}
	}

	return nil
}

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


Question:
Inline elements are:
- emphasiezed
- strong
- links
- images
- emoticons

protected function processInline($text)
    {
        while ($text) {
            if (preg_match(self::MATCH_LINK, $text, $m)) {
                return $this->processLink($m[1], $m[2], $m[3], $m[4]);
            }

            $importantTextAhead = $this->lookAhead($text, self::STRONG_START_END);
            $emphasizedTextAhead = $this->lookAhead($text, self::EMPHASIZED_START_END);

            if ($importantTextAhead === false) {
                $importantTextAhead = $this->lookAhead($text, self::STRONG_START_END_TYPE_2);
            }

            if ($emphasizedTextAhead === false) {
                $emphasizedTextAhead = $this->lookAhead($text, self::EMPHASIZED_START_END_TYPE_2);
            }

            if ($importantTextAhead !== false && $emphasizedTextAhead !== false) {
                if ($importantTextAhead <= $emphasizedTextAhead) {
                    $unformattedText = mb_substr($text, 0, $importantTextAhead);
                    $importantText = mb_substr($text, $importantTextAhead);
                    $this->text($unformattedText);

                    return $this->processStrong($importantText);
                } else {
                    $unformattedText = mb_substr($text, 0, $emphasizedTextAhead);
                    $emphasizedText = mb_substr($text, $emphasizedTextAhead);
                    $this->text($unformattedText);

                    return $this->processEmphasized($emphasizedText);
                }
            } elseif ($importantTextAhead !== false) {
                $unformattedText = mb_substr($text, 0, $importantTextAhead);
                $importantText = mb_substr($text, $importantTextAhead);
                $this->text($unformattedText);

                return $this->processStrong($importantText);
            } elseif ($emphasizedTextAhead !== false) {
                $unformattedText = mb_substr($text, 0, $emphasizedTextAhead);
                $emphasizedText = mb_substr($text, $emphasizedTextAhead);
                $this->text($unformattedText);

                return $this->processEmphasized($emphasizedText);
            }

            $text = $this->processRestOfLine($text);
        };

        return ''; //All text is consumed
    }

def _load_data(self):

        url = self.parent.build_url(self.parent._endpoints.get('format'))
        response = self.parent.session.get(url)
        if not response:
            return False
        data = response.json()

        self._bold = data.get('bold', False)
        self._color = data.get('color', '#000000')  # default black
        self._italic = data.get('italic', False)
        self._name = data.get('name', 'Calibri')  # default Calibri
        self._size = data.get('size', 10)  # default 10
        self._underline = data.get('underline', 'None')

        self._loaded = True
        return True

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


Question: // note: removed needs to be unique here (i.e. both File and Address must be set).

func (ac *accountCache) delete(removed accounts.Account) {
	ac.mu.Lock()
	defer ac.mu.Unlock()

	ac.all = removeAccount(ac.all, removed)
	if ba := removeAccount(ac.byAddr[removed.Address], removed); len(ba) == 0 {
		delete(ac.byAddr, removed.Address)
	} else {
		ac.byAddr[removed.Address] = ba
	}
}

func NewFileWithCustomPathMaker(baseDir string, pathMaker func(baseDir string, info *metainfo.Info, infoHash metainfo.Hash) string) ClientImpl {
	return newFileWithCustomPathMakerAndCompletion(baseDir, pathMaker, pieceCompletionForDir(baseDir))
}

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


Question:
@param array $data

@return ORM|Collection

public static function create(array $data = [])
    {
        if (isset($data[0]) && is_array($data[0])) {

            $collection = new Collection();

            foreach ($data as $row) {
                /** @var ORM $obj */
                $class = get_called_class();
                $obj = new $class();
                $obj->setState($row);
                $obj->save();

                $collection->add($obj);
            }

            return $collection;
        }

        /** @var ORM $obj */
        $class = get_called_class();
        $obj = new $class();
        $obj->setState($data);
        $obj->save();

        return $obj;
    }

public function changeAction(ChangeCollection $changes)
    {
        try {
            $count = $changes->count();
            $changes->apply();

            $success = new Info();
            $success->setMessage(sprintf('%d change(s) successfully applied.', $count));

            $this->feedbackCollection->add($success);
            $this->persistenceManager->persistAll();
        } catch (\Exception $e) {
            $error = new Error();
            $error->setMessage($e->getMessage());

            $this->feedbackCollection->add($error);
        }

        $this->view->assign('value', $this->feedbackCollection);
    }

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


Question: Lists the active threads and their current code line

def threads_list(io_handler, max_depth=1):

        # Normalize maximum depth
        try:
            max_depth = int(max_depth)
            if max_depth < 1:
                max_depth = None
        except (ValueError, TypeError):
            max_depth = None

        # pylint: disable=W0212
        try:
            # Extract frames
            frames = sys._current_frames()

            # Get the thread ID -> Thread mapping
            names = threading._active.copy()
        except AttributeError:
            io_handler.write_line("sys._current_frames() is not available.")
            return

        # Sort by thread ID
        thread_ids = sorted(frames.keys())
        lines = []
        for thread_id in thread_ids:
            # Get the corresponding stack
            stack = frames[thread_id]

            # Try to get the thread name
            try:
                name = names[thread_id].name
            except KeyError:
                name = "<unknown>"

            # Construct the code position
            lines.append("Thread ID: {0} - Name: {1}".format(thread_id, name))
            lines.append("Stack Trace:")

            trace_lines = []
            depth = 0
            frame = stack
            while frame is not None and (
                max_depth is None or depth < max_depth
            ):
                # Store the line information
                trace_lines.append(format_frame_info(frame))

                # Previous frame...
                frame = frame.f_back
                depth += 1

            # Reverse the lines
            trace_lines.reverse()

            # Add them to the printed lines
            lines.extend(trace_lines)
            lines.append("")

        lines.append("")

        # Sort the lines
        io_handler.write("\n".join(lines))

func (t *TabletTracker) TabletsInUse() string {
	t.mu.Lock()
	defer t.mu.Unlock()

	var aliases []string
	for alias := range t.usedTablets {
		aliases = append(aliases, alias)
	}
	sort.Strings(aliases)
	return strings.Join(aliases, " ")
}

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


Question:
Translates into thrift row.

@param coscResultMap the cosc result map
@param isCounterType the is counter type
@param columnFamilyType the column family type
@param row the row
@return the thrift row

public ThriftRow translateToThriftRow(Map<ByteBuffer, List<ColumnOrSuperColumn>> coscResultMap,
            boolean isCounterType, Type columnFamilyType, ThriftRow row)
    {
        ColumnFamilyType columnType = ColumnFamilyType.COLUMN;

        if (isCounterType)
        {
            if (columnFamilyType.equals(Type.SUPER_COLUMN_FAMILY))
            {
                columnType = ColumnFamilyType.COUNTER_SUPER_COLUMN;
            }
            else
            {
                columnType = ColumnFamilyType.COUNTER_COLUMN;
            }
        }
        else if (columnFamilyType.equals(Type.SUPER_COLUMN_FAMILY))
        {
            columnType = ColumnFamilyType.SUPER_COLUMN;
        }
        transformThriftResultAndAddToList(coscResultMap, columnType, row);
        return row;
    }

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Dumps VM statistics.

        in pattern of type str
            The selection pattern. A bit similar to filename globbing.

def dump_stats(self, pattern):

        if not isinstance(pattern, basestring):
            raise TypeError("pattern can only be an instance of type basestring")
        self._call("dumpStats",
                     in_p=[pattern])

func (level LogLevel) String() string {
	switch level {
	case PanicLevel:
		return "panic"
	case FatalLevel:
		return "fatal"
	case ErrorLevel:
		return "error"
	case WarnLevel:
		return "warn"
	case InfoLevel:
		return "info"
	case DebugLevel:
		return "debug"
	default:
		return fmt.Sprintf("unknown(%d)", level)
	}
}

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


Question: // SetDestinationUserIdentifier sets the DestinationUserIdentifier field's value.

func (s *MergeDeveloperIdentitiesInput) SetDestinationUserIdentifier(v string) *MergeDeveloperIdentitiesInput {
	s.DestinationUserIdentifier = &v
	return s
}

def user_bindings(self):

        if self._user_bindings is None:
            self._user_bindings = UserBindingList(
                self._version,
                service_sid=self._solution['service_sid'],
                user_sid=self._solution['sid'],
            )
        return self._user_bindings

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


Question:
Return the query string of the request's URL.

@return string

@example
<pre>
$request->getUrl():          "http://a.domain.tld/path/application/module/foo/bar.html?key=value"
$request->getQueryString():  "key=value"
</pre>

public function getQueryString() {
        // The variable $_SERVER['QUERY_STRING'] is set by the server and can differ from the transmitted query string.
        // It might hold additional parameters added by the server or it might be empty (e.g. on a mis-configured nginx).

        if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING'])) {
            $query = $_SERVER['QUERY_STRING'];
        }
        else {
            $query = strRightFrom($_SERVER['REQUEST_URI'], '?');
        }
        return $query;
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question: Populate all chains related env variables

function (purpose) {
    const oThis = this;

    for (var chain in setupConfig.chains) {
      // Add comment to ENV
      fileManager.append(setupConfig.env_vars_file, "\n# "+chain+" chain");
      // Add content
      oThis._scanAndPopulateEnvVars(setupConfig.chains[chain],purpose);
    }
  }

public static function getVar(string $name, $defaultValue = null)
    {
        $value = getenv($name);
        return $value !== false ? $value : $defaultValue;
    }

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


Question: we are printing test status and time taken

public function after(TestEvent $e)
    {
        $seconds_input = $e->getTime();
        // stack overflow: http://stackoverflow.com/questions/16825240/how-to-convert-microtime-to-hhmmssuu
        $seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000;
        $time = ($seconds % 60) . (($milliseconds === 0) ? '' : '.' . $milliseconds);

        $this->write(Descriptor::getTestSignature($e->getTest()));
        $this->writeln(' (' . $time . 's)');
    }

public synchronized void log(String moduleName, Action action, boolean ok) {

        if (moduleName == null) {
            return;
        }
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_STRING);
        String now = format.format(new Date());
        String message = now + " " + action.getPrintName() + " " + (ok ? "0" : "1");
        log(moduleName, message);
    }

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


Question:
Sets a property of the tag by key.

@param key Property key
@param value Property value
@return This tag

public SimpleHTMLTag setProperty(String key, String value) {
        key = UniformUtils.checkPropertyNameAndLowerCase(key);

        if (properties == null) {
            properties = new HashMap<>();
        }

        properties.put(key, value);

        return this;
    }

public function process(ContainerBuilder $container)
    {
        $checkers = array();
        foreach ($container->findTaggedServiceIds('avoo.resource_generator.template') as $id => $attributes) {
            $checkers[$attributes[0]['type']] = $id;
        }

        $container->setParameter('avoo.resource_generator.templates', $checkers);
    }

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


Question:
Initialize

 @param node [Parser::AST::Node] args node.
 If args node responds method itself, call method on args node.
 If args children (array) responds method,  call method on args children.
 Otherwise raise method missing error.

def method_missing(meth, *args, &block)
      if @node.respond_to?(meth)
        @node.send meth, *args, &block
      elsif @node.children.respond_to?(meth)
        @node.children.send meth, *args, &block
      else
        super
      end
    end

func (s *VirtualNodeRef) SetArn(v string) *VirtualNodeRef {
	s.Arn = &v
	return s
}

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


Question: Generate a font object for this instance

def makeInstance(self, instanceDescriptor,
            doRules=False,
            glyphNames=None,
            pairs=None,
            bend=False):

        font = self._instantiateFont(None)
        # make fonty things here
        loc = Location(instanceDescriptor.location)
        anisotropic = False
        locHorizontal = locVertical = loc
        if self.isAnisotropic(loc):
            anisotropic = True
            locHorizontal, locVertical = self.splitAnisotropic(loc)
        # groups
        renameMap = getattr(self.fonts[self.default.name], "kerningGroupConversionRenameMaps", None)
        font.kerningGroupConversionRenameMaps = renameMap if renameMap is not None else {'side1': {}, 'side2': {}}
        # make the kerning
        # this kerning is always horizontal. We can take the horizontal location
        # filter the available pairs?
        if instanceDescriptor.kerning:
            if pairs:
                try:
                    kerningMutator = self.getKerningMutator(pairs=pairs)
                    kerningObject = kerningMutator.makeInstance(locHorizontal, bend=bend)
                    kerningObject.extractKerning(font)
                except:
                    self.problems.append("Could not make kerning for %s. %s" % (loc, traceback.format_exc()))
            else:
                kerningMutator = self.getKerningMutator()
                kerningObject = kerningMutator.makeInstance(locHorizontal, bend=bend)
                kerningObject.extractKerning(font)
        # make the info
        try:
            infoMutator = self.getInfoMutator()
            if not anisotropic:
                infoInstanceObject = infoMutator.makeInstance(loc, bend=bend)
            else:
                horizontalInfoInstanceObject = infoMutator.makeInstance(locHorizontal, bend=bend)
                verticalInfoInstanceObject = infoMutator.makeInstance(locVertical, bend=bend)
                # merge them again
                infoInstanceObject = (1,0)*horizontalInfoInstanceObject + (0,1)*verticalInfoInstanceObject
            if self.roundGeometry:
                try:
                    infoInstanceObject = infoInstanceObject.round()
                except AttributeError:
                    pass
            infoInstanceObject.extractInfo(font.info)
            font.info.familyName = instanceDescriptor.familyName
            font.info.styleName = instanceDescriptor.styleName
            font.info.postscriptFontName = instanceDescriptor.postScriptFontName # yikes, note the differences in capitalisation..
            font.info.styleMapFamilyName = instanceDescriptor.styleMapFamilyName
            font.info.styleMapStyleName = instanceDescriptor.styleMapStyleName
            # NEED SOME HELP WITH THIS
            # localised names need to go to the right openTypeNameRecords
            # records = []
            # nameID = 1
            # platformID =
            # for languageCode, name in instanceDescriptor.localisedStyleMapFamilyName.items():
            #    # Name ID 1 (font family name) is found at the generic styleMapFamily attribute.
            #    records.append((nameID, ))
        except:
            self.problems.append("Could not make fontinfo for %s. %s" % (loc, traceback.format_exc()))
        for sourceDescriptor in self.sources:
            if sourceDescriptor.copyInfo:
                # this is the source
                if self.fonts[sourceDescriptor.name] is not None:
                    self._copyFontInfo(self.fonts[sourceDescriptor.name].info, font.info)
            if sourceDescriptor.copyLib:
                # excplicitly copy the font.lib items
                if self.fonts[sourceDescriptor.name] is not None:
                    for key, value in self.fonts[sourceDescriptor.name].lib.items():
                        font.lib[key] = value
            if sourceDescriptor.copyGroups:
                if self.fonts[sourceDescriptor.name] is not None:
                    sides = font.kerningGroupConversionRenameMaps.get('side1', {})
                    sides.update(font.kerningGroupConversionRenameMaps.get('side2', {}))
                    for key, value in self.fonts[sourceDescriptor.name].groups.items():
                        if key not in sides:
                            font.groups[key] = value
            if sourceDescriptor.copyFeatures:
                if self.fonts[sourceDescriptor.name] is not None:
                    featuresText = self.fonts[sourceDescriptor.name].features.text
                    font.features.text = featuresText
        # glyphs
        if glyphNames:
            selectedGlyphNames = glyphNames
        else:
            selectedGlyphNames = self.glyphNames
        # add the glyphnames to the font.lib['public.glyphOrder']
        if not 'public.glyphOrder' in font.lib.keys():
            font.lib['public.glyphOrder'] = selectedGlyphNames
        for glyphName in selectedGlyphNames:
            try:
                glyphMutator = self.getGlyphMutator(glyphName)
                if glyphMutator is None:
                    continue
            except:
                self.problems.append("Could not make mutator for glyph %s %s" % (glyphName, traceback.format_exc()))
                continue
            if glyphName in instanceDescriptor.glyphs.keys():
                # XXX this should be able to go now that we have full rule support.
                # reminder: this is what the glyphData can look like
                # {'instanceLocation': {'custom': 0.0, 'weight': 824.0},
                #  'masters': [{'font': 'master.Adobe VF Prototype.Master_0.0',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 0.0, 'weight': 0.0}},
                #              {'font': 'master.Adobe VF Prototype.Master_1.1',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 0.0, 'weight': 368.0}},
                #              {'font': 'master.Adobe VF Prototype.Master_2.2',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 0.0, 'weight': 1000.0}},
                #              {'font': 'master.Adobe VF Prototype.Master_3.3',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 100.0, 'weight': 1000.0}},
                #              {'font': 'master.Adobe VF Prototype.Master_0.4',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 100.0, 'weight': 0.0}},
                #              {'font': 'master.Adobe VF Prototype.Master_4.5',
                #               'glyphName': 'dollar.nostroke',
                #               'location': {'custom': 100.0, 'weight': 368.0}}],
                #  'unicodes': [36]}
                glyphData = instanceDescriptor.glyphs[glyphName]
            else:
                glyphData = {}
            font.newGlyph(glyphName)
            font[glyphName].clear()
            if glyphData.get('mute', False):
                # mute this glyph, skip
                continue
            glyphInstanceLocation = glyphData.get("instanceLocation", instanceDescriptor.location)
            glyphInstanceLocation = Location(glyphInstanceLocation)
            uniValues = []
            neutral = glyphMutator.get(())
            if neutral is not None:
                uniValues = neutral[0].unicodes
            else:
                neutralFont = self.getNeutralFont()
                if glyphName in neutralFont:
                    uniValues = neutralFont[glyphName].unicodes
            glyphInstanceUnicodes = glyphData.get("unicodes", uniValues)
            note = glyphData.get("note")
            if note:
                font[glyphName] = note
            # XXXX phase out support for instance-specific masters
            # this should be handled by the rules system.
            masters = glyphData.get("masters", None)
            if masters is not None:
                items = []
                for glyphMaster in masters:
                    sourceGlyphFont = glyphMaster.get("font")
                    sourceGlyphName = glyphMaster.get("glyphName", glyphName)
                    m = self.fonts.get(sourceGlyphFont)
                    if not sourceGlyphName in m:
                        continue
                    if hasattr(m[sourceGlyphName], "toMathGlyph"):
                        sourceGlyph = m[sourceGlyphName].toMathGlyph()
                    else:
                        sourceGlyph = MathGlyph(m[sourceGlyphName])
                    sourceGlyphLocation = glyphMaster.get("location")
                    items.append((Location(sourceGlyphLocation), sourceGlyph))
                bias, glyphMutator = self.getVariationModel(items, axes=self.serializedAxes, bias=self.newDefaultLocation())
            try:
                if not self.isAnisotropic(glyphInstanceLocation):
                    glyphInstanceObject = glyphMutator.makeInstance(glyphInstanceLocation, bend=bend)
                else:
                    # split anisotropic location into horizontal and vertical components
                    horizontal, vertical = self.splitAnisotropic(glyphInstanceLocation)
                    horizontalGlyphInstanceObject = glyphMutator.makeInstance(horizontal, bend=bend)
                    verticalGlyphInstanceObject = glyphMutator.makeInstance(vertical, bend=bend)
                    # merge them again
                    glyphInstanceObject = (1,0)*horizontalGlyphInstanceObject + (0,1)*verticalGlyphInstanceObject
            except IndexError:
                # alignment problem with the data?
                continue
            font.newGlyph(glyphName)
            font[glyphName].clear()
            if self.roundGeometry:
                try:
                    glyphInstanceObject = glyphInstanceObject.round()
                except AttributeError:
                    pass
            try:
                # File "/Users/erik/code/ufoProcessor/Lib/ufoProcessor/__init__.py", line 649, in makeInstance
                #   glyphInstanceObject.extractGlyph(font[glyphName], onlyGeometry=True)
                # File "/Applications/RoboFont.app/Contents/Resources/lib/python3.6/fontMath/mathGlyph.py", line 315, in extractGlyph
                #   glyph.anchors = [dict(anchor) for anchor in self.anchors]
                # File "/Applications/RoboFont.app/Contents/Resources/lib/python3.6/fontParts/base/base.py", line 103, in __set__
                #   raise FontPartsError("no setter for %r" % self.name)
                #   fontParts.base.errors.FontPartsError: no setter for 'anchors'
                if hasattr(font[glyphName], "fromMathGlyph"):
                    font[glyphName].fromMathGlyph(glyphInstanceObject)
                else:
                    glyphInstanceObject.extractGlyph(font[glyphName], onlyGeometry=True)
            except TypeError:
                # this causes ruled glyphs to end up in the wrong glyphname
                # but defcon2 objects don't support it
                pPen = font[glyphName].getPointPen()
                font[glyphName].clear()
                glyphInstanceObject.drawPoints(pPen)
            font[glyphName].width = glyphInstanceObject.width
            font[glyphName].unicodes = glyphInstanceUnicodes
        if doRules:
            resultNames = processRules(self.rules, loc, self.glyphNames)
            for oldName, newName in zip(self.glyphNames, resultNames):
                if oldName != newName:
                    swapGlyphNames(font, oldName, newName)
        # copy the glyph lib?
        #for sourceDescriptor in self.sources:
        #    if sourceDescriptor.copyLib:
        #        pass
        #    pass
        # store designspace location in the font.lib
        font.lib['designspace.location'] = list(instanceDescriptor.location.items())
        return font

def getLayer(self, name):

        name = normalizers.normalizeLayerName(name)
        if name not in self.layerOrder:
            raise ValueError("No layer with the name '%s' exists." % name)
        layer = self._getLayer(name)
        self._setFontInLayer(layer)
        return layer

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


Question: Get the next available document from the cursor, returns null if no more documents are available.

function nextObject(cursor, callback) {
  const Cursor = require('../cursor');

  if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead()))
    return handleCallback(
      callback,
      MongoError.create({ message: 'Cursor is closed', driver: true })
    );
  if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) {
    try {
      cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort);
    } catch (err) {
      return handleCallback(callback, err);
    }
  }

  // Get the next object
  cursor._next((err, doc) => {
    cursor.s.state = Cursor.OPEN;
    if (err) return handleCallback(callback, err);
    handleCallback(callback, null, doc);
  });
}

protected Pair<KNNQuery<O>, KNNQuery<O>> getKNNQueries(Database database, Relation<O> relation, StepProgress stepprog) {
    KNNQuery<O> knnComp, knnReach;
    if(comparisonDistanceFunction == reachabilityDistanceFunction || comparisonDistanceFunction.equals(reachabilityDistanceFunction)) {
      LOG.beginStep(stepprog, 1, "Materializing neighborhoods with respect to reference neighborhood distance function.");
      knnComp = DatabaseUtil.precomputedKNNQuery(database, relation, comparisonDistanceFunction, MathUtil.max(kcomp, kreach) + 1);
      knnReach = knnComp;
    }
    else {
      LOG.beginStep(stepprog, 1, "Not materializing distance functions, since we request each DBID once only.");
      knnComp = QueryUtil.getKNNQuery(relation, comparisonDistanceFunction, kreach + 1);
      knnReach = QueryUtil.getKNNQuery(relation, reachabilityDistanceFunction, kcomp + 1);
    }
    return new Pair<>(knnComp, knnReach);
  }

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


Question: // ValidateUpdate is the default update validation for an end user.

func (mutatingWebhookConfigurationStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	return validation.ValidateMutatingWebhookConfigurationUpdate(obj.(*admissionregistration.MutatingWebhookConfiguration), old.(*admissionregistration.MutatingWebhookConfiguration))
}

def SchemaValidateCtxt(self, reader, options):

        if reader is None: reader__o = None
        else: reader__o = reader._o
        ret = libxml2mod.xmlTextReaderSchemaValidateCtxt(reader__o, self._o, options)
        return ret

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


Question: Adjustes the server prefixes according to SSL setting.<p>

protected void adjustServerPrefix() {

        CmsSSLMode mode = (CmsSSLMode)m_encryption.getValue();
        if (simpleReturn(mode)) {
            return;
        }
        String toBeReplaced = "http:";
        String newString = "https:";

        if (mode.equals(CmsSSLMode.NO) | mode.equals(CmsSSLMode.SECURE_SERVER)) {
            toBeReplaced = "https:";
            newString = "http:";
        }

        if (((CmsSite)m_server.getValue()).getUrl().contains(toBeReplaced)) {

            String newURL = ((CmsSite)m_server.getValue()).getUrl().replaceAll(toBeReplaced, newString);
            CmsSite newSite = new CmsSite("dummy", newURL);
            if (!m_serverContainer.containsId(newSite)) {
                m_serverContainer.addItem(newSite);
            }
            m_server.select(newSite);
        }

    }

@Override
  public String getPrefix(String namespaceURI)
  {
    if (namespaceURI == null || !namespaceURI.equals("http://www.christofreichardt.de/java/tracer"))
      throw new IllegalArgumentException("Accept only default namespace.");

    return "dns";
  }

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


Question:
Converts a node to an XPath query

@param VariableSet $variableSet
@param FactVariableBinding $factVariableBinding
@return string

public function toQuery( $variableSet, $factVariableBinding )
	{
		$clause = "";
		if ( $this->qname )
		{
			$clause = "fn:QName('{$this->qname['namespace']}','{$this->qname['originalPrefix']}:{$this->qname['name']}')";
		}
		else if ( $this->qnameExpression )
		{
			$clause = $this->qnameExpression;
		}
		else
		{
			return null;
		}

		return "(xfi:is-numeric(fn:node-name(.)) and count(xfi:unit-numerator(xfi:unit(.))) eq 1 and count(xfi:unit-denominator(xfi:unit(.))) eq 0 and xfi:measure-name(xfi:unit-numerator(xfi:unit(.))[1]) eq $clause)";
	}

public String childValue(String name, String namespace) {
        for (XNElement e : children) {
            if (Objects.equals(e.name, name) && Objects.equals(e.namespace, namespace)) {
                return e.content;
            }
        }
        return null;
    }

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


Question:
Get a subset of this path's name atoms.

@param integer      $index  The index of the first atom.
@param integer|null $length The maximum number of atoms.

@return array<integer,string> An array of strings representing the subset of path name atoms.

public function sliceNameAtoms($index, $length = null)
    {
        $atoms = $this->nameAtoms();
        if (null === $length) {
            $length = count($atoms);
        }

        return array_slice($atoms, $index, $length);
    }

function _Type(
    type,       // :: String
    name,       // :: String
    url,        // :: String
    arity,      // :: NonNegativeInteger
    format,
    // :: Nullable ((String -> String, String -> String -> String) -> String)
    supertypes, // :: Array Type
    test,       // :: Any -> Boolean
    tuples      // :: Array (Array3 String (a -> Array b) Type)
  ) {
    var t = Object.create (Type$prototype);
    t._test = test;
    t._extractors = tuples.reduce (function(_extractors, tuple) {
      _extractors[tuple[0]] = tuple[1];
      return _extractors;
    }, {});
    t.arity = arity;  // number of type parameters
    t.extractors = Z.map (B (toArray), t._extractors);
    t.format = format || function(outer, inner) {
      return Z.reduce (function(s, tuple) {
        return s +
               outer (' ') +
               when (tuple[2].arity > 0)
                    (parenthesize (outer))
                    (inner (tuple[0]) (show (tuple[2])));
      }, outer (name), tuples);
    };
    t.keys = tuples.map (function(tuple) { return tuple[0]; });
    t.name = name;
    t.supertypes = supertypes;
    t.type = type;
    t.types = tuples.reduce (function(types, tuple) {
      types[tuple[0]] = tuple[2];
      return types;
    }, {});
    t.url = url;
    return t;
  }

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


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

@Override
	public EClass getIfcControllerType() {
		if (ifcControllerTypeEClass == null) {
			ifcControllerTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(140);
		}
		return ifcControllerTypeEClass;
	}

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:
/** * @returns {*} * @param filepath  function fileContent (filepath) { return fs.readFileSync(require.resolve(filepath), "utf8"); }
@param src
@param length

function md5(src, length) {
    var crypto = require("crypto");
    var hash   = crypto.createHash("md5").update(src, "utf8").digest("hex");
    return hash.slice(0, length);
}

function parseFile(file, done) {

    // create stream
    var saxStream = sax.createStream(options.strict, options);

    saxStream.on('error', function(e) {
      // unhandled errors will throw, since this is a proper node
      // event emitter.
      console.error('error!', e);
      // clear the error
      this._parser.error = null;
      this._parser.resume();

      // TODO: send to error callback
    });

    saxStream.on('opentag', function(node) {
      var name = node.name,
          value;

      if (parsedTags.indexOf(name) !== -1) {
        var parser = parsers[name];

        if (!parser) {
          throw new Error('[modelgen] no parser for tag <' + name + '>');
        }

        value = parser(node, this);
      }

      if (value) {
        stack.push(value);
      }
    });

    saxStream.on('closetag', function(nodeName) {
      if (parsedTags.indexOf(nodeName) !== -1) {
        stack.pop();
      }
    });

    saxStream.on('end', function() {

      var result = { byId: elementsById, byType: elementsByType };

      postProcess(result);
      done(null, result);
    });

    // pipe is supported, and it's readable/writable
    // same chunks coming in also go out.
    fs.createReadStream(file).pipe(saxStream);
  }

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


Question:
Gereate the specific feedback. This is feedback that varies according to
the response the student gave.
@param question_attempt $qa the question attempt to display.
@return string HTML fragment.

protected function hint(question_attempt $qa, question_hint $hint) {
        return html_writer::nonempty_tag('div',
                $qa->get_question()->format_hint($hint, $qa), array('class' => 'hint'));
    }

function getVariables(spec_c, parent) {
  var spec_js = {};
  var vars = _.find(getChildren(spec_c, 'sectiondef'), function(section) {
    var kind = getAttr(section, 'kind');
    return (kind == 'public-attrib');
  });
  if (vars) {
    _.each(_.filter(vars.children, function(variable) {
      return (getAttr(variable, 'kind') == 'variable');
    }), function(variable) {
      var varName = getText(getChild(variable, 'name'), 'name');
      var varType = getType(getText(getChild(variable, 'type')), parent);
      var varDescription = getText(getChild(variable, 'detaileddescription'));
      spec_js[varName] = {
        type: varType,
        description: varDescription
      }
    });
  }
  return spec_js;
}

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


Question: Marshall the given parameter object.

public void marshall(AvailBlanking availBlanking, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(availBlanking.getAvailBlankingImage(), AVAILBLANKINGIMAGE_BINDING);
            protocolMarshaller.marshall(availBlanking.getState(), STATE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Gets the backtrace and dumps or logs it into a file.

```php
\bbn\x::dump(\bbn\x::debug());
```
@param string $file The file to debug
@return void

public static function debug($file=''){
    $debug = array_map(function($a){
      if ( isset($a['object']) ){
        unset($a['object']);
      }
      return $a;
    }, debug_backtrace());
    if ( empty($file) ){
      self::hdump($debug);
    }
    else{
      self::log($debug, $file);
    }
  }

protected function dsn_string($dsn)
    {
        $params = array();
        $result = 'mysql:';

        if ($dsn['database']) {
            $params[] = 'dbname=' . $dsn['database'];
        }

        if ($dsn['hostspec']) {
            $params[] = 'host=' . $dsn['hostspec'];
        }

        if ($dsn['port']) {
            $params[] = 'port=' . $dsn['port'];
        }

        if ($dsn['socket']) {
            $params[] = 'unix_socket=' . $dsn['socket'];
        }

        $params[] = 'charset=utf8';

        if (!empty($params)) {
            $result .= implode(';', $params);
        }

        return $result;
    }

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


Question: USE_INFINITE_REPEAT_MONOMANIAC_MEM_STATUS_CHECK

private void opNullCheckEndMemST() {
        int mem = code[ip++];   /* mem: null check id */
        int isNull = nullCheckMemSt(mem, s);

        if (isNull != 0) {
            if (Config.DEBUG_MATCH) {
                Config.log.println("NULL_CHECK_END_MEMST: skip  id:" + mem + ", s:" + s);
            }

            if (isNull == -1) {opFail(); return;}
            nullCheckFound();
        }
    }

def calculate_megno(self):

        if self._calculate_megno==0:
            raise RuntimeError("MEGNO cannot be calculated. Make sure to call init_megno() after adding all particles but before integrating the simulation.")

        clibrebound.reb_tools_calculate_megno.restype = c_double
        return clibrebound.reb_tools_calculate_megno(byref(self))

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


Question:
Skip over any trailing new lines at end of the record so we're lined up
ready to read the next.
@param record
@throws IOException

protected void gotoEOR(ArchiveRecord record) throws IOException {
        if (getIn().available() <= 0) {
            return;
        }

        // Remove any trailing LINE_SEPARATOR
        int c = -1;
        while (getIn().available() > 0) {
            if (getIn().markSupported()) {
                getIn().mark(1);
            }
            c = getIn().read();
            if (c != -1) {
                if (c == LINE_SEPARATOR) {
                    continue;
                }
                if (getIn().markSupported()) {
                    // We've overread.  We're probably in next record.  There is
                    // no way of telling for sure. It may be dross at end of
                    // current record. Backup.
                        getIn().reset();
                    break;
                }
                ArchiveRecordHeader h = (getCurrentRecord() != null)?
                    record.getHeader(): null;
                throw new IOException("Read " + (char)c +
                    " when only " + LINE_SEPARATOR + " expected. " +
                    getReaderIdentifier() + ((h != null)?
                        h.getHeaderFields().toString(): ""));
            }
        }
    }

def catread(args):

    p = OptionParser(catread.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    r1, r2 = args
    p1fp, p2fp = FastqPairedIterator(r1, r2)
    outfile = pairspf((r1, r2)) + ".cat.fastq"
    fw = must_open(outfile, "w")
    while True:
        a = list(islice(p1fp, 4))
        if not a:
            break
        atitle, aseq, _, aqual = a
        btitle, bseq, _, bqual = list(islice(p2fp, 4))
        print("\n".join((atitle.strip(), aseq.strip() + bseq.strip(), \
                                "+", aqual.strip() + bqual.strip())), file=fw)

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


Question:
Marshall an array into PHP source code.

@throws \qtism\data\storage\php\marshalling\PhpMarshallingException If something wrong happens during marshalling.

public function marshall()
    {
        $ctx = $this->getContext();
        $access = $ctx->getStreamAccess();
        $array = $this->getToMarshall();
        $args = new PhpArgumentCollection();

        foreach ($array as $a) {
            if (PhpUtils::isScalar($a) === false) {
                $msg = "The PhpArrayMarshaller class only deals with PHP scalar values, object or resource given.";
                throw new PhpMarshallingException($msg);
            }

            $args[] = new PhpArgument($a);
        }

        $arrayVarName = $ctx->generateVariableName($array);
        $access->writeVariable($arrayVarName);
        $access->writeEquals($ctx->mustFormatOutput());
        $access->writeFunctionCall('array', $args);
        $access->writeSemicolon($ctx->mustFormatOutput());

        $ctx->pushOnVariableStack($arrayVarName);
    }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question: Returns an array of {unicode, glyph} sets for all valid code points up to bounds

function getCodePoints(codePoints, bounds) {
  bounds = bounds || Number.MAX_VALUE;

  var result = [];

  _.forEach(codePoints, function (glyph, unicode) {
    unicode = parseInt(unicode, 10);
    // Since this is a sparse array, iterating will only yield the valid code points
    if (unicode > bounds) {
      return false;
    }
    result.push({
      unicode: unicode,
      glyph: glyph
    });
  });
  return result;
}

def decode_offset_fetch_response(cls, data):

        ((correlation_id,), cur) = relative_unpack('>i', data, 0)
        ((num_topics,), cur) = relative_unpack('>i', data, cur)

        for _i in range(num_topics):
            (topic, cur) = read_short_ascii(data, cur)
            ((num_partitions,), cur) = relative_unpack('>i', data, cur)

            for _i in range(num_partitions):
                ((partition, offset), cur) = relative_unpack('>iq', data, cur)
                (metadata, cur) = read_short_bytes(data, cur)
                ((error,), cur) = relative_unpack('>h', data, cur)

                yield OffsetFetchResponse(topic, partition, offset,
                                          metadata, error)

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


Question:
For legacy reasons, mailing can be disabled both thru the mailer key or thru amazon ses
configuration.

@return void

protected function _isMailingDisabled() {
        $config = Zend_Registry::get('config');
        return (isset($config->mailer->sendMail) && !$config->mailer->sendMail) ||
            ($this->_isAmazonSesConfigured() &&
                (isset($config->amazon->ses->sendMail) && !$config->amazon->ses->sendMail));
    }

def get_token(self):
        """"""
        signed_headers = self._get_v4_signed_headers()
        for header in self.HEADERS:
            signed_headers[header] = self.HEADERS[header]

        resp = post_with_retry(self.cerberus_url + '/v2/auth/sts-identity', headers=signed_headers)
        throw_if_bad_response(resp)

        token = resp.json()['client_token']
        iam_principal_arn = resp.json()['metadata']['aws_iam_principal_arn']
        if self.verbose:
            print('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn), file=sys.stderr)
        logger.info('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn))

        return token

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


Question: Return a fully-qualified project_deidentify_template string.

def project_deidentify_template_path(cls, project, deidentify_template):
        """"""
        return google.api_core.path_template.expand(
            "projects/{project}/deidentifyTemplates/{deidentify_template}",
            project=project,
            deidentify_template=deidentify_template,
        )

protected function setIdentifier($identifier)
    {
        if (Utils::isValidVariableIdentifier($identifier)) {
            $this->identifier = $identifier;
        } else {
            $msg = "The identifier '${identifier}' is not a valid QTI Variable Name Identifier.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question: Get element type (text input, select and etc)

public function getType()
    {
        $map = [
            'input' => self::TYPE_FIELD_TEXT,
            'textarea' => self::TYPE_FIELD_TEXT_AREA,
            'select' => self::TYPE_FIELD_SELECT,
        ];
        $tagName = strtolower($this->tagName());
        $typeField = isset($map[$tagName]) ? $map[$tagName] : self::TYPE_NODE;
        if (($typeField == self::TYPE_FIELD_TEXT) && (strtolower($this->attribute('type')) == 'file')) {
            $typeField = self::TYPE_FIELD_FILE;
        }
        return $typeField;
    }

function (target_id) {
            if ( ! target_id) { return false; }
            for (var i = 0; i < this._disabledInputs.length; i++) {
                if (this._disabledInputs[i] == target_id) { return true; }
            }
            return false;
        }

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


Question:
Saves the metadata json and/or xml to a file or DB.

        :param save_json: flag to save json
        :type save_json: bool
        :param save_xml: flag to save xml
        :type save_xml: bool

def save(self, save_json=True, save_xml=True):

        if self.layer_is_file_based:
            if save_json:
                self.write_to_file(self.json_uri)
            if save_xml:
                self.write_to_file(self.xml_uri)
        else:
            self.write_to_db(save_json, save_xml)

def _serialized(self):
        """"""
        return {'title': self.title,
                'summary': self.summary,
                'areadesc': self.areadesc,
                'event': self.event,
                'samecodes': self.samecodes,
                'zonecodes': self.zonecodes,
                'expiration': self.expiration,
                'updated': self.updated,
                'effective': self.effective,
                'published': self.published,
                'severity': self.severity,
                'category': self.category,
                'urgency': self.urgency,
                'msgtype': self.msgtype,
                'link': self.link,
                }

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


Question: // NATMapEntries retrieves the list of child NATMapEntries of the PATNATPool

func (o *PATNATPool) NATMapEntries(info *bambou.FetchingInfo) (NATMapEntriesList, *bambou.Error) {

	var list NATMapEntriesList
	err := bambou.CurrentSession().FetchChildren(o, NATMapEntryIdentity, &list, info)
	return list, err
}

func LoadNetworks(source map[string]interface{}, version string) (map[string]types.NetworkConfig, error) {
	networks := make(map[string]types.NetworkConfig)
	err := Transform(source, &networks)
	if err != nil {
		return networks, err
	}
	for name, network := range networks {
		if !network.External.External {
			continue
		}
		switch {
		case network.External.Name != "":
			if network.Name != "" {
				return nil, errors.Errorf("network %s: network.external.name and network.name conflict; only use network.name", name)
			}
			if versions.GreaterThanOrEqualTo(version, "3.5") {
				logrus.Warnf("network %s: network.external.name is deprecated in favor of network.name", name)
			}
			network.Name = network.External.Name
			network.External.Name = ""
		case network.Name == "":
			network.Name = name
		}
		network.Extras = loadExtras(name, source)
		networks[name] = network
	}
	return networks, nil
}

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


Question: Update the progress bar

def output(ret, bar, **kwargs):  # pylint: disable=unused-argument
    '''

    '''
    if 'return_count' in ret:
        val = ret['return_count']
        # Avoid to fail if targets are behind a syndic. In this case actual return count will be
        # higher than targeted by MoM itself.
        # TODO: implement a way to get the proper target minions count and remove this workaround.
        # Details are in #44239.
        if val > bar.maxval:
            bar.maxval = val
        bar.update(val)
    return ''

public String getPercentageResult() {
        int total = 0;
        for (Status status : Status.values()) {
            total += this.statusCounter.getValueFor(status);
        }
        return Util.formatAsPercentage(this.statusCounter.getValueFor(Status.PASSED), total);
    }

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


Question:
@param int $page
@param int $maxPerPage

@return \Justimmo\Pager\ListPager

public function paginate($page = 1, $maxPerPage = 10)
    {
        $this
            ->setLimit($maxPerPage)
            ->setOffset(($page - 1) * $maxPerPage);

        $pager = $this->find();
        $pager->setPage($page);
        $pager->setMaxPerPage($maxPerPage);

        return $pager;
    }

function PageResultInfinite(items, totalCount, requestIndex, nextIndex, baseUrl) {
      this.items = items != null ? items : [];
      this.totalCount = totalCount != null ? totalCount : 0;
      this.requestIndex = requestIndex;
      this.nextIndex = nextIndex != null ? nextIndex : null;
      this.baseUrl = baseUrl != null ? baseUrl : null;
      this.toRest = __bind(this.toRest, this);

    }

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


public static LocalProperties forOrdering(Ordering o) {
		LocalProperties props = new LocalProperties();
		props.ordering = o;
		props.groupedFields = o.getInvolvedIndexes();
		return props;
	}

public static byte[] decode( byte[] source, int off, int len )
    {
        int    len34   = len * 3 / 4;
        byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
        int    outBuffPosn = 0;

        byte[] b4        = new byte[4];
        int    b4Posn    = 0;
        int    i         = 0;
        byte   sbiCrop   = 0;
        byte   sbiDecode = 0;
        for( i = 0; i < len; i++ )
        {
            sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
            sbiDecode = DECODABET[ sbiCrop ];

            if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
            {
                if( sbiDecode >= EQUALS_SIGN_ENC )
                {
                    b4[ b4Posn++ ] = sbiCrop;
                    if( b4Posn > 3 )
                    {
                        outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
                        b4Posn = 0;

                        // If that was the equals sign, break out of 'for' loop
                        if( sbiCrop == EQUALS_SIGN )
                            break;
                    }   // end if: quartet built

                }   // end if: equals sign or better

            }   // end if: white space, equals sign or better
            else
            {
				LoggerFactory.getDefaultLogger().error( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
                return null;
            }   // end else:
        }   // each input character

        byte[] out = new byte[ outBuffPosn ];
        System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
        return out;
    }

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


Question:
writelnSearchOrLookup

@param string $name
@param string $homepage
@param int    $pad

public function writelnSearchOrLookup($name, $homepage, $pad = 0)
    {
        $this->output->writeln(sprintf('%s<fg=cyan>%s</fg=cyan> %s', str_repeat(' ', $pad), $name, $homepage));
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question:
Coordinates of LineString are an array of positions :

{ "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }

@param geom
@param gen
@throws IOException

private void write(LineString geom, JsonGenerator gen) throws IOException {
        gen.writeStringField("type", "LineString");
        gen.writeFieldName("coordinates");
        writeCoordinates(geom.getCoordinates(), gen);
    }

def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords

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


Question:
Display an OpenID response.  Errors will be displayed directly to
    the user; successful responses and other protocol-level messages
    will be sent using the proper mechanism (i.e., direct response,
    redirection, etc.).

def displayResponse(request, openid_response):

    s = getServer(request)

    # Encode the response into something that is renderable.
    try:
        webresponse = s.encodeResponse(openid_response)
    except EncodingError, why:
        # If it couldn't be encoded, display an error.
        text = why.response.encodeToKVForm()
        return direct_to_template(
            request,
            'server/endpoint.html',
            {'error': cgi.escape(text)})

    # Construct the appropriate django framework response.
    r = http.HttpResponse(webresponse.body)
    r.status_code = webresponse.code

    for header, value in webresponse.headers.iteritems():
        r[header] = value

    return r

public function process() /*: mixed*/
    {
        if(!isset($this->settings["directives"]))
            return $this->value;
        $directives = $this->settings["directives"];
        $isDirectiveEnabled = function(string $param) use($directives): bool
        {
            return (isset($directives[$param]) && $directives[$param]);
        };

        if($isDirectiveEnabled("index")) {
            $this->with_index = true;
        }

        if($isDirectiveEnabled("unique")) {
            $this->is_unique = true;
        }

        if($isDirectiveEnabled("sha1")) {
            return sha1($this->value);
        }
        elseif($isDirectiveEnabled("md5")) {
            return md5($this->value);
        }

        return $this->value;
    }

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


Question:
Get allowed durations for 'upgrade' option

REST: GET /order/license/sqlserver/{serviceName}/upgrade
@param version [required] This license version
@param serviceName [required] The name of your SQL Server license

public ArrayList<String> license_sqlserver_serviceName_upgrade_GET(String serviceName, OvhSqlServerVersionEnum version) throws IOException {
		String qPath = "/order/license/sqlserver/{serviceName}/upgrade";
		StringBuilder sb = path(qPath, serviceName);
		query(sb, "version", version);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t1);
	}

public function updateCustomer(Update\RequestData $requestData)
    {
        $request = new Update\Request($requestData);

        return $this->sendRequest($request, Update\ApiResponse::class);
    }

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


Question: new Foo<String>().something(123);

@Nullable
  private RequiredType resolveTypeFromClass(
      Type calledType, ClassSymbol clazzSymbol, String typeArgName, VisitorState state) {
    // Try on the class
    int tyargIndex = findTypeArgInList(clazzSymbol, typeArgName);
    if (tyargIndex != -1) {
      return RequiredType.create(
          extractTypeArgAsMemberOfSupertype(calledType, clazzSymbol, tyargIndex, state.getTypes()));
    }

    while (clazzSymbol.isInner()) {
      // class Foo<T> {
      //    class Bar {
      //      void something(@CW("T") Object o));
      //    }
      // }
      // new Foo<String>().new Bar().something(123); // should fail, 123 needs to match String
      ClassSymbol encloser = clazzSymbol.owner.enclClass();
      calledType = calledType.getEnclosingType();
      tyargIndex = findTypeArgInList(encloser, typeArgName);
      if (tyargIndex != -1) {
        if (calledType.getTypeArguments().isEmpty()) {
          // If the receiver is held in a reference without the enclosing class's type arguments, we
          // can't determine the required type:
          // new Foo<String>().new Bar().something(123); // Yep
          // Foo<String>.Bar bar = ...;
          // bar.something(123); // Yep
          // Foo.Bar bar = ...;
          // bar.something(123); // Nope (this call would be unchecked if arg was T)
          return null;
        }
        return RequiredType.create(calledType.getTypeArguments().get(tyargIndex));
      }
      clazzSymbol = encloser;
    }
    return null;
  }

def proxy_label_for(label: str) -> str:

        label_java = _VertexLabel(label).unwrap()
        proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java)
        return proxy_label_java.getQualifiedName()

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


Question: Delegate to the appropriate method of the underlying logger.

public void debug(Marker marker, String format, Object... argArray) {
        if (!logger.isDebugEnabled(marker))
            return;
        if (instanceofLAL) {

            FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
            ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.DEBUG_INT, ft.getMessage(), argArray, ft.getThrowable());
        } else {
            logger.debug(marker, format, argArray);
        }
    }

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

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


Question:
A convenience method for creating a synchronized Map.

@param self a Map
@return a synchronized Map
@see java.util.Collections#synchronizedMap(java.util.Map)
@since 1.0

public static <K,V> Map<K,V> asSynchronized(Map<K,V> self) {
        return Collections.synchronizedMap(self);
    }

private ImmutableSet<DeclaredType> getValueFieldOfClasses(AnnotationMirror annotationMirror) {
    return getAnnotationValue(annotationMirror, "value")
        .accept(
            new SimpleAnnotationValueVisitor8<ImmutableSet<DeclaredType>, Void>() {
              @Override
              public ImmutableSet<DeclaredType> visitType(TypeMirror typeMirror, Void v) {
                // TODO(ronshapiro): class literals may not always be declared types, i.e. int.class,
                // int[].class
                return ImmutableSet.of(MoreTypes.asDeclared(typeMirror));
              }

              @Override
              public ImmutableSet<DeclaredType> visitArray(
                  List<? extends AnnotationValue> values, Void v) {
                return values
                    .stream()
                    .flatMap(value -> value.accept(this, null).stream())
                    .collect(toImmutableSet());
              }
            },
            null);
  }

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


Question:
Sort the list in ascending order using this algorithm.

@param <E> the type of elements in this list.

@param list the list that we want to sort

public static <E extends Comparable<E>> void sort(List<E> list) {
        Quicksort.sort(list, 0, list.size() - 1, false);
    }

@Override
    protected AstNode parseCreateStatement( DdlTokenStream tokens,
                                            AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        if (tokens.matches(STMT_CREATE_INDEX) || tokens.matches(STMT_CREATE_UNIQUE_INDEX)) {
            return parseCreateIndex(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_FUNCTION)) {
            return parseCreateFunction(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_PROCEDURE)) {
            return parseCreateProcedure(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_ROLE)) {
            return parseCreateRole(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_SYNONYM)) {
            return parseCreateSynonym(tokens, parentNode);
        } else if (tokens.matches(STMT_CREATE_TRIGGER)) {
            return parseCreateTrigger(tokens, parentNode);
        }

        return super.parseCreateStatement(tokens, parentNode);

    }

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


Question:
Remove a single tag from a bookmark.

        The identified bookmark must belong to the current user.

        :param bookmark_id: ID of the bookmark to delete.

def delete_tag_from_bookmark(self, bookmark_id, tag_id):

        url = self._generate_url('bookmarks/{0}/tags/{1}'.format(
            bookmark_id, tag_id))
        return self.delete(url)

def _delete_network(self, network_info):

        org_name = network_info.get('organizationName', '')
        part_name = network_info.get('partitionName', '')
        segment_id = network_info['segmentId']
        if 'mobDomainName' in network_info:
            vlan_id = network_info['vlanId']
            mob_dom_name = network_info['mobDomainName']
            url = self._network_mob_url % (org_name, part_name, vlan_id,
                                           mob_dom_name)
        else:
            url = self._network_url % (org_name, part_name, segment_id)
        return self._send_request('DELETE', url, '', 'network')

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


Question: // RenameContainer renames a container

func (c *HyperClient) RenameContainer(oldName string, newName string) error {
	req := types.ContainerRenameRequest{
		OldContainerName: oldName,
		NewContainerName: newName,
	}
	_, err := c.client.ContainerRename(c.ctx, &req)

	if err != nil {
		return err
	}

	return nil
}

public static function replaceLabel($uri, int $offset, $host)
    {
        return $uri->withHost((string) (new Domain(self::filterUri($uri)->getHost()))->withLabel($offset, $host));
    }

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


Question: Marshall the given parameter object.

public void marshall(TrustedAdvisorCheckDescription trustedAdvisorCheckDescription, ProtocolMarshaller protocolMarshaller) {

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

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

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

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


Question:
/*
Execute a command-line command, and echo it's output.
The command is executed by the user who has invoked this script.

static function execute($cmd)
    {
        $result = '';
        echo 'Executing ' . $cmd . PHP_EOL;
        $result = shell_exec($cmd);
        echo($result);
        return $result;
    }

def invoke(tasks)
      remote_shell do |shell|
        # setup the deployment repository
        invoke_task(:setup,shell) if tasks.include?(:setup)

        # cd into the deployment repository
        shell.cd(shell.uri.path)

        # update the deployment repository
        invoke_task(:update,shell) if tasks.include?(:update)

        # framework tasks
        invoke_task(:install,shell) if tasks.include?(:install)
        invoke_task(:migrate,shell) if tasks.include?(:migrate)

        # server tasks
        if tasks.include?(:config)
          invoke_task(:config,shell)
        elsif tasks.include?(:start)
          invoke_task(:start,shell)
        elsif tasks.include?(:stop)
          invoke_task(:stop,shell)
        elsif tasks.include?(:restart)
          invoke_task(:restart,shell)
        end
      end

      return true
    end

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


Question:
/*
(non-Javadoc)

@see java.util.Hashtable#keys()

@SuppressWarnings("unchecked")
	@Override
	public PrefixedPropertiesEnumeration<Object> keys() {
		lock.readLock().lock();
		try {
			@SuppressWarnings("rawtypes")
			final Set keys = keySet();
			@SuppressWarnings("rawtypes")
			final Iterator it = keys.iterator();
			return new PrefixedPropertiesEnumerationImpl<Object>(it, true);
		} finally {
			lock.readLock().unlock();
		}
	}

public Object searchEqual(
                             Object            searchKey)
    {
        SearchComparator comp = searchComparator(SearchComparator.EQ);
        Object p = find(comp, searchKey);
        return p;
    }

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


Question:
Retrieve the size of the passed {@link Enumeration}.

@param aEnumeration
Enumeration to check. May be null.
@return The number objects or 0 if the passed parameter is
null.

@Nonnegative
  public static int getSize (@Nullable final Enumeration <?> aEnumeration)
  {
    int ret = 0;
    if (aEnumeration != null)
      while (aEnumeration.hasMoreElements ())
      {
        aEnumeration.nextElement ();
        ++ret;
      }
    return ret;
  }

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;
    }

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


Question:
Queries the specific sheet info.

@param {string} sheetId

async function querySheetInfo(sheetId) {
    var key = util.createIdentifier('sheet_info', sheetId);

    return await fetchData(key, api.converter.sheetInfoResponse,
        () => executeRequest('sheet_info', {sheetId: sheetId})
    );
}

def EXT method_name, *description, **metadata, &body
  INSTANCE_METHOD \
    method_name,
    *description,
    **metadata \
  do
    subject do

    end
  end
end

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


Question:
// NewContextWithMinVersionWait returns the context with min version and a
// default deadline set.

func NewContextWithMinVersionWait(ctx context.Context, minVersion int) (c context.Context, cancel func()) {
	ctx = context.WithValue(ctx, minVersionKey, minVersion)
	return context.WithTimeout(ctx, DefaultMinVersionDeadline)
}

def pop_with_body_instrs(setup_with_instr, queue):

    body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')

    # Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
    # These don't correspond to anything in the AST, so remove them here.
    load_none = body_instrs.pop()
    expect(load_none, instrs.LOAD_CONST, "at end of with-block")
    pop_block = body_instrs.pop()
    expect(pop_block, instrs.POP_BLOCK, "at end of with-block")
    if load_none.arg is not None:
        raise DecompilationError(
            "Expected LOAD_CONST(None), but got "
            "%r instead" % (load_none)
        )

    # Target of the setup_with should be a WITH_CLEANUP instruction followed by
    # an END_FINALLY.  Neither of these correspond to anything in the AST.
    with_cleanup = queue.popleft()
    expect(with_cleanup, instrs.WITH_CLEANUP, "at end of with-block")
    end_finally = queue.popleft()
    expect(end_finally, instrs.END_FINALLY, "at end of with-block")

    return body_instrs

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


Question: Treats a MongolianGridFile as a node.js Readable Stream

function MongolianGridFileReadStream(file) {
    if (!file._id) throw new Error("Can only read files retrieved from the database")
    if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
    if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)

    stream.Stream.call(this)

    this.file = file
    this.readable = true
    this._chunkCount = file.chunkCount()
    this._chunkIndex = 0

    process.nextTick(this._nextChunk.bind(this))
}

public function getWebfilesAsStream()
	{
		$client = $this->getClientWithToken();
		$service = new Google_Service_Calendar($client);

		// Print the next 10 events on the user's calendar.
		$optParams = array(
			'maxResults' => 5,
			'orderBy' => 'startTime',
			'singleEvents' => TRUE,
			'timeMin' => date('c'),
		);
		$results = $service->events->listEvents($this->m_sCalendarId, $optParams);

		$webfiles = array();

		foreach ($results->getItems() as $event) {

			$webfile = $this->toWebfileEvent($event);
			array_push($webfiles, $webfile);
		}

		return new MWebfileStream($webfiles);
	}

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


Question: // SetCount sets the Count field's value.

func (s *Bucket) SetCount(v int64) *Bucket {
	s.Count = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: // SetConfidence sets the Confidence field's value.

func (s *ModerationLabel) SetConfidence(v float64) *ModerationLabel {
	s.Confidence = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: Unbinds all events and destroys subBinding...

function () {
            // binding already destroyed?
            if (!this.$) {
                return;
            }
            var e;
            for (var j = 0; j < this.$events.length; j++) {
                e = this.$events[j];
                this.$.scope.unbind(e.eventType, e.callback, this);
            }

            this.$.scope.unbind('destroy', this.destroy, this);

            if (this.$.twoWay === true) {
                this.$.target.unbind(this.$.targetEvent, this._revCallback, this);
            }
            if (this.$subBinding) {
                this.$subBinding.destroy();
                this.$subBinding = null;
            }

            // destroy parameter bindings
            for (var i = 0; i < this.$parameters.length; i++) {
                var par = this.$parameters[i];
                if (par instanceof Binding) {
                    par.destroy();
                }
            }
            this.$parameters = null;
            this.$.scope = this.$.target = this.$.callback = null;
            this.$ = null;
            this.$targets = null;
            this.callBase();

            bindingsDestroyed++;
            if (bindingsDestroyed === 500) {
                if (typeof(CollectGarbage) === "function") {
                    CollectGarbage();
                }
                bindingsDestroyed = 0;
            }
        }

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

        ob_implicit_flush(true);
        flush();

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

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


Question:
@AfterStep ~@modal

Excluding scenarios with @modal tag is required,
because modal dialogs stop any JS interaction

public function readErrorHandlerAfterStep(StepEvent $event) {
		try{
	        $page = $this->getSession()->getPage();

	        $jserrors = $page->find('xpath', '//body[@data-jserrors]');
	        if (null !== $jserrors) {
	            $this->takeScreenshot($event);
	            file_put_contents('php://stderr', $jserrors->getAttribute('data-jserrors') . PHP_EOL);
	        }

	        $javascript = <<<JS
if ('undefined' !== typeof window.jQuery) {
	window.jQuery(document).ready(function() {
		window.jQuery('body').removeAttr('data-jserrors');
	});
}
JS;

			$this->getSession()->executeScript($javascript);
		}catch(\WebDriver\Exception $e){
			$this->logException($e);
        }
    }

function _addItems(item, $container) {
    if (Array.isArray(item)) {
      item.forEach(function(item) {
        _addItems(item, $container);
      });
    } else if (utils.includesCapability(meta.activeWatchInfo, item.capabilities)) {
      if (item.type === 'section') {
        var $wrapper = HTML('<div class="section">');
        $container.add($wrapper);
        _addItems(item.items, $wrapper);
      } else {
        var _item = _.copyObj(item);
        _item.clayId = _items.length;

        var clayItem = new ClayItem(_item).initialize(self);

        if (_item.id) {
          _itemsById[_item.id] = clayItem;
        }

        if (_item.messageKey) {
          _itemsByMessageKey[_item.messageKey] = clayItem;
        }

        _items.push(clayItem);

        // set the value of the item via the manipulator to ensure consistency
        var value = typeof _settings[_item.messageKey] !== 'undefined' ?
          _settings[_item.messageKey] :
          _item.defaultValue;

        clayItem.set(typeof value !== 'undefined' ? value : '');

        $container.add(clayItem.$element);
      }
    }
  }

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