Question:
Sets the attachment.
@param string  $attachment  An URL or the filepath, or the data.
@param string  $filename    The filename.
@return $this

function setAttachment(string $attachment, string $filename = '') {
        $this->attachment = $attachment;
        $this->filename = $filename;
        return $this;
    }

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

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


Question:
Check access route for user.
@param string|array $route
@param integer|User $user
@return boolean

public static function checkRoute($route, $params = [], $user = null)
    {
        $config = Configs::instance();
        $r = static::normalizeRoute($route, $config->advanced);
        if ($config->onlyRegisteredRoute && !isset(static::getRegisteredRoutes()[$r])) {
            return true;
        }

        if ($user === null) {
            $user = Yii::$app->getUser();
        }
        $userId = $user instanceof User ? $user->getId() : $user;

        if ($config->strict) {
            if ($user->can($r, $params)) {
                return true;
            }
            while (($pos = strrpos($r, '/')) > 0) {
                $r = substr($r, 0, $pos);
                if ($user->can($r . '/*', $params)) {
                    return true;
                }
            }
            return $user->can('/*', $params);
        } else {
            $routes = static::getRoutesByUser($userId);
            if (isset($routes[$r])) {
                return true;
            }
            while (($pos = strrpos($r, '/')) > 0) {
                $r = substr($r, 0, $pos);
                if (isset($routes[$r . '/*'])) {
                    return true;
                }
            }
            return isset($routes['/*']);
        }
    }

public function getCurrentUser()
    {
        if ($this->currentuser === null) {
            $hash = $this->getCurrentSessionHash();
            if ($hash === false) {
                return false;
            }

            $uid = $this->getSessionUID($hash);
            if ($uid === false) {
                return false;
            }

            $this->currentuser = $this->getUser($uid);
        }
        return $this->currentuser;
    }

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


Question:
Custom attribute writer method checking allowed values (enum).
 @param [Object] ell_status Object to be assigned

def ell_status=(ell_status)
      validator = EnumAttributeValidator.new('String', ["Y", "N", ""])
      unless validator.valid?(ell_status)
        fail ArgumentError, "invalid value for 'ell_status', must be one of #{validator.allowable_values}."
      end
      @ell_status = ell_status
    end

public function setParameter($name, $parameter)
  {
    if ($this->isLocked()) {
      return $this->getObj()->setParameter($name, $parameter)->setLocked();
    } else {
      return parent::setParameter($name, $parameter);
    }
  }

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


Question:
After routing is done, check if there is any current route and set up
property `$this->selfRouteName` about currently matched route name
to complete any time later `self` url.
@return \MvcCore\Router

protected function routeSetUpSelfRouteNameIfAny () {
		/** @var $this \MvcCore\Router */
		if ($this->currentRoute instanceof \MvcCore\IRoute)
			$this->selfRouteName = $this->anyRoutesConfigured
				? $this->currentRoute->GetName()
				: $this->currentRoute->GetControllerAction();
		return $this;
	}

function () {
			var oRouter = UIComponent.getRouterFor(this);
			if (!this.sNamespace || this.sNamespace === "/") {
				oRouter.navTo("Layers");
			} else {
				var sSplittedNamespace = this.sNamespace.split("/");
				sSplittedNamespace.splice(-2, 1);
				var sTargetNamespace = sSplittedNamespace.join("/");
				oRouter.navTo("LayerContentMaster", {"layer": this.sLayer, "namespace": encodeURIComponent(sTargetNamespace)}, true);
			}
		}

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


Question: // UnmarshalConfig decodes a config from binary protobuf data.

func UnmarshalConfig(data []byte, c *chronograf.Config) error {
	var pb Config
	if err := UnmarshalConfigPB(data, &pb); err != nil {
		return err
	}
	if pb.Auth == nil {
		return fmt.Errorf("auth config is nil")
	}
	c.Auth.SuperAdminNewUsers = pb.Auth.SuperAdminNewUsers

	return nil
}

func (mcs *ConsenterSupport) WriteBlock(block *cb.Block, encodedMetadataValue []byte) {
	if encodedMetadataValue != nil {
		block.Metadata.Metadata[cb.BlockMetadataIndex_ORDERER] = utils.MarshalOrPanic(&cb.Metadata{Value: encodedMetadataValue})
	}
	mcs.Append(block)
}

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


Question:
Start the week with a table row

@since 0.1.0

protected function get_row_cell( $iterator = 1, $start_day = 1 ) {

		// Start an output buffer
		ob_start(); ?>

		<td class="<?php echo $this->get_day_classes( $iterator, $start_day ); ?>">

				<?php echo $this->get_posts_for_cell( $iterator ); ?>

		<?php

		// Return the output buffer
		return ob_get_clean();
	}

def _get_current_names(current, dsn, pc):

    _table_name = ""
    _variable_name = ""
    # Get key info
    try:
        _table_name = current['{}_tableName'.format(pc)]
        _variable_name = current['{}_variableName'.format(pc)]
    except Exception as e:
        print("Error: Unable to collapse time series: {}, {}".format(dsn, e))
        logger_ts.error("get_current: {}, {}".format(dsn, e))
    return _table_name, _variable_name

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


Question:
Make extref fields map and set it to parameter

@param ContainerBuilder $container container builder
@return void

public function process(ContainerBuilder $container)
    {
        $this->documentMap = $container->get('graviton.document.map');

        $map = [];

        $services = array_keys($container->findTaggedServiceIds('graviton.rest'));
        foreach ($services as $id) {
            list($ns, $bundle, , $doc) = explode('.', $id);
            if (empty($bundle) || empty($doc)) {
                continue;
            }
            if ($bundle === 'core' && $doc === 'main') {
                continue;
            }

            $className = $this->getServiceDocument(
                $container->getDefinition($id),
                $ns,
                $bundle,
                $doc
            );
            $extRefFields = $this->processDocument($this->documentMap->getDocument($className));
            $routePrefix = strtolower($ns.'.'.$bundle.'.'.'rest'.'.'.$doc);

            $map[$routePrefix.'.get'] = $extRefFields;
            $map[$routePrefix.'.all'] = $extRefFields;
        }

        $container->setParameter('graviton.document.extref.fields', $map);
    }

public final FctBnCnvIbnToColumnValues
    lazyGetFctBnCnvIbnToColumnValues() throws Exception {
    String beanName = getFctBnCnvIbnToColumnValuesName();
    FctBnCnvIbnToColumnValues fctBnCnvIbnToColumnValues =
      (FctBnCnvIbnToColumnValues) this.beansMap.get(beanName);
    if (fctBnCnvIbnToColumnValues == null) {
      fctBnCnvIbnToColumnValues = new FctBnCnvIbnToColumnValues();
      fctBnCnvIbnToColumnValues.setUtlReflection(lazyGetUtlReflection());
      fctBnCnvIbnToColumnValues.setFieldsRapiHolder(lazyGetHolderRapiFields());
      fctBnCnvIbnToColumnValues
        .setGettersRapiHolder(lazyGetHolderRapiGetters());
      fctBnCnvIbnToColumnValues.setIsNeedsToSqlEscape(getIsNeedsToSqlEscape());
      fctBnCnvIbnToColumnValues.setSrvSqlEscape(lazyGetSrvSqlEscape());
      this.beansMap.put(beanName, fctBnCnvIbnToColumnValues);
      lazyGetLogger().info(null, AFactoryAppBeans.class, beanName
        + " has been created.");
    }
    return fctBnCnvIbnToColumnValues;
  }

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


Question:
// registerQueryResponse is used to setup the listeners for the query,
// and to schedule closing the query after the timeout.

func (s *Serf) registerQueryResponse(timeout time.Duration, resp *QueryResponse) {
	s.queryLock.Lock()
	defer s.queryLock.Unlock()

	// Map the LTime to the QueryResponse. This is necessarily 1-to-1,
	// since we increment the time for each new query.
	s.queryResponse[resp.lTime] = resp

	// Setup a timer to close the response and deregister after the timeout
	time.AfterFunc(timeout, func() {
		s.queryLock.Lock()
		delete(s.queryResponse, resp.lTime)
		resp.Close()
		s.queryLock.Unlock()
	})
}

def quit(self, exit_code=0, event=None):

        # --- Running on_close components methods. ---
        for component in reversed(self.__components_manager.list_components()):
            interface = self.__components_manager.get_interface(component)
            if not interface:
                continue

            if not interface.activated:
                continue

            if not hasattr(interface, "on_close"):
                continue

            if not interface.on_close():
                event and event.ignore()
                return

        # Storing current layout.
        self.__layouts_manager.store_startup_layout()
        self.__settings.settings.sync()

        # Stopping worker threads.
        for worker_thread in self.__worker_threads:
            LOGGER.debug("> Stopping worker thread: '{0}'.".format(worker_thread))
            if not worker_thread.isFinished():
                worker_thread.quit()
            worker_thread.wait()

        foundations.verbose.remove_logging_handler(self.__logging_file_handler)
        foundations.verbose.remove_logging_handler(self.__logging_session_handler)
        # foundations.verbose.remove_logging_handler(self.__logging_console_handler)

        # Stopping the Application timer.
        self.__timer.stop()
        self.__timer = None

        self.deleteLater()
        event and event.accept()

        exit(exit_code)

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


Question:
Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack.

        Optimizations:
         * If 2nd operand is 1 => Return 0
         * If 2nd operand = 2^n => do AND (2^n - 1)

def _modu16(ins):
    '''
    '''
    op1, op2 = tuple(ins.quad[2:])

    if is_int(op2):
        op2 = int16(op2)
        output = _16bit_oper(op1)

        if op2 == 1:
            if op2[0] in ('_', '$'):
                output = []  # Optimization: Discard previous op if not from the stack

            output.append('ld hl, 0')
            output.append('push hl')
            return output

        if is_2n(op2):
            k = op2 - 1
            if op2 > 255:  # only affects H
                output.append('ld a, h')
                output.append('and %i' % (k >> 8))
                output.append('ld h, a')
            else:
                output.append('ld h, 0')  # High part goes 0
                output.append('ld a, l')
                output.append('and %i' % (k % 0xFF))
                output.append('ld l, a')

            output.append('push hl')
            return output

        output.append('ld de, %i' % op2)
    else:
        output = _16bit_oper(op1, op2)

    output.append('call __MODU16')
    output.append('push hl')
    REQUIRES.add('div16.asm')
    return output

func Words(x uint64) []big.Word {
	if bits.UintSize == 32 {
		return []big.Word{big.Word(x), big.Word(x >> 32)}
	}
	return []big.Word{big.Word(x)}
}

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


Question:
Creates the file menu.

@param listener
the listener

@return the j menu

protected JMenu newEditMenu(final ActionListener listener)
	{
		final JMenu menu = new JMenu("Edit");
		menu.setMnemonic('E');

		return menu;
	}

public static void pruneMenus(BaseComponent parent) {
        while (parent != null && parent instanceof BaseMenuComponent) {
            if (parent.getChildren().isEmpty()) {
                BaseComponent newParent = parent.getParent();
                parent.destroy();
                parent = newParent;
            } else {
                break;
            }
        }
    }

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


Question: //CheckAccessToken 检验access_token是否有效

func (oauth *Oauth) CheckAccessToken(accessToken, openID string) (b bool, err error) {
	urlStr := fmt.Sprintf(checkAccessTokenURL, accessToken, openID)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	var result util.CommonError
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		b = false
		return
	}
	b = true
	return
}

function assertTokenParams()
    {
        # Assert Params

        if ( null === $this->getCode() )
            throw new exMissingGrantRequestParams('Request Param "code" must Set.');

        if ( null === $this->getClientId() || null === $this->getClientSecret() )
            throw new exMissingGrantRequestParams('Request Param "client_id" & "client_secret" must Set.');

        # Build Request Params

        $params = $this->__toArray();
        unset($params['response_type']);

        return $params;
    }

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


Question: // Flush deletes all cached data.

func (c *NodbCacher) Flush() (err error) {
	if err = os.RemoveAll(c.filepath); err != nil {
		return err
	}

	c.dbs.Close()
	c.db = nil
	c.dbs = nil

	return c.new()
}

func (engine *Engine) NoCache() *Session {
	session := engine.NewSession()
	session.isAutoClose = true
	return session.NoCache()
}

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


Question:
Changes the current page.

@param int $page the page to jump to.

@return Pager

public function setPage($page)
    {
        $this->offset = (max(1, (int) $page) - 1) * $this->perPage;

        return $this;
    }

public static <S extends HasAttachHandlers> void fire(S source, PageState pageState,
            JQMPage prevPage, JQMPage nextPage) {
      if (TYPE != null) {
        JQMPageEvent event = new JQMPageEvent(pageState, prevPage, nextPage);
        source.fireEvent(event);
      }
    }

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


Question: // defaultVersionFor is shared between defaultServerUrlFor and RESTClientFor

func defaultVersionFor(config *Config) *unversioned.GroupVersion {
	if config.GroupVersion == nil {
		// Clients default to the preferred code API version
		// TODO: implement version negotiation (highest version supported by server)
		// TODO this drops out when groupmeta is refactored
		copyGroupVersion := latest.GroupOrDie("").GroupVersion
		return &copyGroupVersion
	}

	return config.GroupVersion
}

def fetch_synchronous(self, endpoint_name, query_params=None):
        """"""

        endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name

        if query_params is None:
            query_params = {}

        return self._request_client.get(endpoint_url, query_params)

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


Question:
This method verifies that the given {@code value} is {@link #isContained(Object) contained in this range} .

@param value is the value to check.
@throws ValueOutOfRangeException if not {@link #isContained(Object) contained}.

public void verifyContained(V value) throws ValueOutOfRangeException {

    if (!isContained(value)) {
      throw new ValueOutOfRangeException(null, value, this.min, this.max);
    }
  }

@SuppressWarnings("unchecked")
    @Trivial
    private JSONObject toJSONObjectForThrowable(Map<String, ?> errorInfo, Throwable error) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(this, tc, "toJSONObjectForThrowable", errorInfo, error);

        LinkedHashMap<String, List<?>> addedInfo = new LinkedHashMap<String, List<?>>();
        for (Map.Entry<String, ?> entry : errorInfo.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof List)
                addedInfo.put(entry.getKey(), (List<?>) value);
        }

        JSONObject json = new OrderedJSONObject();

        int index = 0;
        JSONObject current = json;
        Set<Throwable> causes = new HashSet<Throwable>(); // avoid cycles in exception chain
        for (Throwable cause = error; cause != null && causes.add(cause); index++) {
            // custom attributes for position in exception chain (for example, sqlState and errorCode for dataSource)
            for (Map.Entry<String, List<?>> entry : addedInfo.entrySet()) {
                List<?> values = entry.getValue();
                if (values.size() > index) {
                    Object value = values.get(index);
                    if (value != null)
                        current.put(entry.getKey(), value);
                }
            }

            current.put("class", cause.getClass().getName());
            current.put("message", cause.getMessage());

            JSONArray stack = new JSONArray();
            for (StackTraceElement element : cause.getStackTrace())
                stack.add(element.toString());
            current.put("stack", stack);

            if ((cause = cause.getCause()) != null) {
                Map<String, Object> parent = current;
                parent.put("cause", current = new OrderedJSONObject());
            }
        }

        return json;
    }

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


Question:
{@inheritdoc}

Overrides \Drupal\Core\TempStore\PrivateTempStore::get().

public function get($key, $default = NULL) {
    $value = parent::get($key);

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

    return $default;
  }

def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_fname=None,
                    mod_loader=None, pkg_name=None):
    """"""
    with _ModifiedArgv0(mod_fname):
        with _TempModule(mod_name) as temp_module:
            mod_globals = temp_module.module.__dict__
            _run_code(code, mod_globals, init_globals,
                      mod_name, mod_fname, mod_loader, pkg_name)
    # Copy the globals of the temporary module, as they
    # may be cleared when the temporary module goes away
    return mod_globals.copy()

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


Question: // Slug returns the slug format for this BuildConfigVersion (User/Name)

func (bv *BuildConfigVersion) Slug() string {
	return fmt.Sprintf("%s/%s", bv.User, bv.Name)
}

def apply_configuration(yml)
      if yml.include?("packages")
        yml["packages"].each do |k, v|
          valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
          @package_info[k] = valid_data
        end
      end

      if yml.include?("platforms")
        yml["platforms"].each do |k, v|
          valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
          @platform_info[k] = valid_data
        end
      end

      if yml.include?("compile")
        valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
        valid_data.each { |k, v| @compile_info[k] = v }
      end

      if yml.include?("unittest")
        valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
        valid_data.each { |k, v| @unittest_info[k] = v }
      end

      self
    end

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


Question:
Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
Replace with a simple call to Unsafe.getUnsafe when integrating
into a jdk.

@return a sun.misc.Unsafe

static Unsafe getUnsafe() {
      try {
         return Unsafe.getUnsafe();
      } catch (SecurityException tryReflectionInstead) {}
      try {
         return java.security.AccessController.doPrivileged
                 (new java.security.PrivilegedExceptionAction<Unsafe>() {
                    public Unsafe run() throws Exception {
                       Class<Unsafe> k = Unsafe.class;
                       for (java.lang.reflect.Field f : k.getDeclaredFields()) {
                          f.setAccessible(true);
                          Object x = f.get(null);
                          if (k.isInstance(x))
                             return k.cast(x);
                       }
                       throw new NoSuchFieldError("the Unsafe");
                    }});
      } catch (java.security.PrivilegedActionException e) {
         throw new RuntimeException("Could not initialize intrinsics",
                 e.getCause());
      }
   }

public InternalRunner create(Class<?> klass, Supplier<MockitoTestListener> listenerSupplier) throws InvocationTargetException {
        try {
            String runnerClassName = "org.mockito.internal.runners.DefaultInternalRunner";
            //Warning: I'm using String literal on purpose!
            //When JUnit is not on classpath, we want the code to throw exception here so that we can catch it
            //If we statically link the class, we will get Error when class is loaded
            return new RunnerProvider().newInstance(runnerClassName, klass, listenerSupplier);
        } catch (InvocationTargetException e) {
            if (!hasTestMethods(klass)) {
                throw new MockitoException(
                    "\n" +
                    "\n" +
                    "No tests found in " + klass.getSimpleName() + "\n" +
                    "Is the method annotated with @Test?\n" +
                    "Is the method public?\n"
                    , e);
            }
            throw e;
        } catch (Throwable t) {
            throw new MockitoException(
                    "\n" +
                    "\n" +
                    "MockitoRunner can only be used with JUnit 4.5 or higher.\n" +
                    "You can upgrade your JUnit version or write your own Runner (please consider contributing your runner to the Mockito community).\n" +
                    "Bear in mind that you can still enjoy all features of the framework without using runners (they are completely optional).\n" +
                    "If you get this error despite using JUnit 4.5 or higher then please report this error to the mockito mailing list.\n"
                    , t);
        }
    }

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


Question:
Write short.

@param value the value
@return the string

public static String writeShort(Short value) {
		if (value==null) return null;

		return Short.toString(value);
	}

public void writeSuccessResult(int line) {
        logger.debug("Write Success result => line:{}", line);
        writeValue(resultColumnName, line, Messages.getMessage(Messages.SUCCESS_MESSAGE));
    }

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


Question: Returns all the registered {@link MarkupFormatterDescriptor}s.

public static DescriptorExtensionList<MarkupFormatter,MarkupFormatterDescriptor> all() {
        return Jenkins.getInstance().<MarkupFormatter,MarkupFormatterDescriptor>
                                    getDescriptorList(MarkupFormatter.class);
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
Check if the timedout flag was previously set and throw an exception if it was.
Otherwise, return the remaining timeout time, in nanoseconds.

@return the time remaining, in nanoseconds

public long check() {
        long remaining = 0;
        lock.readLock().lock();
        try {
            if (this.timedout) {
                // Note: this clears the interrupted flag if it was set
                // Assumption is that the interruption was caused by the Timeout
                boolean wasInterrupted = Thread.interrupted();

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    if (wasInterrupted) {
                        Tr.debug(tc, "{0}: Throwing timeout exception and clearing interrupted flag", getDescriptor());
                    } else {
                        Tr.debug(tc, "{0}: Throwing timeout exception", getDescriptor());
                    }
                }

                throw new TimeoutException(Tr.formatMessage(tc, "timeout.occurred.CWMFT0000E"));
            }
            long now = System.nanoTime();
            remaining = this.targetEnd - now;

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                debugTime("?Start ", this.start);
                debugTime("?Target", this.targetEnd);
                debugTime("?Now   ", now);
                debugTime("?Remain", remaining);
            }
        } finally {
            lock.readLock().unlock();
        }
        return remaining;
    }

func (r *retrier) NextInterval(retry int) time.Duration {
	return r.backoff.Next(retry)
}

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


Question: // Size returns the size or cardinality of this set

func (s *Set) Size() int {
	// Lock set for read
	s.mutex.RLock()
	defer s.mutex.RUnlock()

	return len(s.m)
}

public function getCaption()
    {
        return $this->caption ?: (isset($this->ui['caption']) ? $this->ui['caption'] :
            ucwords(str_replace('_', ' ', $this->short_name)));
    }

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


Question: // NewPayloadsBuffer is factory function to create new payloads buffer

func NewPayloadsBuffer(next uint64) PayloadsBuffer {
	return &PayloadsBufferImpl{
		buf:       make(map[uint64]*proto.Payload),
		readyChan: make(chan struct{}, 1),
		next:      next,
		logger:    util.GetLogger(util.StateLogger, ""),
	}
}

func NewSnapFactory(encrypter encryption.Encrypter, decrypter encryption.Decrypter) SnapFactory {
	return snapCryptor{
		encrypter: encrypter,
		decrypter: decrypter,
	}
}

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


Question:
Creates a new registration.

@param User        $user
@param \collection $collection

@return Registration

public function createRegistration(User $user, \collection $collection)
    {
        $registration = new Registration();
        $registration->setUser($user);
        $registration->setCollection($collection);
        $this->em->persist($registration);
        $this->em->flush();

        return $registration;
    }

public function listTables($limit = null, $exclusiveStartTableName = null)
    {
        if (null !== $this->logger) {
            $this->log('List tables');
        }

        $parameters = array();
        if (null !== $limit) {
            $parameters['Limit'] = $limit;
        }
        if (null !== $exclusiveStartTableName) {
            $parameters['ExclusiveStartTableName'] = $exclusiveStartTableName;
        }

        if (null !== $this->logger) {
            $this->log('ListTable request paramaters : '.print_r($parameters, true), Logger::DEBUG);
        }

        $response = $this->connector->listTables($parameters);

        if (null !== $this->logger) {
            $this->log('ListTable request response : '.print_r($response, true), Logger::DEBUG);
        }

        $tables = new Table\TableCollection((isset($response['LastEvaluatedTableName'])?$response['LastEvaluatedTableName']:null));
        if (!empty($response['TableNames'])) {
            foreach ($response['TableNames'] as $table) {
                $tables->add($table);
            }
        }
        return $tables;
    }

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


Question:
Delete a hook

@link https://developer.github.com/v3/orgs/hooks/#delete-a-hook

@param string $org
@param int    $id

@return bool
@throws \Exception

public function deleteHook(string $org, int $id): bool
    {
        $this->getApi()->request($this->getApi()->sprintf('/orgs/:org/hooks/:id', $org, (string)$id),
            Request::METHOD_DELETE);

        if ($this->getApi()->getHeaders()['Status'] == '204 No Content') {
            return true;
        }

        return false;
    }

public function curlDELETE($curlUrl)
  {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Accept: application/json',
      'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $jsonResult = curl_exec($ch);
    $results[0] = json_decode($jsonResult);
    $results[1] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_cURL: curlDELETE', 1);

    return $results;
  }

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


Question:
Set mail From, FromName, SMTP values

@param \OxidEsales\Eshop\Application\Model\Shop $shop Shop object

protected function _setMailParams($shop = null)
    {
        $this->_clearMailer();

        if (!$shop) {
            $shop = $this->_getShop();
        }

        $this->setFrom($shop->oxshops__oxorderemail->value, $shop->oxshops__oxname->getRawValue());
        $this->setSmtp($shop);
    }

public static function createFromData(array $data): self
    {
        if (!isset($data['method'])) {
            throw new DomainException(self::REQUIRED_METHOD);
        }

        switch ($data['method']) {
            case self::METHOD_ACCOUNT_WEIGHTS:
                $instruction = new AccountWeights($data);

                break;
            case self::METHOD_ACQUIRER_WEIGHTS:
                $instruction = new AcquirerWeights($data);

                break;
            default:
                throw new DomainException(
                    sprintf(self::UNEXPECTED_METHOD, implode(', ', self::methods()))
                );
        }

        return $instruction;
    }

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


Question: Calculate peak interval for parameter.

def peak_interval(self, name, alpha=_alpha, npoints=_npoints, **kwargs):

        data = self.get(name, **kwargs)
        return peak_interval(data,alpha,npoints)

func (o *InventoryGetParams) WithTimeout(timeout time.Duration) *InventoryGetParams {
	o.SetTimeout(timeout)
	return o
}

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


Question:
Get the Route URL generator instance.

@return \Illuminate\Routing\RouteUrlGenerator

protected function routeUrl()
    {
        if (! $this->routeGenerator) {
            $this->routeGenerator = new RouteUrlGenerator($this, $this->request);
        }

        return $this->routeGenerator;
    }

func (c *FakeIngressRoutes) Create(ingressRoute *v1alpha1.IngressRoute) (result *v1alpha1.IngressRoute, err error) {
	obj, err := c.Fake.
		Invokes(testing.NewCreateAction(ingressroutesResource, c.ns, ingressRoute), &v1alpha1.IngressRoute{})

	if obj == nil {
		return nil, err
	}
	return obj.(*v1alpha1.IngressRoute), err
}

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


Question: Load the config and setup the remember-me session if needed

public static function _init()
	{
		\Config::load('simpleauth', true);

		// setup the remember-me session object if needed
		if (\Config::get('simpleauth.remember_me.enabled', false))
		{
			static::$remember_me = \Session::forge(array(
				'driver' => 'cookie',
				'cookie' => array(
					'cookie_name' => \Config::get('simpleauth.remember_me.cookie_name', 'rmcookie'),
				),
				'encrypt_cookie' => true,
				'expire_on_close' => false,
				'expiration_time' => \Config::get('simpleauth.remember_me.expiration', 86400 * 31),
			));
		}
	}

public function admin_menu() {

		// Register settings page.
		add_options_page(
			self::get_page_title(),
			self::get_page_title(),
			'manage_options',
			self::get_page_name(),
			array( $this, 'settings_page' )
		);

		// Register settings section.
		add_settings_section(
			self::get_page_name(),
			__( 'General Settings', 'carbon_breadcrumbs' ),
			'',
			self::get_page_name()
		);

	}

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


Question:
// DecodeConfig returns the color model and dimensions of a WEBP image without
// decoding the entire image.

func DecodeConfig(r io.Reader) (config image.Config, err error) {
	header := make([]byte, maxWebpHeaderSize)
	n, err := r.Read(header)
	if err != nil && err != io.EOF {
		return
	}
	header, err = header[:n], nil
	width, height, _, err := GetInfo(header)
	if err != nil {
		return
	}
	config.Width = width
	config.Height = height
	config.ColorModel = color.RGBAModel
	return
}

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:
Creates a play engine based on current services (scheduling service, consumer service, and provider service). This method is useful
during unit testing.

PlayEngine createEngine(ISchedulingService schedulingService, IConsumerService consumerService, IProviderService providerService) {
        engine = new PlayEngine.Builder(this, schedulingService, consumerService, providerService).build();
        // set the max pending video frames to the play engine
        engine.setMaxPendingVideoFrames(maxPendingVideoFrames);
        // set the max sequential pending video frames to the play engine
        engine.setMaxSequentialPendingVideoFrames(maxSequentialPendingVideoFrames);
        return engine;
    }

def fake2db_sqlite_initiator(self, number_of_rows, name=None, custom=None):
        '''
        '''
        rows = number_of_rows
        conn = self.database_caller_creator(name)

        if custom:
            self.custom_db_creator(rows, conn, custom)
            conn.close()
            sys.exit(0)

        self.data_filler_simple_registration(rows, conn)
        self.data_filler_detailed_registration(rows, conn)
        self.data_filler_company(rows, conn)
        self.data_filler_user_agent(rows, conn)
        self.data_filler_customer(rows, conn)
        conn.close()

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


Question:
@param string $path
@param string $siteId

@throws \Exception

@return Collection

public function findByPathAndSite($path, $siteId)
    {
        $qb = $this->createQueryBuilder();
        $qb->field('siteId')->equals($siteId)
            ->field('path')->equals(new \MongoRegex('/^'.$path.'(\/.*)?$/'));

        return $qb->getQuery()->execute();
    }

public function listTables($limit = null, $exclusiveStartTableName = null)
    {
        if (null !== $this->logger) {
            $this->log('List tables');
        }

        $parameters = array();
        if (null !== $limit) {
            $parameters['Limit'] = $limit;
        }
        if (null !== $exclusiveStartTableName) {
            $parameters['ExclusiveStartTableName'] = $exclusiveStartTableName;
        }

        if (null !== $this->logger) {
            $this->log('ListTable request paramaters : '.print_r($parameters, true), Logger::DEBUG);
        }

        $response = $this->connector->listTables($parameters);

        if (null !== $this->logger) {
            $this->log('ListTable request response : '.print_r($response, true), Logger::DEBUG);
        }

        $tables = new Table\TableCollection((isset($response['LastEvaluatedTableName'])?$response['LastEvaluatedTableName']:null));
        if (!empty($response['TableNames'])) {
            foreach ($response['TableNames'] as $table) {
                $tables->add($table);
            }
        }
        return $tables;
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

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

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

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
// NewGauge implements Provider via prometheus.NewGaugeFrom, i.e. the gauge is
// registered. The metric's namespace and subsystem are taken from the Provider.
// Help is set to the name of the metric, and no const label names are set.

func (p *prometheusProvider) NewGauge(name string) metrics.Gauge {
	return prometheus.NewGaugeFrom(stdprometheus.GaugeOpts{
		Namespace: p.namespace,
		Subsystem: p.subsystem,
		Name:      name,
		Help:      name,
	}, []string{})
}

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

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

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


Question: 従って、バイナリの最後のほうが切り捨てられる。

@Override
	public final Object readObject(OInput in, Class<Object> clazz) throws IOException {
		UnsafeFieldAccessor currentProcessfeild = null; // エラー時のメッセージ出力用。

		try {

			Object data = TheUnsafe.unsafe.allocateInstance(clazz);

			int binarySize = in.readInt();

//			BAInputStream bais;
//			if( in.isUnderlayBAIn() ) {
//				BAInputStream underlay = in.getUnderlayBAIn();
//				bais = new BAInputStream(underlay.getBuf(), underlay.getPos(), binarySize);
//				in.skip(binarySize);
//			} else {
//				byte[] binary = new byte[binarySize];
//				in.readFully(binary);
//				bais = new BAInputStream(binary);
//			}

			// 項目数が少ない場合に対応するため、OIputStreamをブランチする。
			OInput ois = in.branch();
			in.skip(binarySize);

			// Beanクラスに項目追加があった場合、読み込み側で処理を打ち切る為に利用される
			int fieldCount = NaturalNumberIoHelper.readNaturalNumber(ois);
			int processedCount = 0;

			UnsafeFieldAccessor[] fieldList = UnsafeClassMetaDataRegistry.getFieldList(clazz);

			for(UnsafeFieldAccessor f : fieldList) {
				currentProcessfeild = f;

				processedCount += 1;
				if( processedCount > fieldCount) {
					// 現在のBeanのプロパティの数が、書き込まれたプロパティのサイズを超えている。これはクラスに項目追加があった場合。
					return data;
				}

				Class<?> c = f.getType();

				if(c == String.class) {
					String s = ois.readString();
					f.set(data, s);
				} else if(c.isPrimitive()) {

					if(c == Integer.TYPE){
						Integer i = ois.readInt();
						f.setInt(data, i);
					} else if(c == Long.TYPE) {
						Long l = ois.readLong();
						f.setLong(data, l);
					} else if(c == Short.TYPE) {
						Short s = ois.readShort();
						f.setShort(data, s);
					} else if(c == Boolean.TYPE) {
						Boolean b = ois.readBoolean();
						f.setBoolean(data, b);
					} else if(c == Double.TYPE) {
						Double d = ois.readDouble();
						f.setDouble(data, d);
					} else if(c == Float.TYPE) {
						Float flo = ois.readFloat();
						f.setFloat(data, flo);
					} else if(c == Character.TYPE) {
						Character l = ois.readChar();
						f.setChar(data, l);
					} else if(c == Byte.TYPE) {
						Byte l = ois.readByte();
						f.setByte(data, l);
					}

				} else {
					Object o = ois.readObject();
					f.set(data, o);
				}
			}

			return data;
		} catch (MarshalException e) {
			throw e;
		} catch (Exception e) {
			throw new MarshalException("バイナリ読み込みで例外発生 data=" + clazz + ", feild=" + currentProcessfeild ,e);
		}

	}

def main(args=None):
    """"""

    if args is None:
        parser = get_argument_parser()
        args = parser.parse_args()

    input_file = args.annotation_file
    output_file = args.output_file
    species = args.species
    chrom_pat = args.chromosome_pattern
    field_name = args.field_name

    log_file = args.log_file
    quiet = args.quiet
    verbose = args.verbose

    # configure root logger
    log_stream = sys.stdout
    if output_file == '-':
        # if we print output to stdout, redirect log messages to stderr
        log_stream = sys.stderr

    logger = misc.get_logger(log_stream = log_stream, log_file = log_file,
            quiet = quiet, verbose = verbose)

    if chrom_pat is None:
        chrom_pat = re.compile(ensembl.SPECIES_CHROMPAT[species])
    else:
        chrom_pat = re.compile(chrom_pat)

    logger.info('Regular expression used for filtering chromosome names: "%s"',
            chrom_pat.pattern)

    chromosomes = set()
    excluded_chromosomes = set()
    i = 0
    exons = 0
    logger.info('Parsing data...')
    if input_file == '-':
        input_file = None
    with misc.smart_open_read(input_file, mode = 'rb', try_gzip = True) as fh, \
            misc.smart_open_write(output_file) as ofh:
        #if i >= 500000: break
        reader = csv.reader(fh, dialect = 'excel-tab')
        writer = csv.writer(ofh, dialect = 'excel-tab', lineterminator = os.linesep,
                quoting = csv.QUOTE_NONE , quotechar = '|')
        for l in reader:
            i += 1
            #if i % int(1e5) == 0:
            #   print '\r%d...' %(i), ; sys.stdout.flush() # report progress
            if len(l) > 1 and l[2] == field_name:
                attr = parse_attributes(l[8])
                type_ = attr['gene_biotype']
                if type_ in ['protein_coding','polymorphic_pseudogene']:

                    # test whether chromosome is valid
                    chrom = l[0]
                    m = chrom_pat.match(chrom)
                    if m is None:
                        excluded_chromosomes.add(chrom)
                        continue

                    chromosomes.add(chrom)
                    writer.writerow(l)
                    exons += 1

    logger.info('Done! (Parsed %d lines.)', i)

    logger.info('')
    logger.info('Gene chromosomes (%d):', len(chromosomes))
    logger.info('\t' + ', '.join(sorted(chromosomes)))
    logger.info('')
    logger.info('Excluded chromosomes (%d):', len(excluded_chromosomes))
    logger.info('\t' + ', '.join(sorted(excluded_chromosomes)))
    logger.info('')
    logger.info('Total no. of exons: %d' %(exons))

    return 0

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


Question: // Update advances the animations of all tracked entities.

func (a *AnimationSystem) Update(dt float32) {
	for _, e := range a.entities {
		if e.AnimationComponent.CurrentAnimation == nil {
			if e.AnimationComponent.def == nil {
				continue
			}
			e.AnimationComponent.SelectAnimationByAction(e.AnimationComponent.def)
		}

		e.AnimationComponent.change += dt
		if e.AnimationComponent.change >= e.AnimationComponent.Rate {
			e.RenderComponent.Drawable = e.AnimationComponent.Cell()
			e.AnimationComponent.NextFrame()
		}
	}
}

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.TBM__DIRCTION:
				setDIRCTION((Integer)newValue);
				return;
			case AfplibPackage.TBM__PRECSION:
				setPRECSION((Integer)newValue);
				return;
			case AfplibPackage.TBM__INCRMENT:
				setINCRMENT((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

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


Question: Returns an iterable for a (possibly null) tree.

@Override
  public Iterable<V> values() {
    if (isEmpty()) {
      return Collections.<V>emptyList();
    }
    return () -> new Iter<>(this, map -> map.value);
  }

def append(self, node):
        """"""
        if node.parent == self.key and not self.elapsed_time:
            self.children.append(node)
        else:
            # Recursive call
            for child in self.children:
                if not child.elapsed_time:
                    child.append(node)

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


Question:
Builds the HTML
@return string

private function build() {

    	if(null === $this -> text) {

    		$html = '<input type="'. $this -> type .'"';

    		foreach($this -> attributes as $attribute => $value) {
    		    $html .= ' ' . $attribute . '="'. Escape :: attr($value) .'"';
    		}

    		$html .= '>';

    		return $html;
    	}

        $this -> fill();

        $html = '<button';

        foreach($this -> attributes as $attribute => $value) {
            $html .= ' ' . $attribute . '="'. Escape :: attr($value) .'"';
        }

        $html .= '>' . Escape :: html($this -> text) . '</button>';

        return $html;

    }

public ResultResponseUtil status(IReturnCode iReturnCode) {
        this.setCode(iReturnCode.getCode());
        this.setMsg(iReturnCode.getMsg());
        return this;
    }

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


Question:
编译 slot 节点

@param {ANode} aNode 节点对象
@param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
@param {Component} owner 所属组件实例环境

function (aNode, sourceBuffer, owner) {
        var rendererId = genSSRId();

        sourceBuffer.addRaw('componentCtx.slotRenderers.' + rendererId
            + ' = componentCtx.slotRenderers.' + rendererId + ' || function () {');

        sourceBuffer.addRaw('function $defaultSlotRender(componentCtx) {');
        sourceBuffer.addRaw('  var html = "";');
        each(aNode.children, function (aNodeChild) {
            sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
        });
        sourceBuffer.addRaw('  return html;');
        sourceBuffer.addRaw('}');

        sourceBuffer.addRaw('var $isInserted = false;');
        sourceBuffer.addRaw('var $ctxSourceSlots = componentCtx.sourceSlots;');
        sourceBuffer.addRaw('var $mySourceSlots = [];');

        var nameProp = getANodeProp(aNode, 'name');
        if (nameProp) {
            sourceBuffer.addRaw('var $slotName = ' + compileExprSource.expr(nameProp.expr) + ';');

            sourceBuffer.addRaw('for (var $i = 0; $i < $ctxSourceSlots.length; $i++) {');
            sourceBuffer.addRaw('  if ($ctxSourceSlots[$i][1] == $slotName) {');
            sourceBuffer.addRaw('    $mySourceSlots.push($ctxSourceSlots[$i][0]);');
            sourceBuffer.addRaw('    $isInserted = true;');
            sourceBuffer.addRaw('  }');
            sourceBuffer.addRaw('}');
        }
        else {
            sourceBuffer.addRaw('if ($ctxSourceSlots[0] && $ctxSourceSlots[0][1] == null) {');
            sourceBuffer.addRaw('  $mySourceSlots.push($ctxSourceSlots[0][0]);');
            sourceBuffer.addRaw('  $isInserted = true;');
            sourceBuffer.addRaw('}');
        }

        sourceBuffer.addRaw('if (!$isInserted) { $mySourceSlots.push($defaultSlotRender); }');
        sourceBuffer.addRaw('var $slotCtx = $isInserted ? componentCtx.owner : componentCtx;');

        if (aNode.vars || aNode.directives.bind) {
            sourceBuffer.addRaw('$slotCtx = {data: extend({}, $slotCtx.data), proto: $slotCtx.proto, owner: $slotCtx.owner};'); // eslint-disable-line

            if (aNode.directives.bind) {
                sourceBuffer.addRaw('extend($slotCtx.data, ' + compileExprSource.expr(aNode.directives.bind.value) + ');'); // eslint-disable-line
            }

            each(aNode.vars, function (varItem) {
                sourceBuffer.addRaw(
                    '$slotCtx.data["' + varItem.name + '"] = '
                    + compileExprSource.expr(varItem.expr)
                    + ';'
                );
            });
        }

        sourceBuffer.addRaw('for (var $renderIndex = 0; $renderIndex < $mySourceSlots.length; $renderIndex++) {');
        sourceBuffer.addRaw('  html += $mySourceSlots[$renderIndex]($slotCtx);');
        sourceBuffer.addRaw('}');

        sourceBuffer.addRaw('};');
        sourceBuffer.addRaw('componentCtx.slotRenderers.' + rendererId + '();');
    }

function styled(Component) {
  const componentCreator = (style, options = {}) => {
    const { name, ...stylesOptions } = options;

    if (process.env.NODE_ENV !== 'production' && Component === undefined) {
      throw new Error(
        [
          'You are calling styled(Component)(style) with an undefined component.',
          'You may have forgotten to import it.',
        ].join('\n'),
      );
    }

    let classNamePrefix = name;

    if (process.env.NODE_ENV !== 'production' && !name) {
      // Provide a better DX outside production.
      classNamePrefix = getDisplayName(Component);
      warning(
        typeof classNamePrefix === 'string',
        [
          'Material-UI: the component displayName is invalid. It needs to be a string.',
          `Please fix the following component: ${Component}.`,
        ].join('\n'),
      );
    }

    const stylesOrCreator =
      typeof style === 'function'
        ? theme => ({ root: props => style({ theme, ...props }) })
        : { root: style };

    const useStyles = makeStyles(stylesOrCreator, {
      Component,
      name: name || Component.displayName,
      classNamePrefix,
      ...stylesOptions,
    });

    let filterProps;
    let propTypes = {};

    if (style.filterProps) {
      filterProps = style.filterProps;
      delete style.filterProps;
    }

    /* eslint-disable react/forbid-foreign-prop-types */
    if (style.propTypes) {
      propTypes = style.propTypes;
      delete style.propTypes;
    }
    /* eslint-enable react/forbid-foreign-prop-types */

    const StyledComponent = React.forwardRef(function StyledComponent(props, ref) {
      const {
        children,
        className: classNameProp,
        clone,
        component: ComponentProp,
        ...other
      } = props;
      const classes = useStyles(props);
      const className = clsx(classes.root, classNameProp);

      if (clone) {
        return React.cloneElement(children, {
          className: clsx(children.props.className, className),
        });
      }

      let spread = other;
      if (filterProps) {
        spread = omit(spread, filterProps);
      }

      if (typeof children === 'function') {
        return children({ className, ...spread });
      }

      const FinalComponent = ComponentProp || Component;

      return (
        <FinalComponent ref={ref} className={className} {...spread}>
          {children}
        </FinalComponent>
      );
    });

    StyledComponent.propTypes = {
      /**
       * A render function or node.
       */
      children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
      /**
       * @ignore
       */
      className: PropTypes.string,
      /**
       * If `true`, the component will recycle it's children DOM element.
       * It's using `React.cloneElement` internally.
       */
      clone: chainPropTypes(PropTypes.bool, props => {
        if (props.clone && props.component) {
          return new Error('You can not use the clone and component properties at the same time.');
        }
        return null;
      }),
      /**
       * The component used for the root node.
       * Either a string to use a DOM element or a component.
       */
      component: PropTypes.elementType,
      ...propTypes,
    };

    if (process.env.NODE_ENV !== 'production') {
      StyledComponent.displayName = `Styled(${classNamePrefix})`;
    }

    hoistNonReactStatics(StyledComponent, Component);

    return StyledComponent;
  };

  return componentCreator;
}

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


Question: See: https://core.telegram.org/bots/api#getuserprofilephotos

def getUserProfilePhotos(self, user_id,
                             offset=None,
                             limit=None):

        p = _strip(locals())
        return self._api_request('getUserProfilePhotos', _rectify(p))

func (prof *Profiles) ByName(name string) (*User, error) {
	body, err := prof.inst.sendSimpleRequest(urlUserByName, name)
	if err == nil {
		resp := userResp{}
		err = json.Unmarshal(body, &resp)
		if err == nil {
			user := &resp.User
			user.inst = prof.inst
			return user, err
		}
	}
	return nil, err
}

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


Question:
Add another RewardProducer object.<br>

@param producer
the reward producing object to add to the mix.

public void addRewardProducer(IRewardProducer producer) {
        if (this.producers == null) {
            this.producers = new ArrayList<IRewardProducer>();
        }
        this.producers.add(producer);
    }

public static xen_health_monitor[] get_filtered(nitro_service service, String filter) throws Exception
	{
		xen_health_monitor obj = new xen_health_monitor();
		options option = new options();
		option.set_filter(filter);
		xen_health_monitor[] response = (xen_health_monitor[]) obj.getfiltered(service, option);
		return response;
	}

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


Question: Use this API to fetch sslcertkey_binding resource of given name .

public static sslcertkey_binding get(nitro_service service, String certkey) throws Exception{
		sslcertkey_binding obj = new sslcertkey_binding();
		obj.set_certkey(certkey);
		sslcertkey_binding response = (sslcertkey_binding) obj.get_resource(service);
		return response;
	}

def authenticate_with_certificate(reactor, base_url, client_cert, client_key, ca_cert):

    return authenticate_with_certificate_chain(
        reactor, base_url, [client_cert], client_key, ca_cert,
    )

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


Question: // String returns expression text used in rules

func (a OrExpr) String() string {
	return fmt.Sprintf("%v || %v", a.Left, a.Right)
}

protected void addComment(ProgramElementDoc member, Content htmltree) {
        if (member.inlineTags().length > 0) {
            writer.addInlineComment(member, htmltree);
        }
    }

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


Question: Return a list of the VMs that are on the provider, with all fields

def list_nodes_full(conn=None, call=None):
    '''

    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes_full function must be called with -f or '
            '--function.'
        )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    ret = {}
    datacenter_id = get_datacenter_id()
    nodes = conn.list_servers(datacenter_id=datacenter_id, depth=3)

    for item in nodes['items']:
        node = {'id': item['id']}
        node.update(item['properties'])
        node['state'] = node.pop('vmState')
        node['public_ips'] = []
        node['private_ips'] = []
        if item['entities']['nics']['items'] > 0:
            for nic in item['entities']['nics']['items']:
                if nic['properties']['ips']:
                    pass
                ip_address = nic['properties']['ips'][0]
                if salt.utils.cloud.is_public_ip(ip_address):
                    node['public_ips'].append(ip_address)
                else:
                    node['private_ips'].append(ip_address)

        ret[node['name']] = node

    __utils__['cloud.cache_node_list'](
        ret,
        __active_provider_name__.split(':')[0],
        __opts__
    )

    return ret

protected function buildColumnDispatch()
    {
        $this->columnDispatch = array();

        foreach ($this->getComponents() as $item) {
            if ($item instanceof GridField_ColumnProvider) {
                $columns = $item->getColumnsHandled($this);

                foreach ($columns as $column) {
                    $this->columnDispatch[$column][] = $item;
                }
            }
        }
    }

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


Question:
// MustParseColour is like ParseColour except it panics if the colour is invalid.
//
// Will panic if colour is in an invalid format.

func MustParseColour(colour string) Colour {
	parsed := ParseColour(colour)
	if !parsed.IsSet() {
		panic(fmt.Errorf("invalid colour %q", colour))
	}
	return parsed
}

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

      :ok # passes
    end

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


Question:
// ProjectFromNamespace returns the current project installed in the supplied
// Context's namespace.
//
// If the namespace does not have a project namespace prefix, this function
// will return an empty string.

func ProjectFromNamespace(ns string) types.ProjectName {
	if !strings.HasPrefix(ns, ProjectNamespacePrefix) {
		return ""
	}
	return types.ProjectName(ns[len(ProjectNamespacePrefix):])
}

public function leaveNode(Node $node)
    {
        if ($node instanceof Stmt\Class_
            || $node instanceof Stmt\Interface_
            || $node instanceof Stmt\Trait_
        ) {
            if (empty($this->suffix) && !empty($this->namespaceNode)) {
                $node->name = $this->append(new Name($node->name), $this->namespaceNode);
            }
            else {
                $node->name = $node->name . $this->suffix;
            }
        } elseif ($node instanceof Name) {
            if (!$this->cancelNext) {
                return $this->appendSuffix($node);
            }
            $this->cancelNext = false;
        } elseif ($node instanceof Stmt\Use_) {
            $this->isImport = false;
        } elseif ($node instanceof Stmt\GroupUse) {
            $this->groupImport = false;
        }
    }

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


Question:
Appends OR WHERE with <= operator

@param string $column
@param string $value
@param boolean $filter
@return \Krystal\Db\Sql\Db

public function orWhereLessThanOrEquals($column, $value, $filter = false)
    {
        return $this->orWhere($column, '<=', $value, $filter);
    }

def predicates(predicate, collection, klass, column_name, value)
      case predicate
      when :between
        klass.arel_table[column_name].between(value.first..value.last)
      when :does_not_match
        klass.arel_table[column_name].does_not_match("%#{value}%")
      when :does_not_match_all
        klass.arel_table[column_name].does_not_match_all(value)
      when :does_not_match_any
        klass.arel_table[column_name].does_not_match_any(value)
      when :eq
        klass.arel_table[column_name].eq(value)
      when :eq_all
        klass.arel_table[column_name].eq_all(value)
      when :eq_any
        klass.arel_table[column_name].eq_any(value)
      when :gt
        klass.arel_table[column_name].gt(value)
      when :gt_all
        klass.arel_table[column_name].gt_all(value)
      when :gt_any
        klass.arel_table[column_name].gt_any(value)
      when :gteq
        klass.arel_table[column_name].gteq(value)
      when :gteq_all
        klass.arel_table[column_name].gteq_all(value)
      when :gteq_any
        klass.arel_table[column_name].gteq_any(value)
      when :in
        klass.arel_table[column_name].in(value)
      when :in_all
        klass.arel_table[column_name].in_all(value)
      when :in_any
        klass.arel_table[column_name].in_any(value)
      when :lt
        klass.arel_table[column_name].lt(value)
      when :lt_all
        klass.arel_table[column_name].lt_all(value)
      when :lt_any
        klass.arel_table[column_name].lt_any(value)
      when :lteq
        klass.arel_table[column_name].lteq(value)
      when :lteq_all
        klass.arel_table[column_name].lteq_all(value)
      when :lteq_any
        klass.arel_table[column_name].lteq_any(value)
      when :ilike
        klass.arel_table[column_name].matches("%#{value}%")
      when :matches
        klass.arel_table[column_name].matches(value)
      when :matches_all
        klass.arel_table[column_name].matches_all(value)
      when :matches_any
        klass.arel_table[column_name].matches_any(value)
      when :not_between
        klass.arel_table[column_name].not_between(value.first..value.last)
      when :not_eq
        klass.arel_table[column_name].not_eq(value)
      when :not_eq_all
        klass.arel_table[column_name].not_eq_all(value)
      when :not_eq_any
        klass.arel_table[column_name].not_eq_any(value)
      when :not_in
        klass.arel_table[column_name].not_in(value)
      when :not_in_all
        klass.arel_table[column_name].not_in_all(value)
      when :not_in_any
        klass.arel_table[column_name].not_in_any(value)
      else
        unless predicate.respond_to?(:call)
          raise ArgumentError,
                "unsupported predicate `#{predicate}`"
        end

        predicate.call(collection, value)
      end
    end

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


Question:
// evalString evals a builtinSubDateAndStringSig.
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_subtime

func (b *builtinSubDateAndStringSig) evalString(row chunk.Row) (string, bool, error) {
	arg0, isNull, err := b.args[0].EvalDuration(b.ctx, row)
	if isNull || err != nil {
		return "", isNull, err
	}
	s, isNull, err := b.args[1].EvalString(b.ctx, row)
	if isNull || err != nil {
		return "", isNull, err
	}
	if !isDuration(s) {
		return "", true, nil
	}
	arg1, err := types.ParseDuration(b.ctx.GetSessionVars().StmtCtx, s, getFsp4TimeAddSub(s))
	if err != nil {
		return "", true, err
	}
	result, err := arg0.Sub(arg1)
	if err != nil {
		return "", true, err
	}
	return result.String(), false, nil
}

public static function encrypt($str,$key,$expire=0){
        $expire = sprintf('%010d', $expire ? $expire + time():0);
        $r = md5($key);
        $c = 0;
        $v = "";
        $str    =   $expire.$str;
		$len = strlen($str);
		$l = strlen($r);
        for ($i=0;$i<$len;$i++){
         if ($c== $l) $c=0;
         $v .= substr($r,$c,1) .
             (substr($str,$i,1) ^ substr($r,$c,1));
         $c++;
        }
        return self::ed($v,$key);
    }

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


Question:
Get hyperlink

@param string $pCellCoordinate    Cell coordinate to get hyperlink for

public function getHyperlink($pCellCoordinate = 'A1')
    {
        // return hyperlink if we already have one
        if (isset($this->hyperlinkCollection[$pCellCoordinate])) {
            return $this->hyperlinkCollection[$pCellCoordinate];
        }

        // else create hyperlink
        $this->hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink();
        return $this->hyperlinkCollection[$pCellCoordinate];
    }

def get_link_attribute(self, link_text, attribute, hard_fail=True):

        soup = self.get_beautiful_soup()
        html_links = soup.find_all('a')
        for html_link in html_links:
            if html_link.text.strip() == link_text.strip():
                if html_link.has_attr(attribute):
                    attribute_value = html_link.get(attribute)
                    return attribute_value
                if hard_fail:
                    raise Exception(
                        'Unable to find attribute {%s} from link text {%s}!'
                        % (attribute, link_text))
                else:
                    return None
        if hard_fail:
            raise Exception("Link text {%s} was not found!" % link_text)
        else:
            return None

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


Question:
Handle one message and modify the job storage appropriately.
        :param msg: the message to handle
        :return: None

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

public void marshall(DeleteBackupVaultNotificationsRequest deleteBackupVaultNotificationsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deleteBackupVaultNotificationsRequest.getBackupVaultName(), BACKUPVAULTNAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
If the request is under the Swagger API's basePath, but no matching Path was found,
then an HTTP 404 (Not Found) error is thrown

function http404 (req, res, next) {
  if (req.swagger && req.swagger.api && !req.swagger.path) {
    util.debug(
      'Client requested path "%s", which is not defined in the Swagger API. Returning HTTP 404 (Not Found)',
      req.path
    );
    throw ono({ status: 404 }, "Resource not found: %s", req.path);
  }

  next();
}

static MavenResolvedArtifact fromArtifactResult(final ArtifactResult artifactResult) {
        final Artifact artifact = artifactResult.getArtifact();
        final DependencyNode root = artifactResult.getRequest().getDependencyNode();

        // SHRINKRES-143 lets ignore invalid scope
        ScopeType scopeType = ScopeType.RUNTIME;
        try {
            scopeType = ScopeType.fromScopeType(root.getDependency().getScope());
        } catch (IllegalArgumentException e) {
            // let scope be RUNTIME
            log.log(Level.WARNING, "Invalid scope {0} of retrieved dependency {1} will be replaced by <scope>runtime</scope>",
                    new Object[] { root.getDependency().getScope(), root.getDependency().getArtifact() });
        }

        final List<DependencyNode> children = root.getChildren();
        final boolean optional = root.getDependency().isOptional();
        return new MavenResolvedArtifactImpl(artifact, scopeType, children, optional);
    }

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


Question: Returns the mean ground motion acceleration and velocity

def _compute_mean(self, C, rup, dists, sites, imt):

        # Convert rhypo to rrup
        rrup = rhypo_to_rrup(dists.rhypo, rup.mag)
        mean = (self._get_magnitude_scaling_term(C, rup.mag) +
                self._get_distance_scaling_term(C, rup.mag, rrup) +
                self._get_style_of_faulting_term(C, rup.rake) +
                self._get_site_amplification_term(C, sites.vs30))
        # convert from cm/s**2 to g for SA and from cm/s**2 to g for PGA (PGV
        # is already in cm/s) and also convert from base 10 to base e.
        if isinstance(imt, PGA):
            mean = np.log((10 ** mean) * ((2 * np.pi / 0.01) ** 2) *
                          1e-2 / g)
        elif isinstance(imt, SA):
            mean = np.log((10 ** mean) * ((2 * np.pi / imt.period) ** 2) *
                          1e-2 / g)
        else:
            mean = np.log(10 ** mean)

        return mean + self.adjustment_factor

func (joint *SimpleMotor) ApplyCachedImpulse(dt_coef vect.Float) {
	a := joint.BodyA
	b := joint.BodyB

	j := joint.jAcc*dt_coef
	a.w -= j*a.i_inv
	b.w += j*b.i_inv
}

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


Question:
Context tree icon ~
Define a CSS class here to be used to display the context icon in the tree. You can use this setting on each context to customize the icon per context.

@param string $value

@return $this

public function setCoreMgrTreeIconContext($value)
    {
        $this->setFieldName('mgr_tree_icon_context');
        $this->loadObject(true);
        $this->setFieldValue($value);

        return $this;
    }

public function currency($options = array())
    {
        $options = new AnConfig($options);

        $options->append(array(
            'name' => 'currency',
            'prompt' => true,
        ));

        $selected = $options->selected;
        unset($options->selected);
        $currencies = array_combine(self::$ISO_CURRENCY_SYMBOLS, self::$ISO_CURRENCY_SYMBOLS);

        return $this->_html->select($options->name, array('options' => $currencies, 'selected' => $selected), AnConfig::unbox($options));
    }

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


Question: Put a <String,String> Map object into the transmission buffer

public void putMap (Map<String,String> map) {                                                       //SIB0163.comms.1
     if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "putMap", "map="+map);

     if (map != null) {
       final Set<String> keys = map.keySet();
       putShort(keys.size()); // Number of entries
       for (String k: keys) {
         putString(k);
         putString(map.get(k));
       }
     } else {
       putShort(0);
     }

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

public void marshall(Tmpfs tmpfs, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(tmpfs.getContainerPath(), CONTAINERPATH_BINDING);
            protocolMarshaller.marshall(tmpfs.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(tmpfs.getMountOptions(), MOUNTOPTIONS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
{@inheritDoc}
@see \Jagilpe\EncryptionBundle\Crypt\FieldNormalizer\DefaultFieldNormalizer::normalize()

public function normalize($clearValue)
    {
        $normalizedValue = null;

        if ($clearValue !== null) {
            $primitiveConversor = static::$allowedPrimitives[$this->primitive];
            $primivitveValue = $clearValue !== null ? call_user_func($primitiveConversor, $clearValue) : null;
            $normalizedValue = $primivitveValue;
        }

        return $normalizedValue;
    }

public function addNamespace($namespace, $priority = PriorityQueue::NORMAL)
    {
        $namespace = static::normalise($namespace);

        $this->namespaces->insert($namespace, $priority);

        return $this;
    }

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


Question:
*
Check if child path is child of parent path.
@param parent Expected parent path.
@param child Expected child path.
@return If child path is child of parent path.
@throws IOException

public static boolean isSubPath(org.apache.hadoop.fs.Path parent, org.apache.hadoop.fs.Path child) throws IOException {
    String childStr = child.toString();
    String parentStr = parent.toString();

    return childStr.startsWith(parentStr);
  }

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

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

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

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

        return '';
    }

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


Question: Parse errors from HTTP exceptions

public static void adapt(HttpStatusIOException httpStatusException) {

    String msg = "HTTP Status: " + httpStatusException.getHttpStatusCode();

    // if we have a HTTP body try to parse more error details from body
    if (isNotEmpty(httpStatusException.getHttpBody())) {
      ObjectMapper mapper = new ObjectMapper();
      CmcResult result;
      try {
        result = mapper.readValue(httpStatusException.getHttpBody(), CmcResult.class);
      } catch (Exception e) {
        // but ignore errors on parsing and throw generic ExchangeException instead
        throw new ExchangeException(msg, httpStatusException);
      }
      // but if it contains a parsable result, then try to parse errors from result:
      if (result.getStatus() != null
          && isNotEmpty(result.getStatus().getErrorMessage())
          && !result.isSuccess()) {

        String error = result.getStatus().getErrorMessage();
        if (result.getStatus().getErrorCode() == 401) {
          throw new ExchangeSecurityException(error);
        }
        if (result.getStatus().getErrorCode() == 402) {
          throw new FundsExceededException(error);
        }
        if (result.getStatus().getErrorCode() == 429) {
          throw new FrequencyLimitExceededException(error);
        }

        msg = error + " - ErrorCode: " + result.getStatus().getErrorCode();
        throw new ExchangeException(msg);
      }
    }
    // else: just throw ExchangeException with causing Exception
    throw new ExchangeException(msg, httpStatusException);
  }

public static void expectSLASH(final Buffer buffer) throws SipParseException {
        try {
            final int count = consumeSLASH(buffer);
            if (count == 0) {
                throw new SipParseException(buffer.getReaderIndex(), "Expected SLASH");
            }
        } catch (final IndexOutOfBoundsException e) {
            throw new SipParseException(buffer.getReaderIndex(), "Expected SLASH but nothing more to read", e);

        } catch (final IOException e) {
            throw new SipParseException(buffer.getReaderIndex(), "Expected SLASH but problem reading from stream", e);
        }
    }

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


Question: Get the value at the given key and return it as a config object

public function getConfig($name) {
        $data = $this->get($name);
        if ($data === null) {
            return null;
        }
        if (isset($this->data['global'])) {
            $data['global'] = $this->data['global'];
        }
        $config = new self();
        $config->load($data);
        return $config;
    }

func (s *Configurations) SetCurrent(v *ConfigurationId) *Configurations {
	s.Current = v
	return s
}

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


Question:
Will execute a HEAD only request, following redirects, trying to locate an rdf document.
@param uri - the initial uri
@param format - the expected mime type
@return - the final http response
@throws IOException

static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException {

        HttpHead headMethod = new HttpHead(uri);
        MyRedirectHandler redirectHandler = new MyRedirectHandler(uri);

        String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*";
        CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingConnManager)
            .setSSLContext(ssl)
            .setRedirectStrategy(redirectHandler)
            .setDefaultHeaders(Arrays.asList(
                new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything
                new BasicHeader("User-Agent", "Mozilla/5.0"),
                new BasicHeader("Upgrade-Insecure-Requests", "1")       // we are an all trusting client...
            ))
            .build();

        HttpResponse httpResponse = httpClient.execute(headMethod);
        redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x)));
        return httpResponse;
    }

public ApiSuccessResponse forward(ForwardData forwardData) throws ApiException {
        ApiResponse<ApiSuccessResponse> resp = forwardWithHttpInfo(forwardData);
        return resp.getData();
    }

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


Question:
Delete an access token.

@param  \League\OAuth2\Server\Entity\AuthCodeEntity $token The access token to delete

@return void

public function delete(AuthCodeEntity $token)
    {
        $this->getConnection()->table('oauth_auth_codes')
        ->where('oauth_auth_codes.id', $token->getId())
        ->delete();
    }

public function curlDELETE($curlUrl)
  {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Accept: application/json',
      'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $jsonResult = curl_exec($ch);
    $results[0] = json_decode($jsonResult);
    $results[1] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_cURL: curlDELETE', 1);

    return $results;
  }

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


Question: Publish handler for 'link' element.

function publishHandlerLink( $element, &$params )
    {
        $ret = null;

        $href = $element->getAttribute( 'href' );

        if ( $href )
        {
            if ( preg_match( "@^ezobject://[0-9]+(#.*)?$@", $href ) )
            {
                $url = strtok( $href, '#' );
                $anchorName = strtok( '#' );
                $objectID = substr( strrchr( $url, "/" ), 1 );
                $element->setAttribute( 'object_id', $objectID );

                 if ( !in_array( $objectID, $this->linkedObjectIDArray ) )
                 {
                    $this->linkedObjectIDArray[] = $objectID;
                }
            }
            elseif ( preg_match( "@^eznode://.+(#.*)?$@" , $href ) )
            {
                $objectID = null;
                $url = strtok( $href, '#' );
                $anchorName = strtok( '#' );
                $nodePath = substr( strchr( $url, "/" ), 2 );
                if ( preg_match( "@^[0-9]+$@", $nodePath ) )
                {
                    $nodeID = $nodePath;
                    $node = eZContentObjectTreeNode::fetch( $nodeID, false, false );
                    if ( !$node )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Node '%1' does not exist.", '', array( $nodeID ) ) );
                    }
                    else
                    {
                        $objectID = $node['id'];
                    }
                }
                else
                {
                    $node = eZContentObjectTreeNode::fetchByURLPath( $nodePath, false );
                    if ( !$node )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Node '%1' does not exist.", '', array( $nodePath ) ) );
                    }
                    else
                    {
                        $nodeID = $node['node_id'];
                        $objectID = $node['id'];
                    }
                    $element->setAttribute( 'show_path', 'true' );
                }
                $element->setAttribute( 'node_id', $nodeID );

                if ( $objectID && !in_array( $objectID, $this->linkedObjectIDArray ) )
                {
                    $this->linkedObjectIDArray[] = $objectID;
                }
            }
            elseif ( preg_match( "@^#.*$@" , $href ) )
            {
                $anchorName = substr( $href, 1 );
            }
            else
            {
                //washing href. single and double quotes replaced with their urlencoded form
                $href = str_replace( array('\'','"'), array('%27','%22'), $href );

                $temp = explode( '#', $href );
                $url = $temp[0];
                if ( isset( $temp[1] ) )
                {
                    $anchorName = $temp[1];
                }

                if ( $url )
                {
                    // Protection from XSS attack
                    if ( preg_match( "/^(java|vb)script:.*/i" , $url ) )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Using scripts in links is not allowed, link '%1' has been removed", '', array( $url ) ) );

                        $element->removeAttribute( 'href' );
                        return $ret;

                    }
                    // Check mail address validity following RFC 5322 and RFC 5321
                    if ( preg_match( "/^mailto:([^.][a-z0-9!#\$%&'*+-\/=?`{|}~^]+@([a-z0-9.-]+))/i" , $url, $mailAddr ) &&
                         !eZMail::validate( $mailAddr[1] ) )
                    {
                        $this->handleError( eZXMLInputParser::ERROR_DATA,
                                            ezpI18n::tr( 'kernel/classes/datatypes/ezxmltext', "Invalid e-mail address: '%1'", '' , array( $mailAddr[1] ) ) );

                        $element->removeAttribute( 'href' );
                        return $ret;
                    }
                    // Store urlID instead of href
                    $urlID = $this->convertHrefToID( $url );
                    if ( $urlID )
                    {
                        $urlIDAttributeName = 'url_id';

                        $element->setAttribute( $urlIDAttributeName, $urlID );
                    }
                }
            }

            if ( isset( $anchorName ) && $anchorName )
            {
                $element->setAttribute( 'anchor_name', $anchorName );
            }

            $element->removeAttribute( 'href' );
        }

        return $ret;
    }

public function dispatchCommentUpdateEvent(Post $post, Comment $comment, $changeSet)
    {
        $event = new LogCommentUpdateEvent($post, $comment, $changeSet, $this->translator);

        return $this->dispatch($event);
    }

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


Question:
Add closure handle

@return CallableLoader

@throws AlreadyBuildedException

public function addCallableHandle()
    {
        if ($this->handler) {
            throw new AlreadyBuildedException('The handler already builded.');
        }

        $loader = new CallableLoader();
        $resolver = new CallableResolver();

        $this->addCallableResolver($resolver);
        $this->addActionLoader($loader);

        return $loader;
    }

func (_m *API) BuildContent(ctx context.Context, scm source.Source, opts *types.BuildOptions) (io.ReadCloser, error) {
	ret := _m.Called(ctx, scm, opts)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, source.Source, *types.BuildOptions) io.ReadCloser); ok {
		r0 = rf(ctx, scm, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, source.Source, *types.BuildOptions) error); ok {
		r1 = rf(ctx, scm, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question:
Update Fields
@return FieldList

public function updateCMSFields(FieldList $fields)
    {
        $owner = $this->owner;
        $fields->addFieldToTab(
            'Root.Main',
            TextField::create(
                'IDCustomValue',
                _t(__CLASS__ . '.ID', 'ID')
            )
            ->setDescription(_t(__CLASS__ . '.IDCUSTOMVALUE', 'Define an ID for the link.  This is particularly useful for google tracking.'))
        );
        return $fields;
    }

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: // ForeignEmbeddedMethod mocks base method

func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "ForeignEmbeddedMethod")
	ret0, _ := ret[0].(*bufio.Reader)
	return ret0
}

public function setView($view)
    {
        parent::setView($view);

        if (!$this->_view instanceof LibBaseViewAbstract) {
            $view = AnInflector::isPlural($view) ? 'comments' : 'comment';
            $defaults[] = 'ComBaseView'.ucfirst($view).ucfirst($this->_view->name);
            register_default(array(
                'identifier' => $this->_view,
                'default' => $defaults, ));
        }

        return $this;
    }

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


Question:
Removes contacts

Delete contacts identified by contactIds from system. If id points to
non-existent contact the id will be ignored and processing will continue.

@api
@param Request\RemoveContacts $RemoveContacts = null

public function RemoveContacts(Request\RemoveContacts $RemoveContacts = null)
    {
        $uri = $this->getUri('/contact', array());

        return $this->delete($uri, $RemoveContacts);
    }

private function deserializeObjects(Item $question, array $objects = [], array $options = [])
    {
        $objectEntities = $question->getObjects()->toArray();
        $question->emptyObjects();

        foreach ($objects as $index => $objectData) {
            $existingObject = null;

            // Searches for an existing object entity.
            foreach ($objectEntities as $entityIndex => $entityObject) {
                /** @var ItemObject $entityObject */
                if ($entityObject->getUuid() === $objectData['id']) {
                    $existingObject = $entityObject;
                    unset($objectEntities[$entityIndex]);
                    break;
                }
            }
            $itemObject = $this->itemObjectSerializer->deserialize($objectData, $existingObject, $options);
            $itemObject->setOrder($index);
            $question->addObject($itemObject);
        }

        // Remaining objects are no longer in the Item
        if (0 < count($objectEntities)) {
            foreach ($objectEntities as $objectToRemove) {
                $this->om->remove($objectToRemove);
            }
        }
    }

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


Question:
// SetExecutionContextID sets the ExecutionContextID optional argument.
// Specifies in which execution context to perform script run. If the
// parameter is omitted the evaluation will be performed in the context
// of the inspected page.

func (a *CompileScriptArgs) SetExecutionContextID(executionContextID ExecutionContextID) *CompileScriptArgs {
	a.ExecutionContextID = &executionContextID
	return a
}

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question: // OverwriteFlags replaces any flags on the message with those specified.

func (m *DummyMessage) OverwriteFlags(newFlags types.Flags) Message {
	m.flags = newFlags
	return m
}

private function addHtmlMessage($type, $html = null, $css_selector = null)
    {
        return $this->add($type, array(
            'value' => $html,
            'selector' => $css_selector,
        ));
    }

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


Question: // Time returns a time.Time representation.

func (t Result) Time() time.Time {
	res, _ := time.Parse(time.RFC3339, t.String())
	return res
}

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

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