Question:
Overrides the mform get_data method.

Created to force a value since the validation method does not work with multiple checkbox.

@return stdClass form data object.

public function get_data() {
        global $CFG;
        $data = parent::get_data();
        if ($data && $this->_customdata['multipledisplaytypes']) {
            if (count(array_filter($data->display)) == 0) {
                // Ensure that a value was selected as the export plugins expect at least one value.
                if ($CFG->grade_export_displaytype == GRADE_DISPLAY_TYPE_LETTER) {
                    $data->display['letter'] = GRADE_DISPLAY_TYPE_LETTER;
                } else if ($CFG->grade_export_displaytype == GRADE_DISPLAY_TYPE_PERCENTAGE) {
                    $data->display['percentage'] = GRADE_DISPLAY_TYPE_PERCENTAGE;
                } else {
                    $data->display['real'] = GRADE_DISPLAY_TYPE_REAL;
                }
            }
        }
        return $data;
    }

public function openGroup($name, $label = null, $options = [])
    {
        $options = $this->appendClassToOptions('form-group', $options);
        // Append the name of the group to the groupStack.
        $this->groupStack[] = $name;
        if ($this->hasErrors($name)) {
            // If the form element with the given name has any errors,
            // apply the 'has-error' class to the group.
            $options = $this->appendClassToOptions('has-error', $options);
        }
        // If a label is given, we set it up here. Otherwise, we will just
        // set it to an empty string.
        $label = $label ? $this->label($name, $label, ['class' => 'control-label']) : '';

        return '<div' . $this->html->attributes($options) . '>' . $label;
    }

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


Question:
Returns the next free position with respect to an address, including that address itself

        :param address: The address to begin the search with (including itself)
        :return: The next free position

def next_free_pos(self, address):

        idx = self._search(address)
        if idx < len(self._list) and self._list[idx].start <= address < self._list[idx].end:
            # Occupied
            i = idx
            while i + 1 < len(self._list) and self._list[i].end == self._list[i + 1].start:
                i += 1
            if i == len(self._list):
                return self._list[-1].end

            return self._list[i].end

        return address

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
Use a binary search over the range of provided actuation_steps to find the
    maximum actuation voltage that is measured by the board feedback circuit
    using the specified feedback resistor.

def find_good(control_board, actuation_steps, resistor_index, start_index,
              end_index):
    '''

    '''
    lower = start_index
    upper = end_index
    while lower < upper - 1:
        index = lower + (upper - lower) / 2
        v = actuation_steps[index]
        control_board.set_waveform_voltage(v)
        data = measure_board_rms(control_board)
        valid_data = data[data['divider resistor index'] >= 0]

        if (valid_data['divider resistor index'] < resistor_index).sum():
            # We have some measurements from another resistor.
            upper = index
        else:
            lower = index
    control_board.set_waveform_voltage(actuation_steps[lower])
    data = measure_board_rms(control_board)
    return lower, data

private void _processNotification(Alert alert, History history, List<Metric> metrics,
			Map<BigInteger, Map<Metric, Long>> triggerFiredTimesAndMetricsByTrigger, Notification notification, Long alertEnqueueTimestamp) {

		//refocus notifier does not need cool down logic, and every evaluation needs to send notification
		boolean isRefocusNotifier = SupportedNotifier.REFOCUS.getName().equals(notification.getNotifierName());

		for(Trigger trigger : notification.getTriggers()) {
			Map<Metric, Long> triggerFiredTimesForMetrics = triggerFiredTimesAndMetricsByTrigger.get(trigger.getId());

			for(Metric m : metrics) {
				if(triggerFiredTimesForMetrics!=null && triggerFiredTimesForMetrics.containsKey(m)) {
					String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is fired.", trigger.getName(), m.getIdentifier());
					history.appendMessageNUpdateHistory(logMessage, null, 0);

					if (isRefocusNotifier) {
						sendNotification(trigger, m, history, notification, alert, triggerFiredTimesForMetrics.get(m), alertEnqueueTimestamp);
						continue;
					}

					if(!notification.onCooldown(trigger, m)) {
						_updateNotificationSetActiveStatus(trigger, m, history, notification);
						sendNotification(trigger, m, history, notification, alert, triggerFiredTimesForMetrics.get(m), alertEnqueueTimestamp);
					} else {
						logMessage = MessageFormat.format("The notification {0} is on cooldown until {1}.", notification.getName(), getDateMMDDYYYY(notification.getCooldownExpirationByTriggerAndMetric(trigger, m)));
						history.appendMessageNUpdateHistory(logMessage, null, 0);
					}
				} else {
					String logMessage = MessageFormat.format("The trigger {0} was evaluated against metric {1} and it is not fired.", trigger.getName(), m.getIdentifier());
					history.appendMessageNUpdateHistory(logMessage, null, 0);

					if (isRefocusNotifier) {
						sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp);
						continue;
					}

					if(notification.isActiveForTriggerAndMetric(trigger, m)) {
						// This is case when the notification was active for the given trigger, metric combination
						// and the metric did not violate triggering condition on current evaluation. Hence we must clear it.
						_updateNotificationClearActiveStatus(trigger, m, notification);
						sendClearNotification(trigger, m, history, notification, alert, alertEnqueueTimestamp);
					}
				}
			}
		}
	}

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


Question:
@param ResourceBundleInterface $bundle
@param string                  $key

@return string[]

private function getBundleValue(ResourceBundleInterface $bundle, string $key): array
    {
        return [
            BundleStorageInterface::INDEX_PAIR_VALUE  => $bundle->getValue($key),
            BundleStorageInterface::INDEX_PAIR_LOCALE => $bundle->getLocale(),
        ];
    }

void resolveTypeVariable(SQLiteModelMethod value) {
		// before proceed, we need to resolve typeVariables
		for (Pair<String, TypeName> item : value.getParameters()) {
			item.value1 = typeVariableResolver.resolve(item.value1);
		}

		value.setReturnClass(typeVariableResolver.resolve(value.getReturnClass()));

	}

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


Question:
@return mixed[]

@throws \yii\base\InvalidParamException

public function getComponents()
    {
        if ($this->_components === null) {
            $this->_components = [];
            if ($config = $this->readConfig()) {
                foreach ($this->files as $current) {
                    if (isset($config[$current]['components'])) {
                        /** @var mixed[] $components */
                        $components = $config[$current]['components'];
                        if (is_array($components)) {
                            foreach ($components as $name => $component) {
                                if (($class = $this->findClass($component)) !== false) {
                                    $this->_components[$name][$class] = $class;
                                }
                            }
                        }
                    }
                }
            }
        }
        return $this->_components;
    }

public function categorySearchChildrenAction()
    {
        $type = $this->params('type');
        $children = $this->getService($type)->getAll();

        $viewVars = array('children' => $children, 'type' => $type);
        return $this->partialView('category-search-children', $viewVars);
    }

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


Question:
Ends the uninstallation of the given bundle (must be called by Bundle)

        :param bundle: The bundle to uninstall
        :raise BundleException: Invalid bundle

def uninstall_bundle(self, bundle):
        # type: (Bundle) -> None

        if bundle is None:
            # Do nothing
            return

        with self.__bundles_lock:
            # Stop the bundle first
            bundle.stop()

            bundle_id = bundle.get_bundle_id()
            if bundle_id not in self.__bundles:
                raise BundleException("Invalid bundle {0}".format(bundle))

            # Notify listeners
            self._dispatcher.fire_bundle_event(
                BundleEvent(BundleEvent.UNINSTALLED, bundle)
            )

            # Remove it from the dictionary
            del self.__bundles[bundle_id]

            # Remove it from the system => avoid unintended behaviors and
            # forces a complete module reload if it is re-installed
            name = bundle.get_symbolic_name()
            try:
                del sys.modules[name]
            except KeyError:
                # Ignore
                pass

            try:
                # Clear reference in parent
                parent, basename = name.rsplit(".", 1)
                if parent:
                    delattr(sys.modules[parent], basename)
            except (KeyError, AttributeError, ValueError):
                # Ignore errors
                pass

protected static function __abort($message, $start)
        {
            $result = Symphony::Log()->pushToLog($message, E_ERROR, true);

            if ($result) {
                Symphony::Log()->writeToLog('============================================', true);
                Symphony::Log()->writeToLog(sprintf('INSTALLATION ABORTED: Execution Time - %d sec (%s)',
                    max(1, time() - $start),
                    date('d.m.y H:i:s')
                ), true);
                Symphony::Log()->writeToLog('============================================' . PHP_EOL . PHP_EOL . PHP_EOL, true);
            }

            self::__render(new InstallerPage('failure'));
        }

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


Question:
Check if the table exists.

@param string      $dataset
@param bool        $no_exit
@param bool|string $connection

@return void

@SuppressWarnings(PHPMD.ExitExpression)
@SuppressWarnings(PHPMD.BooleanArgumentFlag)

protected function checkTableExists($dataset, $no_exit = false, $connection = false)
    {
        $connection = $connection === false ? $this->connection($dataset) : $connection;

        $result = DB::connection($connection)
            ->select(DB::raw('SHOW TABLES LIKE \'data_'.$dataset.'\''));

        if (count($result) == 0) {
            if ($no_exit) {
                return false;
            }

            $this->error(sprintf('\'%s\' table does not exist. Please migrate it first.', 'data_'.$dataset));
            $this->line('');
            exit(1);
        }

        return true;
    }

public @NotNull QueryBuilder append(@SuppressWarnings("ParameterHidesMemberVariable") @NotNull SqlQuery query) {
        this.query.append(query.getSql());
        arguments.addAll(query.getArguments());
        return this;
    }

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


Question:
Returns the number of bytes needed to encode the given length.
If the length is indefinite, this value takes in account the bytes needed to encode the EOC tag.

@param {number} lenValue
@param {boolean} indefiniteLength
@return {number}

function getLengthOfLength(lenValue, indefiniteLength) {
  var lenOfLen;

  if (indefiniteLength) {
    lenOfLen = 3;
  } else if (lenValue > 0x00FFFFFF) {
    lenOfLen = 5;
  } else if (lenValue > 0x0000FFFF) {
    lenOfLen = 4;
  } else if (lenValue > 0x000000FF) {
    lenOfLen = 3;
  } else if (lenValue > 0x0000007F) {
    lenOfLen = 2;
  } else {
    lenOfLen = 1;
  }

  return lenOfLen
}

func (c *Cipher) XORKeyStream(dst, src []byte) {
	if len(dst) < len(src) {
		panic("chacha20/chacha: dst buffer is to small")
	}

	if c.off > 0 {
		n := len(c.block[c.off:])
		if len(src) <= n {
			for i, v := range src {
				dst[i] = v ^ c.block[c.off]
				c.off++
			}
			if c.off == 64 {
				c.off = 0
			}
			return
		}

		for i, v := range c.block[c.off:] {
			dst[i] = src[i] ^ v
		}
		src = src[n:]
		dst = dst[n:]
		c.off = 0
	}

	// check for counter overflow
	blocksToXOR := len(src) / 64
	if len(src)%64 != 0 {
		blocksToXOR++
	}
	var overflow bool
	if c.noncesize == INonceSize {
		overflow = binary.LittleEndian.Uint32(c.state[48:]) > math.MaxUint32-uint32(blocksToXOR)
	} else {
		overflow = binary.LittleEndian.Uint64(c.state[48:]) > math.MaxUint64-uint64(blocksToXOR)
	}
	if overflow {
		panic("chacha20/chacha: counter overflow")
	}

	c.off += xorKeyStream(dst, src, &(c.block), &(c.state), c.rounds)
}

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


Question: // SetTargets sets the Targets field's value.

func (s *CreatePullRequestInput) SetTargets(v []*Target) *CreatePullRequestInput {
	s.Targets = v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


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

@Override
	public EClass getIfcHeatingValueMeasure() {
		if (ifcHeatingValueMeasureEClass == null) {
			ifcHeatingValueMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(813);
		}
		return ifcHeatingValueMeasureEClass;
	}

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:
Register an external service.

        :param plugin_name: Service name
        :param plugin_instance: PluginBase
        :return:

def _register_external_service(self, plugin_name, plugin_instance):

        for attr in plugin_instance.get_external_services().keys():
            if attr in self._external_services:
                raise PluginException("External service with name {} already exists! Unable to add "
                                      "services from plugin {}.".format(attr, plugin_name))
            self._external_services[attr] = plugin_instance.get_external_services().get(attr)

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
Add errors.

@param Collection $errors

@return $this

public function addErrors(Collection $errors)
    {
        $this->errors = $this->getErrors()->merge($errors);

        return $this;
    }

function _addFailure(attribute, rule, parameters) {
    _addError(attribute, rule, parameters);
    if (! _failedRules[attribute]) {
      _failedRules[attribute] = {};
    }
    _failedRules[attribute][rule] = parameters;
  }

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


Question:
Set the key-value pair, verifying existing CAS.
 Returns the resulting CAS value if succeeded, and falsy otherwise.

def set_cas(key, value, cas, ttl=nil, options=nil)
      ttl ||= @options[:expires_in].to_i
      perform(:set, key, value, ttl, cas, options)
    end

func ToRenderValuesCaps(chrt *chart.Chart, chrtVals *chart.Config, options ReleaseOptions, caps *Capabilities) (Values, error) {

	top := map[string]interface{}{
		"Release": map[string]interface{}{
			"Name":      options.Name,
			"Time":      options.Time,
			"Namespace": options.Namespace,
			"IsUpgrade": options.IsUpgrade,
			"IsInstall": options.IsInstall,
			"Revision":  options.Revision,
			"Service":   "Tiller",
		},
		"Chart":        chrt.Metadata,
		"Files":        NewFiles(chrt.Files),
		"Capabilities": caps,
	}

	vals, err := CoalesceValues(chrt, chrtVals)
	if err != nil {
		return top, err
	}

	top["Values"] = vals
	return top, nil
}

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


Question:
Append new <url> section to current file

@param SitemapUrlNode $url

@return bool

public function writeUrl(SitemapUrlNode $url)
    {
        // if count of written items more than allowed per one xml sitemap file
        if (++$this->_itemsCount > $this->urlsPerFile) {
            // Ending of current file
            $this->writeFooter();

            // Starting new file
            $this->beginNewFile();

            return $this->writeUrl($url);
        }

        // Write new <url> section to current file
        return (bool)$this->appendToFile($url . PHP_EOL);
    }

def add3(self, target, path_settings=None, method='GET'):

        if path_settings is None:
            path_settings = []
        return self.add(method, path_settings, target)

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


Question:
Send SMS.

@return array

public function send()
    {
        return $this->client->executeRequest(
            new OutboundSMSRequest(
                $this->message,
                $this->recipientNumber,
                $this->senderNumber,
                $this->senderName
            )
        );
    }

public static function createMessage($value)
    {
        $newValue = $value . self::EOL;
        return
            self::CONTENT_LENGTH . ':' . strlen($newValue) . self::EOL
            . self::EOL
            . $newValue;
    }

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


Question:
Set a cookie to a new value

@param   string  $key
@param   mixed   $value
@throws  \InvalidArgumentException
@since   2.0.0

public function set($key, $value = null)
	{
		if (is_array($key))
		{
			foreach ($key as $arraykey => $value)
			{
				$this->set($arraykey, $value);
			}
		}
		else
		{
			if (isset($this->jar[$key]) and ! $this->jar[$key]->isDeleted())
			{
				if ($value instanceOf Cookie)
				{
					$this->jar[$key] = $value;
				}
				else
				{
					$this->jar[$key]->setValue($value);
				}
			}
			elseif ($this->has($key))
			{
				$this->parent->set($key, $value);
			}
			else
			{
				$this->jar[$key] = new Cookie($key, $this->config, $value);
			}
		}

		return $this;
	}

func (s *BatchPutMessageInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "BatchPutMessageInput"}
	if s.ChannelName == nil {
		invalidParams.Add(request.NewErrParamRequired("ChannelName"))
	}
	if s.ChannelName != nil && len(*s.ChannelName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ChannelName", 1))
	}
	if s.Messages == nil {
		invalidParams.Add(request.NewErrParamRequired("Messages"))
	}
	if s.Messages != nil {
		for i, v := range s.Messages {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Messages", i), err.(request.ErrInvalidParams))
			}
		}
	}

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

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


Question:
Either creates a mime part or sets the existing mime part with the passed
mimeType to $strongOrHandle.

@param Message $message
@param string $mimeType
@param string|resource $stringOrHandle
@param string $charset

public function setContentPartForMimeType(Message $message, $mimeType, $stringOrHandle, $charset)
    {
        $part = ($mimeType === 'text/html') ? $message->getHtmlPart() : $message->getTextPart();
        if ($part === null) {
            $part = $this->createContentPartForMimeType($message, $mimeType, $charset);
        } else {
            $contentType = $part->getContentType();
            $part->setRawHeader('Content-Type', "$contentType;\r\n\tcharset=\"$charset\"");
        }
        $part->setContent($stringOrHandle);
    }

public function make($identifier, $expireTime = 3600)
    {
        $json = [
            'TLS.account_type' => $this->accountType,
            'TLS.identifier' => (string)$identifier,
            'TLS.appid_at_3rd' => (string)$this->appId,
            'TLS.sdk_appid' => (string)$this->appId,
            'TLS.expire_after' => (string)$expireTime,
            'TLS.version' => '201512300000',
            'TLS.time' => (string)time()
        ];

        $content = $this->genSignatureContent($json);
        $signature = $this->makeSignature($content);
        $json['TLS.sig'] = base64_encode($signature);
        if ($json['TLS.sig'] === false) {
            throw new SignatureException('base64_encode error.');
        }
        $json_text = json_encode($json);
        if ($json_text === false) {
            throw new SignatureException('json_encode error.');
        }
        $compressed = gzcompress($json_text);
        if ($compressed === false) {
            throw new SignatureException('gzcompress error.');
        }
        return $this->base64Encode($compressed);

    }

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


Question: // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.

func (in *ExecCredential) DeepCopyObject() runtime.Object {
	if c := in.DeepCopy(); c != nil {
		return c
	}
	return nil
}

func (s *VolumeServer) Clone(
	ctx context.Context,
	req *api.SdkVolumeCloneRequest,
) (*api.SdkVolumeCloneResponse, error) {
	if s.cluster() == nil || s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if len(req.GetName()) == 0 {
		return nil, status.Error(
			codes.InvalidArgument,
			"Must supply a uniqe name")
	} else if len(req.GetParentId()) == 0 {
		return nil, status.Error(
			codes.InvalidArgument,
			"Must parent volume id")
	}

	locator := &api.VolumeLocator{
		Name: req.GetName(),
	}
	source := &api.Source{
		Parent: req.GetParentId(),
	}

	// Get spec. This also checks if the parend id exists.
	// This will also check for Ownership_Read access.
	parentVol, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
		VolumeId: req.GetParentId(),
	})
	if err != nil {
		return nil, err
	}

	// Create the clone
	id, err := s.create(ctx, locator, source, parentVol.GetVolume().GetSpec())
	if err != nil {
		return nil, err
	}

	return &api.SdkVolumeCloneResponse{
		VolumeId: id,
	}, nil
}

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


Question: Make stdout again the active buffer.

def quit_alternate_screen(self):

        if self._in_alternate_screen:
            stdout = self._winapi(windll.kernel32.GetStdHandle, STD_OUTPUT_HANDLE)
            self._winapi(windll.kernel32.SetConsoleActiveScreenBuffer, stdout)
            self._winapi(windll.kernel32.CloseHandle, self.hconsole)
            self.hconsole = stdout
            self._in_alternate_screen = False

def getinputencoding(stream=None):

    if stream is None:
        stream = sys.stdin
    encoding = stream.encoding
    if not encoding:
        encoding = getpreferredencoding()
    return encoding

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


Question:
Creates a zip entry inputstream source and maps it to the specified filename.
@param subsystemFileName
@param zipFile
@param zipEntry

public void addSubsystemFileSource(String subsystemFileName, File zipFile, ZipEntry zipEntry) {
       inputStreamSourceMap.put(subsystemFileName, new ZipEntryInputStreamSource(zipFile, zipEntry));
    }

public static void setInputPaths(JobConf conf, String commaSeparatedPaths) {
    setInputPaths(conf, StringUtils.stringToPath(
                        getPathStrings(commaSeparatedPaths)));
  }

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


Question:
Returns an array of tokens

@param string $string
@param int &$needle
@throws \UnexpectedValueException
@return array

public function getTokens($string, &$needle = 0)
    {
        $exprTokenizer = new ExpressionTokenizer();
        $ret = array();
        $depth = 0;
        $needle = 0;
        $len = strlen($string);
        while ($needle < $len) {
            $before = $needle;
            $substr = substr($string, $needle);
            if ($depth === 0) {
                // match either '$(' or '@(' and mark that as an EXPR_START token.
                if (preg_match('/^([$@])\(/', $substr, $m)) {
                    $needle += strlen($m[0]);
                    $ret[] = new Token(Token::EXPR_START, $m[0]);

                    // record expression depth, to make sure the usage of parentheses inside the expression doesn't
                    // break tokenization (e.g. '$( ("foo") )'
                    $depth++;
                } else {
                    // store the current token in a temp var for appending, in case it's a DATA token
                    $token = end($ret);

                    // handle escaping of the $( syntax, '$$(' becomes '$('
                    if (preg_match('/^\$\$\(/', $substr, $m)) {
                        $value = substr($m[0], 1);
                        $needle += strlen($m[0]);
                    } else {
                        $value = $string{$needle};
                        $needle += strlen($value);
                    }

                    // if the current token is DATA, and the previous token is DATA, append the value to the previous
                    // and ignore the current.
                    if ($token && $token->match(Token::DATA)) {
                        $token->value .= $value;
                        unset($token);
                    } else {
                        $ret[] = new Token(Token::DATA, $value);
                    }
                }
            } else {
                $ret = array_merge($ret, $exprTokenizer->getTokens($string, $needle));
                $depth = 0;
            }
            if ($before === $needle) {
                // safety net.
                throw new \UnexpectedValueException(
                    "Unexpected input near token {$string{$needle}}, unsupported character"
                );
            }
        }
        return $ret;
    }

public function handleAction(Request $request): Envelope
    {
        $request->attributes->set('pbjx_redact_error_message', false);
        $envelope = EnvelopeV1::create();
        if (!$this->isRequestMethodOk($envelope, $request) || !$this->isContentTypeOk($envelope, $request)) {
            return $envelope;
        }

        if ($request->isMethod('GET')) {
            $json = PbjxToken::urlsafeB64Decode($request->query->get('pbj'));
        } elseif (0 === strpos($request->headers->get('Content-Type'), 'multipart/form-data')) {
            $json = $request->request->get('pbj');
        } else {
            $json = $request->getContent();
        }

        $json = (string)$json;
        $data = json_decode($json, true) ?: [];
        if (!$this->isJsonOk($envelope, $request)) {
            return $envelope;
        }

        $pbjxCategory = $request->attributes->get('pbjx_category');
        if (false !== strpos($pbjxCategory, '_')) {
            $pbjxCategory = str_replace('_', '', $pbjxCategory);
            $request->attributes->set('pbjx_category', $pbjxCategory);
        }

        try {
            $expectedCurie = SchemaCurie::fromString(sprintf(
                '%s:%s:%s:%s',
                $request->attributes->get('pbjx_vendor'),
                $request->attributes->get('pbjx_package'),
                $pbjxCategory,
                $request->attributes->get('pbjx_message')
            ));

            $request->attributes->set('pbjx_curie', $expectedCurie->toString());
            $schemaId = isset($data[Schema::PBJ_FIELD_NAME]) ? SchemaId::fromString($data[Schema::PBJ_FIELD_NAME]) : null;

            /** @var Message $class */
            if (null === $schemaId) {
                $class = MessageResolver::resolveCurie($expectedCurie);
                $schema = $class::schema();
                $schemaId = $schema->getId();
            } else {
                $class = MessageResolver::resolveId($schemaId);
            }

            if ($schemaId->getCurie() !== $expectedCurie) {
                throw new \InvalidArgumentException(
                    sprintf(
                        'The resolved schema [%s] doesn\'t match expected curie [%s].',
                        $schemaId->toString(),
                        $expectedCurie->toString()
                    )
                );
            }
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set('pbjx_input', $data);
        $request->attributes->set('pbjx_bind_unrestricted', $request->attributes->getBoolean('pbjx_bind_unrestricted'));

        try {
            /** @var Command|Event|PbjxRequest $message */
            $message = $class::fromArray($data);
            $message->set('ctx_correlator_ref', $envelope->generateMessageRef());
        } catch (\Throwable $e) {
            return $envelope
                ->set('code', Code::INVALID_ARGUMENT)
                ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
                ->set('error_name', 'UnprocessableEntity')
                ->set('error_message', $e->getMessage());
        }

        $request->attributes->set(
            'pbjx_redact_error_message',
            !$request->attributes->getBoolean('pbjx_console')
        );

        if (!$this->isPbjxTokenOk($envelope, $request, $json)) {
            return $envelope;
        }

        // allows for functional tests/postman tests/etc. to post pbjx but
        // not actually run them.  this is most important for commands/events
        // which can change state but for request, you'd typically not use
        // dry run because you need to get a response in order to make assertions.
        if ($request->headers->has('x-pbjx-dry-run')) {
            return $envelope
                ->set('code', Code::OK)
                ->set('http_code', HttpCode::HTTP_ACCEPTED())
                ->set('message_ref', $message->generateMessageRef());
        }

        if ($message instanceof Command) {
            return $this->handleCommand($envelope, $request, $message);
        }

        if ($message instanceof Event) {
            return $this->handleEvent($envelope, $request, $message);
        }

        if ($message instanceof PbjxRequest) {
            return $this->handleRequest($envelope, $request, $message);
        }

        $request->attributes->set('pbjx_redact_error_message', false);
        return $envelope
            ->set('code', Code::INVALID_ARGUMENT)
            ->set('http_code', HttpCode::HTTP_UNPROCESSABLE_ENTITY())
            ->set('error_name', 'UnprocessableEntity')
            ->set(
                'error_message',
                sprintf('This service does not allow you to submit [%s] messages.', $schemaId->toString())
            );
    }

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


Question: List names of metric dimensions.

def do_dimension_name_list(mc, args):
    ''''''
    fields = {}
    if args.metric_name:
        fields['metric_name'] = args.metric_name
    if args.limit:
        fields['limit'] = args.limit
    if args.offset:
        fields['offset'] = args.offset
    if args.tenant_id:
        fields['tenant_id'] = args.tenant_id

    try:
        dimension_names = mc.metrics.list_dimension_names(**fields)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))

    if args.json:
        print(utils.json_formatter(dimension_names))
        return

    if isinstance(dimension_names, list):
        utils.print_list(dimension_names, ['Dimension Names'], formatters={
            'Dimension Names': lambda x: x['dimension_name']})

def get_help_option_names(self, ctx):
        """"""
        all_names = set(ctx.help_option_names)
        for param in self.params:
            all_names.difference_update(param.opts)
            all_names.difference_update(param.secondary_opts)
        return all_names

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


Question: // Convert_core_WeightedPodAffinityTerm_To_v1_WeightedPodAffinityTerm is an autogenerated conversion function.

func Convert_core_WeightedPodAffinityTerm_To_v1_WeightedPodAffinityTerm(in *core.WeightedPodAffinityTerm, out *v1.WeightedPodAffinityTerm, s conversion.Scope) error {
	return autoConvert_core_WeightedPodAffinityTerm_To_v1_WeightedPodAffinityTerm(in, out, s)
}

public function updateBlogUser( $user_id, $old_user_data ) {
		$user = get_userdata( $user_id );
		if ( $user && user_can( $user, 'edit_posts' ) ) {
			$slug = $user->user_nicename;
			$name = trim( "{$user->first_name} {$user->last_name}" );
			if ( empty( $name ) ) {
				$name = $user->display_name;
				if ( empty( $name ) ) {
					$name = $slug;
				}
			}
			$term = get_term_by( 'slug', $old_user_data->user_nicename, self::TAXONOMY );
			if ( $term ) {
				$results = wp_update_term(
					$term->term_id, self::TAXONOMY, [
						'name' => $name,
						'slug' => $slug,
					]
				);
				update_term_meta( $results['term_id'], 'contributor_first_name', $user->first_name );
				update_term_meta( $results['term_id'], 'contributor_last_name', $user->last_name );
			} else {
				$results = wp_insert_term(
					$name, self::TAXONOMY, [
						'slug' => $slug,
					]
				);
				add_term_meta( $results['term_id'], 'contributor_first_name', $user->first_name, true );
				add_term_meta( $results['term_id'], 'contributor_last_name', $user->last_name, true );
			}
			if ( is_array( $results ) ) {
				return $results;
			}
		}
		return false;
	}

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


Question:
Decorator to track the rate at which a function is called
    with dimensions.

def meter_calls_with_dims(**dims):

    def meter_wrapper(fn):
        @functools.wraps(fn)
        def fn_wrapper(*args, **kwargs):
            meter("%s_calls" %
                  pyformance.registry.get_qualname(fn), **dims).mark()
            return fn(*args, **kwargs)
        return fn_wrapper
    return meter_wrapper

func (dl *dialLimiter) AddDialJob(dj *dialJob) {
	dl.lk.Lock()
	defer dl.lk.Unlock()

	log.Debugf("[limiter] adding a dial job through limiter: %v", dj.addr)
	dl.addCheckPeerLimit(dj)
}

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


Question:
Provide rendered value

@param mixed $data Data to use for provision
@param array $options Options to use for provision
@return string

public function provide($data = null, array $options = [])
    {
        if (! is_string($data)) {
            return '';
        }

        if ('' === $data) {
            return '';
        }

        $table = $this->config->getTable();
        $field = $this->config->getField();

        $fileUpload = new FileUpload($table);

        $entities = $fileUpload->getFiles($field, $data);

        if ($entities->isEmpty()) {
            return '';
        }

        $defaultElement = 'CsvMigrations.FieldHandlers/FilesFieldHandler/value';
        $element = empty($options['element']) ? $defaultElement : $options['element'];

        return $this->renderElement($element, ['entities' => $entities]);
    }

def add_arguments(cls, subparsers, dirs):

        parser = subparsers.add_parser(
            'packet',
            help='Packet Bare Metal',
            formatter_class=lambda prog: argparse.ArgumentDefaultsHelpFormatter(prog, max_help_position=40, width=120))

        m = parser.add_argument_group('Mandatory Packet Parameters') # pylint: disable=invalid-name

        g = m.add_mutually_exclusive_group(required=False) # pylint: disable=invalid-name
        g.add_argument('-create-demand',
                       action='store_true',
                       help='Create an on demand based bare metal device instance.')

        g.add_argument('-create-spot',
                       action='store_true',
                       help='Create a spot price based bare metal device instance.')

        g.add_argument('-reboot',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Reboot active instances.')

        g.add_argument('-stop',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Stop active instances.')

        g.add_argument('-terminate',
                       nargs='?',
                       const=-1,
                       metavar='n',
                       help='Terminate active instances.')

        o = parser.add_argument_group('Optional Parameters') # pylint: disable=invalid-name
        o.add_argument('-create-volume',
                       nargs='+',
                       type=str,
                       metavar='s',
                       help='Create storage: <plan> <size> <region> <description>')

        o.add_argument('-conf',
                       metavar='path',
                       type=argparse.FileType(),
                       default=os.path.join(dirs.user_config_dir, 'examples', 'packet', 'packet.json'),
                       help='Packet configuration')

        o.add_argument('-list-projects',
                       action='store_true',
                       help='List available projects.')

        o.add_argument('-list-plans',
                       action='store_true',
                       help='List available plans.')

        o.add_argument('-list-operating-systems',
                       action='store_true',
                       help='List available operating systems.')

        o.add_argument('-list-spot-prices',
                       action='store_true',
                       help='List spot prices.')

        o.add_argument('-list-facilities',
                       action='store_true',
                       help='List available facilities.')

        o.add_argument('-list-devices',
                       action='store_true',
                       help='List devices under given project name.')

        o.add_argument('-project',
                       metavar='project',
                       type=str,
                       default='fuzzing',
                       help='The project to perform operations on.')
        o.add_argument('-tags',
                       metavar='seq',
                       nargs='+',
                       type=str,
                       help='Tags associated with the instance.')
        o.add_argument('-region',
                       metavar='region',
                       type=str,
                       default='nrt1',
                       help='The facility in which the instance is going to run.')
        o.add_argument('-os',
                       metavar='name',
                       type=str,
                       default='ubuntu_18_04',
                       help='The operating system for the created instance.')
        o.add_argument('-plan',
                       metavar='name',
                       type=str,
                       default='baremetal_0',
                       help='The instance type to run.')
        o.add_argument('-max-spot-price',
                       metavar='#',
                       type=float,
                       default='0.05',
                       help='Max price for spot instances.')
        o.add_argument('-count',
                       metavar='#',
                       type=int,
                       default='1',
                       help='The amount of devices to be spawned.')
        o.add_argument('-only',
                       metavar='k=v',
                       nargs='+',
                       type=str,
                       help='Filter instances by criterias.')
        o.add_argument('-version',
                       action='version',
                       version='%(prog)s {}'.format(cls.VERSION),
                       help=argparse.SUPPRESS)

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


Question:
Gets a request that gets information about a user

@param id    id of the user to get information on
@return request to get information about a user

public BoxRequestsUser.GetUserInfo getUserInfoRequest(String id) {
        BoxRequestsUser.GetUserInfo request = new BoxRequestsUser.GetUserInfo(getUserInformationUrl(id), mSession);
        return request;
    }

public void getMemberInfo(final String memberId, final AVIMConversationMemberQueryCallback callback) {
    QueryConditions conditions = new QueryConditions();
    conditions.addWhereItem("cid", QueryOperation.EQUAL_OP, this.conversationId);
    conditions.addWhereItem("peerId", QueryOperation.EQUAL_OP, memberId);
    queryMemberInfo(conditions, callback);
  }

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


Question: // Include 取得する項目

func (api *InternetAPI) Include(key string) *InternetAPI {
	api.include(key)
	return api
}

public function add_shortcode( $tag, $mvc_call, $mvc_args = null )
	{
		$this->shortcodes[] = [
			'tag'		=> $tag,
			'mvc'		=> $mvc_call,
			'mvc_args'	=> $mvc_args,
		];
	}

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


Question: If the facet of the given type exists, return it. Otherwise null.

public <T extends Facet> T getFacet(Class<T> type) {
        for (Facet f : facets)
            if(type==f.getClass())
                return type.cast(f);
        return null;
    }

protected void handleCollectionTypeNotAvailable(XCollectionLiteral literal, ITypeComputationState state, Class<?> clazz) {
		for(XExpression element: literal.getElements()) {
			state.withNonVoidExpectation().computeTypes(element);
		}
		state.acceptActualType(state.getReferenceOwner().newUnknownTypeReference(clazz.getName()));
	}

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


Question:
Blocks the particular signal.

        :param      signal | <str>
                    state  | <bool>

def blockSignal(self, signal, state):

        signal = nativestring(signal)
        if state:
            self._blockedSignals.setdefault(signal, 0)
            self._blockedSignals[signal] += 1
        else:
            val = self._blockedSignals.get(signal, 0)
            val -= 1
            if val > 0:
                self._blockedSignals[signal] = val
            elif val == 0:
                self._blockedSignals.pop(signal)

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question:
Gets a system property int, or a replacement value if the property is
null or blank or not parseable

@param key
@param valueIfNullOrNotParseable
@return

public static long getInt(String key, int valueIfNullOrNotParseable) {
        String value = System.getProperty(key);
        if (Strings.isNullOrEmpty(value)) {
            return valueIfNullOrNotParseable;
        }
        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return valueIfNullOrNotParseable;
        }
    }

func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string,
	routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool,
	args map[string]interface{}, data interface{}) (BaseResponse, error) {
	var url string
	var retval BaseResponse
	url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh)
	if err != nil {
		return retval, err
	}
	var method string
	if len(id) == 0 {
		method = "POST"
	} else {
		method = "PUT"
	}
	body, err := c.DoCommand(method, url, args, data)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}

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


Question:
Get all the minimum needs profiles.

        :returns: The minimum needs by name.
        :rtype: list

def get_profiles(self, overwrite=False):

        def sort_by_locale(unsorted_profiles, locale):
            """Sort the profiles by language settings.

            The profiles that are in the same language as the QGIS' locale
            will be sorted out first.

            :param unsorted_profiles: The user profiles profiles
            :type unsorted_profiles: list

            :param locale: The language settings string
            :type locale: str

            :returns: Ordered profiles
            :rtype: list
            """
            if locale is None:
                return unsorted_profiles

            locale = '_%s' % locale[:2]
            profiles_our_locale = []
            profiles_remaining = []
            for profile_name in unsorted_profiles:
                if locale in profile_name:
                    profiles_our_locale.append(profile_name)
                else:
                    profiles_remaining.append(profile_name)

            return profiles_our_locale + profiles_remaining

        # We ignore empty root_directory to avoid load min needs profile
        # to test directory when test is running.
        if not self.root_directory:
            profiles = []
            return profiles

        else:
            locale_minimum_needs_dir = os.path.join(
                self.root_directory, 'minimum_needs')
            path_name = resources_path('minimum_needs')
            if not os.path.exists(locale_minimum_needs_dir):
                os.makedirs(locale_minimum_needs_dir)
            # load default min needs profile
            for file_name in os.listdir(path_name):
                source_file = os.path.join(path_name, file_name)
                destination_file = os.path.join(
                    locale_minimum_needs_dir, file_name)
                if not os.path.exists(destination_file) or overwrite:
                    copy(source_file, destination_file)
            # move old min needs profile under user profile to inasafe
            # subdirectory
            self.move_old_profile(locale_minimum_needs_dir)
            profiles = [
                profile[:-5] for profile in
                os.listdir(locale_minimum_needs_dir) if
                profile[-5:] == '.json']
            profiles = sort_by_locale(profiles, self.locale)
            return profiles

func (c *Client) RestrictChatMember(chatID string, userID int, r *Restrictions, opts ...sendOption) error {
	req := url.Values{}
	req.Set("chat_id", chatID)
	req.Set("user_id", fmt.Sprint(userID))
	req.Set("can_send_messages", fmt.Sprint(r.CanSendMessages))
	req.Set("can_send_media_messages", fmt.Sprint(r.CanSendMediaMessages))
	req.Set("can_send_other_messages", fmt.Sprint(r.CanSendOtherMessages))
	req.Set("can_add_web_page_previews", fmt.Sprint(r.CanAddWebPagePreviews))
	for _, opt := range opts {
		opt(req)
	}
	var restricted bool
	return c.doRequest("restrictChatMember", req, &restricted)
}

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


Question: Return a camcrypt.CamCrypt object based on keylen, hexkey, and key.

def _get_crypto(keylen, hexkey, key):
    """"""
    if keylen not in camcrypt.ACCEPTABLE_KEY_LENGTHS:
        raise ValueError("key length must be one of 128, 192, or 256")

    if hexkey:
        key = key.decode('hex')

    return camcrypt.CamCrypt(keylen=keylen, key=key)

def RechazarCTG(self, carta_porte, ctg, motivo):
        ""
        response = self.client.rechazarCTG(request=dict(
                        auth={
                            'token': self.Token, 'sign': self.Sign,
                            'cuitRepresentado': self.Cuit, },
                        datosRechazarCTG={
                            'cartaPorte': carta_porte,
                            'ctg': ctg, 'motivoRechazo': motivo,
                            }))['response']
        datos = response.get('datosResponse')
        self.__analizar_errores(response)
        if datos:
            self.CartaPorte = str(datos['cartaPorte'])
            self.NumeroCTG = str(datos['CTG'])
            self.FechaHora = str(datos['fechaHora'])
            self.CodigoOperacion = str(datos['codigoOperacion'])

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


Question:
The Chinese Remainder Theorem as needed for decryption. Returns the solution modulo n=pq.

        Args:
           mp(int): the solution modulo p.
           mq(int): the solution modulo q.

def crt(self, mp, mq):

        u = (mq - mp) * self.p_inverse % self.q
        return mp + (u * self.p)

func GobEncode(store Store, w io.Writer) error {
	enc := gob.NewEncoder(w)
	err := enc.Encode(store)
	return err
}

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


Question:
Generates control's HTML element.
@param  string
@return Nette\Utils\Html

public function getControl($caption = null)
	{
		$el = parent::getControl('');

		$el->type = 'submit';
		$el->class = $this->getClass();

		if ($this->getIcon()) {
			$el->addHtml(Html::el('span')->class(DataGrid::$icon_prefix . $this->getIcon()));

			if (strlen($this->getText())) {
				$el->addHtml(' ');
			}
		}

		$el->addText($this->grid->getTranslator()->translate($this->getText()));

		return $el;
	}

public function parse(Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $view = $parser->getExpressionParser()->parseExpression();

        $variablesOverride = new Twig_Node_Expression_Array(array(), $token->getLine());
        if ($stream->test(Twig_Token::NAME_TYPE, 'with')) {
            $stream->next();

            $variablesOverride->addElement($this->parser->getExpressionParser()->parseExpression());
        }

        $stream->expect(Twig_Token::BLOCK_END_TYPE);

        $viewTemplateExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateFile',
            new Twig_Node_Expression_Array(array(), $token->getLine()),
            $token->getLine()
        );

        $variablesExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateVars',
            $variablesOverride,
            $token->getLine()
        );

        return new Twig_Node_Include(
            $viewTemplateExpr,
            $variablesExpr,
            $only = false,
            $ignoreMissing = false,
            $token->getLine()
        );
    }

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


Question: One of ways of creating builder. This might be the only way (considering all _functional_ builders) that might be utilize to specify generic params only once.

@Nonnull
	public static <T> LObjIntConsumerBuilder<T> objIntConsumer(Consumer<LObjIntConsumer<T>> consumer) {
		return new LObjIntConsumerBuilder(consumer);
	}

private static Deserializer<?> getDeserializer(Properties props, Optional<Deserializers> deserializerType) throws ReflectiveOperationException {

    Deserializer<?> deserializer;
    if (deserializerType.isPresent()) {
      deserializer = ConstructorUtils.invokeConstructor(deserializerType.get().getDeserializerClass());
    } else {
      deserializer = Deserializer.class
          .cast(ConstructorUtils.invokeConstructor(Class.forName(props.getProperty(KAFKA_DESERIALIZER_TYPE))));
    }
    deserializer.configure(PropertiesUtils.propsToStringKeyMap(props), false);
    return deserializer;
  }

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


Question:
/* (non-Javadoc)
@see com.tvd12.ezyfox.core.command.RoomInfo#room(java.lang.String)

@Override
    public RoomInfo room(String name) {
        this.room = CommandUtil.getSfsRoom(name, extension);
        return this;
    }

public Object getObject(String type, Package pkg) {
        if (type==null || type.equals(documentType)) {
            if (object==null && content!=null) {
                object = VariableTranslator.realToObject(pkg, documentType, content);
            }
        } else {
            if (content!=null) {
                documentType = type;
                object = VariableTranslator.realToObject(pkg, documentType, content);
            } else if (object!=null) {
                content = VariableTranslator.realToString(pkg, documentType, object);
                documentType = type;
                object = VariableTranslator.realToObject(pkg, documentType, content);
            }
        }
        return object;
    }

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


Question:
We need this here for old package installers that call CollectionKey::add()
@deprecated

public static function add($type, $args, $pkg = false)
    {
        $category = static::getFacadeApplication()->make('Concrete\Core\Attribute\Category\CategoryService')
            ->getByHandle('collection');
        return $category->getController()->add($type, $args, $pkg);
    }

public function set($key, $value, \DatePeriod $period = null)
    {
        if (is_null($period)) {
            $this->repository->set($key, $value);
        } else {
            $this->setForPeriod($key, $value, $period);
        }
    }

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


Question:
// SetDebugWriter sets the io.Writer where the Graph will record debug
// information. After this is set, the graph will immediately encode itself to
// the stream, and continue to record all subsequent operations.

func (g *Graph) SetDebugWriter(w io.Writer) {
	g.debug = &encoder{w: w}
	g.debug.Encode(newMarshalGraph("root", g))
}

private function traceCLI(array $trace, $label) {
            foreach ($trace as $k => $v) {
                $func = $loc = $line = '';
                $argsPresent = isset($v['args']) && !empty($v['args']);

                self::formatTraceLine($v, $func, $loc, $line);

                $this->console->write('<' . $label . 'b>#' . $k . ': </>')
                              ->write('<' . $label . '>' . ($loc ? $loc : '<<unknown file>>') . '</> ')
                              ->write('<' . $label . '>(' . ($line ? 'line ' . $line : 'unknown line') . ')</>')
                              ->write('<' . $label . '> | </>')
                              ->write('<' . $label . '>' . $func . '</>', true);

                if ($argsPresent) {
                    $this->console->write('<' . $label . 'b>Arguments:</>', true);
                    VarDumper::dump($v['args']);
                }

                $this->console->writeln('');
            }
        }

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


Question:
Check input matrix format.

    :param table: input matrix
    :type table : dict
    :return: bool

def matrix_check(table):

    try:
        if len(table.keys()) == 0:
            return False
        for i in table.keys():
            if table.keys() != table[i].keys() or vector_check(
                    list(table[i].values())) is False:
                return False
        return True
    except Exception:
        return False

def parse_data_to_internal(self, data=None):

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

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


Question:
Answers an array of list item class names for the HTML template.

@return array

public function getListItemClassNames()
    {
        // Initialise:

        $classes = ['item'];

        // Merge Ancestor Class Names:

        $classes = array_merge(
            $classes,
            ViewTools::singleton()->getAncestorClassNames(
                $this->owner,
                $this->owner->baseClass()
            )
        );

        // Merge Meta Class Names:

        if ($this->owner->hasMethod('getMetaClassNames')) {
            $classes = array_merge($classes, $this->owner->getMetaClassNames());
        }

        // Update Class Names via Renderer:

        if ($this->owner->getRenderer()->hasMethod('updateListItemClassNames')) {
            $this->owner->getRenderer()->updateListItemClassNames($classes);
        }

        // Answer Classes:

        return $classes;
    }

public String[] getProxyHostsWhiteList()
    {
        if (_proxyHostsWhiteList == null || _proxyHostsWhiteList.size() == 0)
            return new String[0];

        String[] hosts = new String[_proxyHostsWhiteList.size()];
        hosts = (String[]) _proxyHostsWhiteList.toArray(hosts);
        return hosts;
    }

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


Question:
Decorates a JComponent with a nice shadow border. Since not all JComponents handle opacity correctly, they will
be wrapped inside a DCPanel, which actually has the border.

@param comp
@param outline
@param margin
@return

public static DCPanel decorateWithShadow(final JComponent comp, final boolean outline, final int margin) {
        final DCPanel panel = new DCPanel();
        panel.setLayout(new BorderLayout());
        Border border = BORDER_SHADOW;
        if (outline) {
            border = new CompoundBorder(border, BORDER_THIN);
        }
        if (margin > 0) {
            border = new CompoundBorder(new EmptyBorder(margin, margin, margin, margin), border);
        }
        panel.setBorder(border);
        panel.add(comp, BorderLayout.CENTER);
        return panel;
    }

function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }

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


Question: Updates a block.

public function updateBlock(Block $block): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_block')
            ->set('layout_id', ':layout_id')
            ->set('depth', ':depth')
            ->set('path', ':path')
            ->set('parent_id', ':parent_id')
            ->set('placeholder', ':placeholder')
            ->set('position', ':position')
            ->set('definition_identifier', ':definition_identifier')
            ->set('view_type', ':view_type')
            ->set('item_view_type', ':item_view_type')
            ->set('name', ':name')
            ->set('translatable', ':translatable')
            ->set('main_locale', ':main_locale')
            ->set('always_available', ':always_available')
            ->set('config', ':config')
            ->where(
                $query->expr()->eq('id', ':id')
            )
            ->setParameter('id', $block->id, Type::INTEGER)
            ->setParameter('layout_id', $block->layoutId, Type::INTEGER)
            ->setParameter('depth', $block->depth, Type::STRING)
            ->setParameter('path', $block->path, Type::STRING)
            ->setParameter('parent_id', $block->parentId, Type::INTEGER)
            ->setParameter('placeholder', $block->placeholder, Type::STRING)
            ->setParameter('position', $block->position, Type::INTEGER)
            ->setParameter('definition_identifier', $block->definitionIdentifier, Type::STRING)
            ->setParameter('view_type', $block->viewType, Type::STRING)
            ->setParameter('item_view_type', $block->itemViewType, Type::STRING)
            ->setParameter('name', $block->name, Type::STRING)
            ->setParameter('translatable', $block->isTranslatable, Type::BOOLEAN)
            ->setParameter('main_locale', $block->mainLocale, Type::STRING)
            ->setParameter('always_available', $block->alwaysAvailable, Type::BOOLEAN)
            ->setParameter('config', $block->config, Type::JSON_ARRAY);

        $this->applyStatusCondition($query, $block->status);

        $query->execute();
    }

func (agg *Aggregator) flush() {
	if agg.minMetric != nil {
		agg.minMetric.Add(agg.currentBoundary, agg.agg.Min)
	}
	if agg.maxMetric != nil {
		agg.maxMetric.Add(agg.currentBoundary, agg.agg.Max)
	}
	if agg.sumMetric != nil {
		agg.sumMetric.Add(agg.currentBoundary, agg.agg.Sum)
	}
	if agg.cntMetric != nil {
		agg.cntMetric.Add(agg.currentBoundary, agg.agg.Cnt)
	}
	if agg.lstMetric != nil {
		agg.lstMetric.Add(agg.currentBoundary, agg.agg.Lst)
	}
	//msg := fmt.Sprintf("flushed cnt %v sum %f min %f max %f, reset the block", agg.agg.cnt, agg.agg.sum, agg.agg.min, agg.agg.max)
	agg.agg.Reset()
}

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


Question:
Generate UUID from hash and version.

@param $hash
@param $version
@return string

protected function getFromHash($hash, $version)
    {
        return sprintf('%08s-%04s-%04x-%04x-%12s',
    		// 32 bits for "time_low"
    		substr($hash, 0, 8),
    		// 16 bits for "time_mid"
    		substr($hash, 8, 4),
    		// 16 bits for "time_hi_and_version",
    		// four most significant bits holds version number 4
    		(hexdec(substr($hash, 12, 4)) & 0x0fff) | $version << 12,
    		// 16 bits, 8 bits for "clk_seq_hi_res",
    		// 8 bits for "clk_seq_low",
    		// two most significant bits holds zero and one for variant DCE1.1
    		(hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
    		// 48 bits for "node"
    		substr($hash, 20, 12)
		);
    }

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

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

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


Question:
Set object or bucket Access Control Policy

@param string $bucket Bucket name
@param string $uri Object URI
@param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
@return boolean

public static function setAccessControlPolicy($bucket, $uri = '', $acp = array())
	{
		$dom = new DOMDocument;
		$dom->formatOutput = true;
		$accessControlPolicy = $dom->createElement('AccessControlPolicy');
		$accessControlList = $dom->createElement('AccessControlList');

		// It seems the owner has to be passed along too
		$owner = $dom->createElement('Owner');
		$owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
		$owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
		$accessControlPolicy->appendChild($owner);

		foreach ($acp['acl'] as $g)
		{
			$grant = $dom->createElement('Grant');
			$grantee = $dom->createElement('Grantee');
			$grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
			if (isset($g['id']))
			{ // CanonicalUser (DisplayName is omitted)
				$grantee->setAttribute('xsi:type', 'CanonicalUser');
				$grantee->appendChild($dom->createElement('ID', $g['id']));
			}
			elseif (isset($g['email']))
			{ // AmazonCustomerByEmail
				$grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
				$grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
			}
			elseif ($g['type'] == 'Group')
			{ // Group
				$grantee->setAttribute('xsi:type', 'Group');
				$grantee->appendChild($dom->createElement('URI', $g['uri']));
			}
			$grant->appendChild($grantee);
			$grant->appendChild($dom->createElement('Permission', $g['permission']));
			$accessControlList->appendChild($grant);
		}

		$accessControlPolicy->appendChild($accessControlList);
		$dom->appendChild($accessControlPolicy);

		$rest = new S3Request('PUT', $bucket, $uri, self::$endpoint);
		$rest->setParameter('acl', null);
		$rest->data = $dom->saveXML();
		$rest->size = strlen($rest->data);
		$rest->setHeader('Content-Type', 'application/xml');
		$rest = $rest->getResponse();
		if ($rest->error === false && $rest->code !== 200)
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		if ($rest->error !== false)
		{
			self::__triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
			$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
			return false;
		}
		return true;
	}

public function authenticate($code)
    {
        // Validate code
        if (!$code || strlen($code) != 6) {
            throw new Exception('Invalid authorization code');
        }

        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->clientSecret) {
            throw new Exception('Client secret is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        $fields = [
            'client_id'     => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code'          => $code,
            'redirect_uri'  => urlencode($this->redirectUri),
            'grant_type'    => 'authorization_code'
        ];

        $url  = 'https://';
        $url .= $this->level . '.';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::TOKEN;

        $this->http->setUrl($url)
                   ->setPostFields($fields)
                   ->setHeader(['Accept' => 'application/json']);

        $data = json_decode($this->http->execute());

        if (isset($data->access_token)) {
            $this->setAccessToken($data->access_token);
            $this->setOrcid($data->orcid);
        } else {
            // Seems like the response format changes on occasion...not sure what's going on there?
            $error = (isset($data->error_description)) ? $data->error_description : $data->{'error-desc'}->value;

            throw new Exception($error);
        }

        return $this;
    }

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


Question:
Special comparator  that  allows FactHandles to  be  keys, but always  checks
equals with the  identity of the  objects involved

public boolean equal(final Object o1,
                         Object o2) {
        if ( o1 == o2 ) {
            return true;

        }
        // o1 is a FactHandle, so just check their id's are the same
        if ( o1 instanceof FactHandle ) {
            return ((InternalFactHandle)o1).getId() == ((InternalFactHandle)o2).getId() ;
        }

        // o1 is an object, so unwrap o2 for comparison
        final InternalFactHandle handle = ((InternalFactHandle) o2);
        o2 = handle.getObject();
        return o1 == o2 || o2.equals( o1 );
    }

func (s *Service) ComparePassword(ctx context.Context, name string, password string) error {
	return s.kv.View(ctx, func(tx Tx) error {
		return s.comparePassword(ctx, tx, name, password)
	})
}

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


Question:
Checks if the $idna_info parameter of idn_to_ascii() or idn_to_utf8()
contains errors.

@param array $info  Fourth parameter to idn_to_ascii() or idn_to_utf8().

@throws Horde_Idna_Exception

protected static function _checkForError($info)
    {
        switch (true) {
        case $info['errors'] & IDNA_ERROR_EMPTY_LABEL:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Domain name is empty"
            ));
        case $info['errors'] & IDNA_ERROR_LABEL_TOO_LONG:
        case $info['errors'] & IDNA_ERROR_DOMAIN_NAME_TOO_LONG:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Domain name is too long"
            ));
        case $info['errors'] & IDNA_ERROR_LEADING_HYPHEN:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Starts with a hyphen"
            ));
        case $info['errors'] & IDNA_ERROR_TRAILING_HYPHEN:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Ends with a hyphen"
            ));
        case $info['errors'] & IDNA_ERROR_HYPHEN_3_4:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Contains hyphen in the third and fourth positions"
            ));
        case $info['errors'] & IDNA_ERROR_LEADING_COMBINING_MARK:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Starts with a combining mark"
            ));
        case $info['errors'] & IDNA_ERROR_DISALLOWED:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Contains disallowed characters"
            ));
        case $info['errors'] & IDNA_ERROR_PUNYCODE:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Starts with \"xn--\" but does not contain valid Punycode"
            ));
        case $info['errors'] & IDNA_ERROR_LABEL_HAS_DOT:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Contains a dot"
            ));
        case $info['errors'] & IDNA_ERROR_INVALID_ACE_LABEL:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "ACE label does not contain a valid label string"
            ));
        case $info['errors'] & IDNA_ERROR_BIDI:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Does not meet the IDNA BiDi requirements (for right-to-left characters)"
            ));
        case $info['errors'] & IDNA_ERROR_CONTEXTJ:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Does not meet the IDNA CONTEXTJ requirements"
            ));
        case $info['errors']:
            throw new Horde_Idna_Exception(Horde_Idna_Translation::t(
                "Unknown error"
            ));
        }
    }

func builtinChar(args []types.Datum, ctx context.Context) (d types.Datum, err error) {
	// The kinds of args are int or string, and the last one represents charset.
	var resultStr string
	var intSlice = make([]int64, 0, len(args)-1)

	for _, datum := range args[:len(args)-1] {
		switch datum.Kind() {
		case types.KindNull:
			continue
		case types.KindString:
			i, err := datum.ToInt64(ctx.GetSessionVars().StmtCtx)
			if err != nil {
				d.SetString(resultStr)
				return d, nil
			}
			intSlice = append(intSlice, i)
		case types.KindInt64, types.KindUint64, types.KindMysqlHex, types.KindFloat32, types.KindFloat64, types.KindMysqlDecimal:
			x, err := datum.Cast(ctx.GetSessionVars().StmtCtx, types.NewFieldType(mysql.TypeLonglong))
			if err != nil {
				return d, errors.Trace(err)
			}
			intSlice = append(intSlice, x.GetInt64())
		default:
			return d, errors.Errorf("Char invalid args, need int or string but get %T", args[0].GetValue())
		}
	}

	resultStr = string(convertInt64ToBytes(intSlice))

	// The last argument represents the charset name after "using".
	// If it is nil, the default charset utf8 is used.
	argCharset := args[len(args)-1]
	if !argCharset.IsNull() {
		char, err := argCharset.ToString()
		if err != nil {
			return d, errors.Trace(err)
		}

		if strings.ToLower(char) == "ascii" || strings.HasPrefix(strings.ToLower(char), "utf8") {
			d.SetString(resultStr)
			return d, nil
		}

		encoding, _ := charset.Lookup(char)
		if encoding == nil {
			return d, errors.Errorf("unknown encoding: %s", char)
		}

		resultStr, _, err = transform.String(encoding.NewDecoder(), resultStr)
		if err != nil {
			log.Printf("Convert %s to %s with error: %v", resultStr, char, err)
			return d, errors.Trace(err)
		}
	}
	d.SetString(resultStr)
	return d, nil
}

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


Question:
Is a max row limit indicated?

@param selection The row selection options
@return Whether a max row limit was indicated

public static boolean hasMaxRows(RowSelection selection) {
		return selection != null && selection.getMaxRows() != null && selection.getMaxRows() > 0;
	}

def get_arguments():
    """"""
    import argparse
    parser = argparse.ArgumentParser(
        description='Plot spectral responses for a set of satellite imagers')

    parser.add_argument("--platform_name", '-p', nargs='*',
                        help="The Platform name",
                        type=str, required=True)
    parser.add_argument("--sensor", '-s', nargs='*',
                        help="The sensor/instrument name",
                        type=str, required=True)
    parser.add_argument("-x", "--xlimits", nargs=2,
                        help=("x-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-y", "--ylimits", nargs=2,
                        help=("y-axis boundaries for plot"),
                        default=None, type=float)
    parser.add_argument("-t", "--minimum_response",
                        help=("Minimum response: Any response lower than " +
                              "this will be ignored when plotting"),
                        default=0.015, type=float)

    parser.add_argument("-no_platform_name_in_legend", help=("No platform name in legend"),
                        action='store_true')
    parser.add_argument("--title", help=("Plot title"),
                        default=None, type=str)
    parser.add_argument("--wavelength_resolution",
                        help=("The step in wavelength (nanometers) when scanning\n" +
                              " the spectral range trying to find bands"),
                        default=0.005, type=float)
    parser.add_argument("-o", "--filename", help=("Output plot file name"),
                        default=None, type=str)
    parser.add_argument(
        "-v", '--verbose', help=("Turn logging on"), action='store_true')

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("--bandname", '-b',
                       help="The sensor band name", type=str)
    group.add_argument("--wavelength", "-w", type=float,
                       help='the approximate spectral wavelength in micron')
    group.add_argument("--range", "-r", nargs='*',
                       help="The wavelength range for the plot",
                       default=[None, None], type=float)

    return parser.parse_args()

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


Question:
/*
(non-Javadoc)

@see com.ibm.wsspi.http.HttpResponse#getTrailers()

@Override
    public void setTrailer(String name, String value) {

        HttpTrailers trailers = message.createTrailers();
        HeaderKeys key = HttpHeaderKeys.find(name);

        if (trailers.containsDeferredTrailer(key)) {
            trailers.removeDeferredTrailer(key);
        }

        HttpTrailerGenerator generator = new HttpTrailerGeneratorImpl(key, value);
        trailers.setDeferredTrailer(key, generator);

        return;
    }

public void reply(HeadersAmp headers,
                    String to,
                    long qid,
                    Object value)
    throws IOException
  {
    if (log.isLoggable(Level.FINEST)) {
      log.finest(this + " reply " + value
                + "\n  {to:" + to + "," + headers + "}");
    }

    try {
      JsonWriterImpl jOut = _jOut;
      jOut.init();

      jOut.writeStartArray();
      jOut.write("reply");

      writeHeaders(jOut, headers);

      jOut.write(to);
      jOut.write(qid);

      jOut.write(value);

      jOut.writeEndArray();

      jOut.close();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);

      throw e;
    }
  }

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


Question:
// AddPoolMember adds a node/member to the given pool. <member> must be in the form
// of <node>:<port>, i.e.: "web-server1:443".

func (b *BigIP) AddPoolMember(pool, member string) error {
	config := &poolMember{
		Name: member,
	}

	return b.post(config, uriLtm, uriPool, pool, uriPoolMember)
}

protected function _stringNode($delimiter = '', $heredoc = false)
    {
        $this->_codeNode();
        $token = $this->_stream->current(true);
        if (!$delimiter) {
            $this->_states['body'] = $token[1];
        } elseif ($delimiter === '"') {
            $this->_states['body'] = $token[1] . $this->_stream->next('"');
        } else {
            $this->_states['body'] = $token[1] . $this->_stream->nextSequence($delimiter);
        }
        if ($heredoc) {
            $this->_states['body'] .= $this->_stream->next([';']);
        }

        $node = new NodeDef($this->_states['body'], 'string');
        $this->_contextualize($node);
        return $node;
    }

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


Question:
Gets head.

@return the head

public HString head() {
      return tokens()
                .stream()
                .filter(t -> t
                                .parent()
                                .isEmpty())
                .map(Cast::<HString>as)
                .findFirst()
                .orElseGet(() -> tokens()
                                    .stream()
                                    .filter(t -> !this.overlaps(t.parent()))
                                    .map(Cast::<HString>as)
                                    .findFirst()
                                    .orElse(this));
   }

def ack(self, id, transaction=None, receipt=None):

        assert id is not None, "'id' is required"
        headers = {HDR_MESSAGE_ID: id}
        if transaction:
            headers[HDR_TRANSACTION] = transaction
        if receipt:
            headers[HDR_RECEIPT] = receipt
        self.send_frame(CMD_ACK, headers)

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


Question: // Unmarshal implements JSONInterface

func (StdJSON) Unmarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}

func (c Config) MarshalJSON() ([]byte, error) {
	m := map[string]interface{}{
		"version":  c.Version,
		"services": c.Services,
	}

	if len(c.Networks) > 0 {
		m["networks"] = c.Networks
	}
	if len(c.Volumes) > 0 {
		m["volumes"] = c.Volumes
	}
	if len(c.Secrets) > 0 {
		m["secrets"] = c.Secrets
	}
	if len(c.Configs) > 0 {
		m["configs"] = c.Configs
	}
	for k, v := range c.Extras {
		m[k] = v
	}
	return json.Marshal(m)
}

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


Question:
// Create a new add-on.
//
// appIdentity is the unique identifier of the Addon's App. plan is the unique
// identifier of this plan or unique name of this plan. options is the struct of
// optional parameters for this action.

func (c *Client) AddonCreate(appIdentity string, plan string, options *AddonCreateOpts) (*Addon, error) {
	params := struct {
		Plan   string             `json:"plan"`
		Config *map[string]string `json:"config,omitempty"`
	}{
		Plan: plan,
	}
	if options != nil {
		params.Config = options.Config
	}
	var addonRes Addon
	return &addonRes, c.Post(&addonRes, "/apps/"+appIdentity+"/addons", params)
}

func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData) (st *Channel, err error) {
	body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}

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


Question: Creates the list of widgets for this dialog.<p>

@Override
    protected void defineWidgets() {

        List selectOptions = getModulesFromServer();

        if (selectOptions.isEmpty()) {
            // no import modules available, display message
            addWidget(
                new CmsWidgetDialogParameter(
                    this,
                    "moduleupload",
                    PAGES[0],
                    new CmsDisplayWidget(key(Messages.GUI_MODULES_IMPORT_NOT_AVAILABLE_0))));
        } else {
            // add the file select box widget
            addWidget(new CmsWidgetDialogParameter(this, "moduleupload", PAGES[0], new CmsSelectWidget(selectOptions)));
        }
    }

def flush(self):

        items = []

        for data in self._to_put:
            items.append(encode_put(self.connection.dynamizer, data))

        for data in self._to_delete:
            items.append(encode_delete(self.connection.dynamizer, data))
        self._write(items)
        self._to_put = []
        self._to_delete = []

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


Question:
@param Model $parent

@since  1.1.0

@author Eddilbert Macharia (http://eddmash.com) <edd.cowan@gmail.com>

public function setupProxy(Model $parent)
    {
        $this->dbTable = $parent->getMeta()->getDbTable();
        $this->primaryKey = $parent->getMeta()->primaryKey;
    }

def version_history(soup, html_flag=True):
    ""
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)
    version_history = []
    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
    for tag in related_object_tags:
        article_version = OrderedDict()
        date_tag = first(raw_parser.date(tag))
        if date_tag:
            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
            (day, month, year) = ymd(date_tag)
            article_version['day'] = day
            article_version['month'] = month
            article_version['year'] = year
            article_version['date'] = date_struct_nn(year, month, day)
        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
        set_if_value(article_version, "comment",
                     convert(node_contents_str(first(raw_parser.comment(tag)))))
        version_history.append(article_version)
    return version_history

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


Question:
just like set but it can
captures all output in a closure and set that.

@param string			$key
@param callback		$callback
@return void

public function capture( $key, $callback )
	{
		return $this->set( $key, CCStr::capture( $callback, $this ) );
	}

func (s *GetWebACLOutput) SetWebACL(v *WebACL) *GetWebACLOutput {
	s.WebACL = v
	return s
}

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


Question: ===================== helper method ==================

private CommunicationParam buildParams(String addr) {
        CommunicationParam params = new CommunicationParam();
        String[] strs = StringUtils.split(addr, ":");
        if (strs == null || strs.length != 2) {
            throw new IllegalArgumentException("addr example: 127.0.0.1:1099");
        }
        InetAddress address = null;
        try {
            address = InetAddress.getByName(strs[0]);
        } catch (UnknownHostException e) {
            throw new CommunicationException("addr_error", "addr[" + addr + "] is unknow!");
        }
        params.setIp(address.getHostAddress());
        params.setPort(Integer.valueOf(strs[1]));
        return params;
    }

def get_cleanup_hitters_by_year(year)
      results = []
      games = all_games(year)
      games.each do |game|
        boxscore = game.get_boxscore
        hitters = boxscore.get_cleanup_hitters
        if game.home_team_abbrev == @abrev
          results << hitters[1]
        else
          results << hitters[0]
        end
      end
      results
    end

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


Question: Marshall the given parameter object.

public void marshall(ListThingsRequest listThingsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listThingsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeName(), ATTRIBUTENAME_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getAttributeValue(), ATTRIBUTEVALUE_BINDING);
            protocolMarshaller.marshall(listThingsRequest.getThingTypeName(), THINGTYPENAME_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: // GetTeamFromChannel returns teamId belonging to channel (DM channels have no teamId).

func (m *MMClient) GetTeamFromChannel(channelId string) string { //nolint:golint
	m.RLock()
	defer m.RUnlock()
	var channels []*model.Channel
	for _, t := range m.OtherTeams {
		channels = append(channels, t.Channels...)
		if t.MoreChannels != nil {
			channels = append(channels, t.MoreChannels...)
		}
		for _, c := range channels {
			if c.Id == channelId {
				if c.Type == model.CHANNEL_GROUP {
					return "G"
				}
				return t.Id
			}
		}
		channels = nil
	}
	return ""
}

public function contextHasMessages($context_data)
    {
        $qb2 = $this->_em->createQueryBuilder();
        $qb2->select('mc')
              ->from($this->_entityName, 'mc')
              ->where('mc.system = :system')
              ->andWhere('mc.object_name = :object_name')
              ->andWhere('mc.external_id = :external_id')
              ->setParameter("system", $context_data['system'])
              ->setParameter("object_name", $context_data['object_name'])
              ->setParameter("external_id", $context_data['external_id'])
              ->setMaxResults(1);

        $message_context = $qb2->getQuery()->getResult();
        return !empty($message_context);
    }

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