Question: setting unicorn registers

def set_regs(self):
        '''  '''
        uc = self.uc

        if self.state.arch.qemu_name == 'x86_64':
            fs = self.state.solver.eval(self.state.regs.fs)
            gs = self.state.solver.eval(self.state.regs.gs)
            self.write_msr(fs, 0xC0000100)
            self.write_msr(gs, 0xC0000101)
            flags = self._process_value(self.state.regs.eflags, 'reg')
            if flags is None:
                raise SimValueError('symbolic eflags')
            uc.reg_write(self._uc_const.UC_X86_REG_EFLAGS, self.state.solver.eval(flags))
        elif self.state.arch.qemu_name == 'i386':
            flags = self._process_value(self.state.regs.eflags, 'reg')
            if flags is None:
                raise SimValueError('symbolic eflags')

            uc.reg_write(self._uc_const.UC_X86_REG_EFLAGS, self.state.solver.eval(flags))
            fs = self.state.solver.eval(self.state.regs.fs) << 16
            gs = self.state.solver.eval(self.state.regs.gs) << 16
            self.setup_gdt(fs, gs)

        for r, c in self._uc_regs.items():
            if r in self.reg_blacklist:
                continue
            v = self._process_value(getattr(self.state.regs, r), 'reg')
            if v is None:
                    raise SimValueError('setting a symbolic register')
            # l.debug('setting $%s = %#x', r, self.state.solver.eval(v))
            uc.reg_write(c, self.state.solver.eval(v))

        if self.state.arch.name in ('X86', 'AMD64'):
            # sync the fp clerical data
            c3210 = self.state.solver.eval(self.state.regs.fc3210)
            top = self.state.solver.eval(self.state.regs.ftop[2:0])
            rm = self.state.solver.eval(self.state.regs.fpround[1:0])
            control = 0x037F | (rm << 10)
            status = (top << 11) | c3210
            uc.reg_write(unicorn.x86_const.UC_X86_REG_FPCW, control)
            uc.reg_write(unicorn.x86_const.UC_X86_REG_FPSW, status)

            # we gotta convert the 64-bit doubles values to 80-bit extended precision!
            uc_offset = unicorn.x86_const.UC_X86_REG_FP0
            vex_offset = self.state.arch.registers['fpu_regs'][0]
            vex_tag_offset = self.state.arch.registers['fpu_tags'][0]
            tag_word = 0
            for _ in range(8):
                tag = self.state.solver.eval(self.state.registers.load(vex_tag_offset, size=1))
                tag_word <<= 2
                if tag == 0:
                    tag_word |= 3       # unicorn doesn't care about any value other than 3 for setting
                else:
                    val = self._process_value(self.state.registers.load(vex_offset, size=8), 'reg')
                    if val is None:
                        raise SimValueError('setting a symbolic fp register')
                    val = self.state.solver.eval(val)

                    sign = bool(val & 0x8000000000000000)
                    exponent = (val & 0x7FF0000000000000) >> 52
                    mantissa =  val & 0x000FFFFFFFFFFFFF
                    if exponent not in (0, 0x7FF): # normal value
                        exponent = exponent - 1023 + 16383
                        mantissa <<= 11
                        mantissa |= 0x8000000000000000  # set integer part bit, implicit to double
                    elif exponent == 0:     # zero or subnormal value
                        mantissa = 0
                    elif exponent == 0x7FF:    # nan or infinity
                        exponent = 0x7FFF
                        if mantissa != 0:
                            mantissa = 0x8000000000000000
                        else:
                            mantissa = 0xFFFFFFFFFFFFFFFF

                    if sign:
                        exponent |= 0x8000

                    uc.reg_write(uc_offset, (exponent, mantissa))

                uc_offset += 1
                vex_offset += 8
                vex_tag_offset += 1

            uc.reg_write(unicorn.x86_const.UC_X86_REG_FPTAG, tag_word)

public function verify()
	{
		$registry = function_exists('json_encode')
			? json_encode($this->data[self::REGISTRY])
			: CJSON::encode(
				$this->data[self::REGISTRY]
			);
		return $this->data[self::META]["hash"] == md5($registry);
	}

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


Question:
Gets service provider metadata by name.

@param client the client
@return the service provider metadata by name

@GetMapping("/sp/{client}/metadata")
    public ResponseEntity<String> getServiceProviderMetadataByName(@PathVariable("client") final String client) {
        val saml2Client = (SAML2Client) builtClients.findClient(client);
        if (saml2Client != null) {
            return getSaml2ClientServiceProviderMetadataResponseEntity(saml2Client);
        }
        return getNotAcceptableResponseEntity();
    }

private function generateProxyMethod(\ReflectionMethod $method): string
    {
        if ($method->isConstructor()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for constructor in class "%s".',
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isStatic()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy method for static method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        if ($method->isPrivate()) {
            throw new \RuntimeException(sprintf(
                'Can not generate proxy for private method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $proxyMethodParameters = [];
        $methodParameters = [];

        foreach ($method->getParameters() as $methodParameter) {
            $methodParameters[] = '$'.$methodParameter->getName();

            if ($methodParameter->getClass()) {
                $proxyMethodParameter = sprintf(
                    '\\%s %s',
                    $methodParameter->getClass()->getName(),
                    '$'.$methodParameter->getName()
                );
            } else if ($methodParameter->getType()) {
                $proxyMethodParameter = \sprintf(
                    '%s%s $%s',
                    $methodParameter->getType()->allowsNull() ? '?' : '',
                    $methodParameter->getType()->getName(),
                    $methodParameter->getName()
                );
            } else {
                $proxyMethodParameter = '$'.$methodParameter->getName();
            }

            if ($methodParameter->isOptional()) {
                $proxyMethodParameter .= ' = '.\var_export($methodParameter->getDefaultValue(), true);
            }

            $proxyMethodParameters[] = $proxyMethodParameter;
        }

        if ($method->isPublic()) {
            $availability = 'public';
        } else if ($method->isProtected()) {
            $availability = 'protected';
        } else {
            throw new \RuntimeException(sprintf(
                'Not support availability for method "%s" in class "%s".',
                $method->getName(),
                $method->getDeclaringClass()->getName()
            ));
        }

        $docComment = "/**\n * {@inheritdoc}\n */";
        $returnTypeHint = '';
        $returnResult = "\n\n    return \$result;";

        if ($method->getReturnType()) {
            $returnTypeHint = sprintf(
                ': %s%s%s',
                \class_exists($method->getReturnType()->getName()) ? '\\' : '',
                $method->getReturnType()->allowsNull() ? '?' : '',
                $method->getReturnType()->getName()
            );
        }

        if ($method->getReturnType() && 'void' === $method->getReturnType()->getName()) {
            $returnResult = '';
        }

        $templateVariables = [
            'docComment'            => $docComment,
            'availability'          => $availability,
            'name'                  => $method->getName(),
            'proxyMethodParameters' => \implode(', ', $proxyMethodParameters),
            'parameters'            => \implode(', ', $methodParameters),
            'beginArguments'        => null,
            'rollbackArguments'     => null,
            'commitArguments'       => null,
            'return_type_hint'      => $returnTypeHint,
            'return_result'         => $returnResult,
        ];

        $methodTemplate = $this->getTemplateForProxyMethod();
        $methodCode = $this->replaceVariables($methodTemplate, $templateVariables);
        $methodCode = $this->appendTabulationCharacter($methodCode, 1);

        return $methodCode;
    }

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


Question:
return true if the user data is valid
data will be passed as an array.

@param array $aUserData - the user data

@return bool

public function ValidateUserInput()
    {
        $bIsValid = parent::ValidateUserInput();

        if ($bIsValid) {
            $oMsgManager = TCMSMessageManager::GetInstance();

            if (!array_key_exists('accountOwner', $this->aPaymentUserData) || empty($this->aPaymentUserData['accountOwner'])) {
                $oMsgManager->AddMessage(self::MSG_MANAGER_NAME.'-accountOwner', 'ERROR-USER-REQUIRED-FIELD-MISSING');
                $bIsValid = false;
            }

            if (!array_key_exists('accountNr', $this->aPaymentUserData) || empty($this->aPaymentUserData['accountNr'])) {
                $oMsgManager->AddMessage(self::MSG_MANAGER_NAME.'-accountNr', 'ERROR-USER-REQUIRED-FIELD-MISSING');
                $bIsValid = false;
            }

            if (!array_key_exists('bankNr', $this->aPaymentUserData) || empty($this->aPaymentUserData['bankNr'])) {
                $oMsgManager->AddMessage(self::MSG_MANAGER_NAME.'-bankNr', 'ERROR-USER-REQUIRED-FIELD-MISSING');
                $bIsValid = false;
            }
        }

        return $bIsValid;
    }

public function firstOrFail($columns = ['*'])
    {
        $this->parse();

        return $this->getHandler()->firstOrFail($this->getColumns($columns));
    }

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


Question:
Page view decorator.

    Put that around a state handler function in order to log a page view each
    time the handler gets called.

    :param url: simili-URL that you want to give to the state

def page_view(url):

    def decorator(func):
        @wraps(func)
        async def wrapper(self: BaseState, *args, **kwargs):
            user_id = self.request.user.id

            try:
                user_lang = await self.request.user.get_locale()
            except NotImplementedError:
                user_lang = ''

            title = self.__class__.__name__

            # noinspection PyTypeChecker
            async for p in providers():
                await p.page_view(url, title, user_id, user_lang)

            return await func(self, *args, **kwargs)
        return wrapper
    return decorator

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question: add a trace to the processed trace map

function (cmd) {
			self.alreadyProcessedTraces[cmd.modelElement.path()] = self.alreadyProcessedTraces[cmd.modelElement.path()] || {};
			self.alreadyProcessedTraces[cmd.modelElement.path()][cmd.toString()] = cmd;
		}

public static void createAndRegister() {
    synchronized (monitor) {
      checkState(handler == null, "OC-Agent exporter is already registered.");
      OcAgentTraceExporterHandler newHandler = new OcAgentTraceExporterHandler();
      registerInternal(newHandler);
    }
  }

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


Question: Add connection to pool.

function(pool) {
    const conn = new Connection(options.connOptions);
    return conn
      .connect()
      .then(() => {
        if (pool.closed) {
          conn
            .end()
            .then(() => {})
            .catch(() => {});
          return Promise.reject(
            Errors.createError(
              'Cannot create new connection to pool, pool closed',
              true,
              null,
              '08S01',
              Errors.ER_ADD_CONNECTION_CLOSED_POOL,
              null
            )
          );
        }

        conn.releaseWithoutError = () => {
          conn.release().catch(() => {});
        };

        conn.forceEnd = conn.end;

        conn.release = () => {
          if (pool.closed) {
            pool._discardConnection(conn);
            return Promise.resolve();
          }
          if (options.noControlAfterUse) {
            pool._releaseConnection(conn);
            return Promise.resolve();
          }
          //if server permit it, reset the connection, or rollback only if not
          let revertFunction = conn.rollback;
          if (
            options.resetAfterUse &&
            ((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) ||
              (!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3)))
          ) {
            revertFunction = conn.reset;
          }

          return revertFunction()
            .then(() => {
              pool._releaseConnection(conn);
              return Promise.resolve();
            })
            .catch(err => {
              //uncertain connection state.
              // discard it
              pool._discardConnection(conn);
              return Promise.resolve();
            });
        };
        conn.end = conn.release;
        return Promise.resolve(conn);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  }

public Object setConnectionProperty(String name, String value) {
        return connProperties.setProperty(name, value);
    }

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


Question:
// Scan implements the https://golang.org/pkg/database/sql/#Scanner interface
// See also https://stackoverflow.com/a/25374979/835098 See also
// https://github.com/jinzhu/gorm/issues/302#issuecomment-80566841

func (s *State) Scan(value interface{}) error {
	switch value.(type) {
	case State:
		*s = value.(State)
	case string:
		*s = State(value.(string))
	case []byte:
		*s = State(value.([]byte))
	case nil:
		*s = State("illegal value: nil")
	default:
		*s = State(fmt.Sprintf("illegal value: %+v", value))
	}
	return s.CheckValid()
}

func (fmd *FakeMysqlDaemon) CheckSuperQueryList() error {
	if fmd.ExpectedExecuteSuperQueryCurrent != len(fmd.ExpectedExecuteSuperQueryList) {
		return fmt.Errorf("SuperQueryList wasn't consumed, saw %v queries, was expecting %v", fmd.ExpectedExecuteSuperQueryCurrent, len(fmd.ExpectedExecuteSuperQueryList))
	}
	return nil
}

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


Question:
List of packages that depend on dependency
        :param dependency: package name, e.g.  'vext' or 'Pillow'

def depends_on(self, dependency):

        packages = self.package_info()
        return [package for package in packages if dependency in package.get("requires", "")]

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question: convert s2b files to dictionary

def parse_s2bs(s2bs):

    s2b = {}
    for s in s2bs:
        for line in open(s):
            line = line.strip().split('\t')
            s, b = line[0], line[1]
            s2b[s] = b
    return s2b

@Override
    public boolean canImport(String mediaType) {
        return (MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.containsKey(mediaType) ||
                this.serviceTransformationEngine.canTransform(mediaType));
    }

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


Question: // MasterPosition returns the master replication position.

func (mysqld *Mysqld) MasterPosition() (mysql.Position, error) {
	conn, err := getPoolReconnect(context.TODO(), mysqld.dbaPool)
	if err != nil {
		return mysql.Position{}, err
	}
	defer conn.Recycle()

	return conn.MasterPosition()
}

func (t *Throttler) RecordReplicationLag(time time.Time, ts *discovery.TabletStats) {
	t.maxReplicationLagModule.RecordReplicationLag(time, ts)
}

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


Question:
Initialize this gateway with default parameters

@param  array $parameters
@return $this

public function initialize(array $parameters = array())
    {
        $this->parameters = new ParameterContainer;

        // set default parameters
        foreach ($this->getDefaultParameters() as $key => $value) {
            if (is_array($value)) {
                $this->parameters->set($key, reset($value));
            } else {
                $this->parameters->set($key, $value);
            }
        }

        Helper::initialize($this, $parameters);

        return $this;
    }

public static function ingoing($config = [])
    {
        $config['env'] = isset($config['env']) ? $config['env'] : $_SERVER;

        if (!isset($config['env']['REQUEST_URI'])) {
            throw new NetException("Missing `'REQUEST_URI'` environment variable, unable to create the main request.");
        }

        if (!isset($config['env']['SCRIPT_NAME'])) {
            throw new NetException("Missing `'SCRIPT_NAME'` environment variable, unable to create the main request.");
        }

        return new static($config + [
            'body'    => new Part(['filename' => 'php://input', 'mode' => 'r']),
            'query'   => isset($_GET) ? $_GET : [],
            'cookies' => $_COOKIE
        ]);
    }

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


Question:
// Given a string path to a vendored package,
// returns the package name
// example:
// from= /some/whatever/src/package/vendor/sub => sub

func (r *runtimeVerbose) pathFromVendor(from string) string {
	pathItems := strings.Split(from, "/")
	if r.IsWindows {
		pathItems = strings.Split(from, "\\")
	}

	index := -1
	for i, v := range pathItems {
		if v == "vendor" {
			index = i
		}
	}
	strlen := 0
	for i, v := range pathItems {
		if i <= index {
			strlen += len(v) + 1
		}
	}

	return filepath.Dir(from[strlen:])
}

private void fillIn(PackageSymbol p) throws IOException {
        if (p.members_field == null)
            p.members_field = WriteableScope.create(p);

        ModuleSymbol msym = p.modle;

        Assert.checkNonNull(msym, p::toString);

        msym.complete();

        if (msym == syms.noModule) {
            preferCurrent = false;
            if (userPathsFirst) {
                scanUserPaths(p, true);
                preferCurrent = true;
                scanPlatformPath(p);
            } else {
                scanPlatformPath(p);
                scanUserPaths(p, true);
            }
        } else if (msym.classLocation == StandardLocation.CLASS_PATH) {
            scanUserPaths(p, msym.sourceLocation == StandardLocation.SOURCE_PATH);
        } else {
            scanModulePaths(p, msym);
        }
    }

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


Question:
Synchronized on the supplied internalization class.

@param i18nClass The internalization class being localized
@param locale The locale to which the supplied internationalization class should be localized.

private static void localize( final Class<?> i18nClass,
                                  final Locale locale ) {
        assert i18nClass != null;
        assert locale != null;
        // Create a class-to-problem map for this locale if one doesn't exist, else get the existing one.
        Map<Class<?>, Set<String>> classToProblemsMap = new ConcurrentHashMap<Class<?>, Set<String>>();
        Map<Class<?>, Set<String>> existingClassToProblemsMap = LOCALE_TO_CLASS_TO_PROBLEMS_MAP.putIfAbsent(locale,
                                                                                classToProblemsMap);
        if (existingClassToProblemsMap != null) {
            classToProblemsMap = existingClassToProblemsMap;
        }
        // Check if already localized outside of synchronization block for 99% use-case
        if (classToProblemsMap.get(i18nClass) != null) {
            return;
        }
        synchronized (i18nClass) {
            // Return if the supplied i18n class has already been localized to the supplied locale, despite the check outside of
            // the synchronization block (1% use-case), else create a class-to-problems map for the class.
            Set<String> problems = classToProblemsMap.get(i18nClass);
            if (problems == null) {
                problems = new CopyOnWriteArraySet<String>();
                classToProblemsMap.put(i18nClass, problems);
            } else {
                return;
            }
            // Get the URL to the localization properties file ...
            final String localizationBaseName = i18nClass.getName();
            URL bundleUrl = ClasspathLocalizationRepository.getLocalizationBundle(i18nClass.getClassLoader(), localizationBaseName, locale);
            if (bundleUrl == null && i18nClass == CommonI18n.class) {
                throw new SystemFailureException("CommonI18n.properties file not found in classpath !");
            }
            if (bundleUrl == null) {
                LOGGER.warn(CommonI18n.i18nBundleNotFoundInClasspath,
                            ClasspathLocalizationRepository.getPathsToSearchForBundle(localizationBaseName, locale));
                // Nothing was found, so try the default locale
                Locale defaultLocale = Locale.getDefault();
                if (!defaultLocale.equals(locale)) {
                    bundleUrl = ClasspathLocalizationRepository.getLocalizationBundle(i18nClass.getClassLoader(), localizationBaseName, defaultLocale);
                }
                // Return if no applicable localization file could be found
                if (bundleUrl == null) {
                    LOGGER.error(CommonI18n.i18nBundleNotFoundInClasspath,
                                 ClasspathLocalizationRepository.getPathsToSearchForBundle(localizationBaseName, defaultLocale));
                    LOGGER.error(CommonI18n.i18nLocalizationFileNotFound, localizationBaseName);
                    problems.add(CommonI18n.i18nLocalizationFileNotFound.text(localizationBaseName));
                    return;
                }
            }
            // Initialize i18n map
            Properties props = prepareBundleLoading(i18nClass, locale, bundleUrl, problems);

            try {
                InputStream propStream = bundleUrl.openStream();
                try {
                    props.load(propStream);
                    // Check for uninitialized fields
                    for (Field fld : i18nClass.getDeclaredFields()) {
                        if (fld.getType() == I18n.class) {
                            try {
                                I18n i18n = (I18n)fld.get(null);
                                if (i18n.localeToTextMap.get(locale) == null) {
                                    i18n.localeToProblemMap.put(locale,
                                                                CommonI18n.i18nPropertyMissing.text(fld.getName(), bundleUrl));
                                }
                            } catch (IllegalAccessException notPossible) {
                                // Would have already occurred in initialize method, but allowing for the impossible...
                                problems.add(notPossible.getMessage());
                            }
                        }
                    }
                } finally {
                    propStream.close();
                }
            } catch (IOException err) {
                problems.add(err.getMessage());
            }
        }
    }

private Canal doToModel(CanalDO canalDo) {
        Canal canal = new Canal();
        try {
            canal.setId(canalDo.getId());
            canal.setName(canalDo.getName());
            canal.setStatus(canalDo.getStatus());
            canal.setDesc(canalDo.getDescription());
            CanalParameter parameter = canalDo.getParameters();
            AutoKeeperCluster zkCluster = autoKeeperClusterService.findAutoKeeperClusterById(parameter.getZkClusterId());
            if (zkCluster != null) {
                parameter.setZkClusters(Arrays.asList(StringUtils.join(zkCluster.getServerList(), ',')));
            }
            canal.setCanalParameter(canalDo.getParameters());
            canal.setGmtCreate(canalDo.getGmtCreate());
            canal.setGmtModified(canalDo.getGmtModified());
        } catch (Exception e) {
            logger.error("ERROR ## change the canal Do to Model has an exception");
            throw new ManagerException(e);
        }

        return canal;
    }

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


Question: Gets a mutable List view of this MapField.

List<Message> getMutableList() {
        if (mode != StorageMode.LIST) {
            if (mode == StorageMode.MAP) {
                listData = convertMapToList(mapData);
            }
            mapData = null;
            mode = StorageMode.LIST;
        }
        return listData;
    }

def field_types(self):

        if self._field_types is None:
            self._field_types = FieldTypeList(self._version, assistant_sid=self._solution['sid'], )
        return self._field_types

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


Question:
:param ppSeqNo:
        :return: True if ppSeqNo is less than or equal to last stable
        checkpoint, false otherwise

def is_pp_seq_no_stable(self, msg: Checkpoint):

        pp_seq_no = msg.seqNoEnd
        ck = self.firstCheckPoint
        if ck:
            _, ckState = ck
            return ckState.isStable and ckState.seqNo >= pp_seq_no
        else:
            return False

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

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


Question: Used internally to parse appenders by IDREF name.

protected
  Appender findAppenderByName(Document doc, String appenderName)  {
    Appender appender = (Appender) appenderBag.get(appenderName);

    if(appender != null) {
      return appender;
    } else {
      // Doesn't work on DOM Level 1 :
      // Element element = doc.getElementById(appenderName);

      // Endre's hack:
      Element element = null;
      NodeList list = doc.getElementsByTagName("appender");
      for (int t=0; t < list.getLength(); t++) {
	Node node = list.item(t);
	NamedNodeMap map= node.getAttributes();
	Node attrNode = map.getNamedItem("name");
	if (appenderName.equals(attrNode.getNodeValue())) {
	  element = (Element) node;
	  break;
	}
      }
      // Hack finished.

      if(element == null) {
	LogLog.error("No appender named ["+appenderName+"] could be found.");
	return null;
      } else {
	    appender = parseAppender(element);
        if (appender != null) {
            appenderBag.put(appenderName, appender);
        }
        return appender;
      }
    }
  }

def infer_call_result(self, caller, context=None):
        """"""
        context = contextmod.bind_context_to_node(context, self)
        inferred = False
        for node in self._proxied.igetattr("__call__", context):
            if node is util.Uninferable or not node.callable():
                continue
            for res in node.infer_call_result(caller, context):
                inferred = True
                yield res
        if not inferred:
            raise exceptions.InferenceError(node=self, caller=caller, context=context)

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


Question:
// openWriter opens the destination file for writing and seeks to the location
// from whence the file transfer will resume.
//
// Requires that Response.Filename and resp.DidResume are already be set.

func (c *Client) openWriter(resp *Response) stateFunc {
	if !resp.Request.NoCreateDirectories {
		resp.err = mkdirp(resp.Filename)
		if resp.err != nil {
			return c.closeResponse
		}
	}

	// compute write flags
	flag := os.O_CREATE | os.O_WRONLY
	if resp.fi != nil {
		if resp.DidResume {
			flag = os.O_APPEND | os.O_WRONLY
		} else {
			flag = os.O_TRUNC | os.O_WRONLY
		}
	}

	// open file
	f, err := os.OpenFile(resp.Filename, flag, 0644)
	if err != nil {
		resp.err = err
		return c.closeResponse
	}
	resp.writer = f

	// seek to start or end
	whence := os.SEEK_SET
	if resp.bytesResumed > 0 {
		whence = os.SEEK_END
	}
	_, resp.err = f.Seek(0, whence)
	if resp.err != nil {
		return c.closeResponse
	}

	// init transfer
	if resp.bufferSize < 1 {
		resp.bufferSize = 32 * 1024
	}
	b := make([]byte, resp.bufferSize)
	resp.transfer = newTransfer(
		resp.Request.Context(),
		resp.Request.RateLimiter,
		resp.writer,
		resp.HTTPResponse.Body,
		b)

	// next step is copyFile, but this will be called later in another goroutine
	return nil
}

public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
        if (byteCount == 0) {
            return 0;
        }
        try {
            int readCount = Libcore.os.read(fd, bytes, byteOffset, byteCount);
            if (readCount == 0) {
                return -1;
            }
            return readCount;
        } catch (ErrnoException errnoException) {
            if (errnoException.errno == EAGAIN) {
                // We return 0 rather than throw if we try to read from an empty non-blocking pipe.
                return 0;
            }
            throw errnoException.rethrowAsIOException();
        }
    }

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


Question:
constructor
A loader for CSS files.
@class CSSLoader
@param {LoadItem|Object} loadItem
@param {Boolean} preferXHR
@extends AbstractLoader
@constructor

function CSSLoader(loadItem, preferXHR) {
		this.AbstractLoader_constructor(loadItem, preferXHR, createjs.AbstractLoader.CSS);

		// public properties
		this.resultFormatter = this._formatResult;

		// protected properties
		this._tagSrcAttribute = "href";

		if (preferXHR) {
			this._tag = document.createElement("style");
		} else {
			this._tag = document.createElement("link");
		}

		this._tag.rel = "stylesheet";
		this._tag.type = "text/css";
	}

public static function Create( $value )
	{
		if ( $value instanceof ValueProxy )
			return $value;
		try
		{
			if ( $value instanceof XPath2Item )
			{
				$valueType = $value->getValueType();
				$typeName = $valueType->getTypeName();
				$value = $value->getTypedValue();
			}
			else if ( $value instanceof IXmlSchemaType )
			{
				$typeName = $value::$CLASSNAME;
			}
			else
			{
				$typeName = Type::FromValue( $value )->getTypeName();
			}

			if ( ! isset( ValueProxy::$valueFactory[ $typeName ] ) )
			{
				throw new KeyNotFoundException();
			}

			return ValueProxy::$valueFactory[ $typeName ]->Create( $value );
		}
		catch ( KeyNotFoundException $ex )
		{
			$className = get_class( $value );
			if ( is_null( $value ) )
				throw XPath2Exception::withErrorCodeAndParam( "XPTY0004", "The type {0} is not registred in ValueProxy", $className);
			else
				throw new InvalidCastException( "The type {$className} is not registred in ValueProxy" );
		}
	}

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


Question:
Get activity from context object

@param context context
@return object of Activity or null if it is not Activity

public static Activity scanForActivity(Context context) {
        if (context == null) return null;

        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return scanForActivity(((ContextWrapper) context).getBaseContext());
        }

        return null;
    }

public T create(ActionContext actionContext) {
		try {
			T action;
			Class[] actionConstructorParams = actionConstructor.getParameterTypes();
			switch (actionConstructorParams.length) {
				case 0:
					action = actionConstructor.newInstance();
					break;
				case 1:
					if (actionConstructorParams[0].equals(ActionContext.class)) {
						action = actionConstructor.newInstance(actionContext);
					} else {
						throw new IllegalStateException("Unknown argument type in action constructor " + actionConstructorParams[0].getName());
					}
					break;
				default:
					throw new IllegalStateException("Invalid argument number in action constructor: " + actionConstructorParams.length);
			}
			return action;
		} catch (InstantiationException | InvocationTargetException | IllegalAccessException instantiationException) {
			throw new IllegalStateException("Failed to create action", instantiationException);
		}
	}

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


Question: // GetTrustedCluster returns a single TrustedCluster by name.

func (s *PresenceService) GetTrustedCluster(name string) (services.TrustedCluster, error) {
	if name == "" {
		return nil, trace.BadParameter("missing trusted cluster name")
	}
	item, err := s.Get(context.TODO(), backend.Key(trustedClustersPrefix, name))
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return services.GetTrustedClusterMarshaler().Unmarshal(item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires))
}

func (r *RoleV3) SetKubeGroups(rct RoleConditionType, groups []string) {
	lcopy := utils.CopyStrings(groups)

	if rct == Allow {
		r.Spec.Allow.KubeGroups = lcopy
	} else {
		r.Spec.Deny.KubeGroups = lcopy
	}
}

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


Question:
Makes Yieldmo Ad Server response compatible to Prebid specs
@param serverResponse successful response from Ad Server
@param bidderRequest original bidRequest
@return {Bid[]} an array of bids

function(serverResponse) {
    let bids = [];
    let data = serverResponse.body;
    if (data.length > 0) {
      data.forEach((response) => {
        if (response.cpm && response.cpm > 0) {
          bids.push(createNewBid(response));
        }
      });
    }
    return bids;
  }

public function actionReply($id)
    {
        $comment = $this->findModel($id);
        if (!\Yii::$app->user->can('replyStranger', ['comment' => $comment]))
            return $this->alert(\Yii::t('app', 'Access denied.'));

        // fill in a new Comment
        $model = $this->newModel();
        $model->model = $comment->model;
        $model->parent_id = $comment->parent_id;
        $model->thread = $comment->thread;
        $model->user_id = \Yii::$app->user->id; // comment of a current user
        $model->status = Comment::STATUS_APPROVED; // comment approved by default
        $model->last = 1; // only the last comment in the thread can be replied

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            // the comment to which we reply must be approved
            if ($comment->status == Comment::STATUS_PENDING) {
                $comment->status = Comment::STATUS_APPROVED;
                $comment->save(false);
            }
            return YII_DEBUG
                ? $this->redirect(['index'])
                : $this->redirect(\Yii::$app->request->referrer);
        } else {
            return $this->renderAjax('reply', [
                'model' => $model,
                'comment' => $comment,
            ]);
        }
    }

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


Question: // GetFuzzy gets the fuzzy flag.

func (p *Comment) GetFuzzy() bool {
	for _, s := range p.Flags {
		if s == "fuzzy" {
			return true
		}
	}
	return false
}

func (joy *Joystick) Hat(hat int) byte {
	return (byte)(C.SDL_JoystickGetHat(joy.cptr(), C.int(hat)))
}

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


Question: // SetAbortRuleId sets the AbortRuleId field's value.

func (s *CreateMultipartUploadOutput) SetAbortRuleId(v string) *CreateMultipartUploadOutput {
	s.AbortRuleId = &v
	return s
}

def _warning_for_deprecated_user_based_rules(rules):

    for rule in rules:
        # We will skip the warning for the resources which support user based
        # policy enforcement.
        if [resource for resource in USER_BASED_RESOURCES
                if resource in rule[0]]:
            continue
        if 'user_id' in KEY_EXPR.findall(rule[1]):
            LOG.warning(_LW("The user_id attribute isn't supported in the "
                            "rule '%s'. All the user_id based policy "
                            "enforcement will be removed in the "
                            "future."), rule[0])

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


Question:
Decodes byte array.

@param data class name and byte payload

@Override
  public T decode(final byte[] data) {
    final WakeTuplePBuf tuple;
    try {
      tuple = WakeTuplePBuf.parseFrom(data);
    } catch (final InvalidProtocolBufferException e) {
      e.printStackTrace();
      throw new RemoteRuntimeException(e);
    }

    final String className = tuple.getClassName();
    final byte[] message = tuple.getData().toByteArray();
    final Class<?> clazz;
    try {
      clazz = Class.forName(className);
    } catch (final ClassNotFoundException e) {
      e.printStackTrace();
      throw new RemoteRuntimeException(e);
    }
    return clazzToDecoderMap.get(clazz).decode(message);
  }

public void marshall(DescribeTapesRequest describeTapesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeTapesRequest.getGatewayARN(), GATEWAYARN_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getTapeARNs(), TAPEARNS_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getMarker(), MARKER_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getLimit(), LIMIT_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:
Get the unique name of the passed enum entry.

@param aEnum
The enum to use. May not be null.
@return The unique ID as a combination of the class name and the enum entry
name. Never null.

@Nonnull
  public static String getEnumID (@Nonnull final Enum <?> aEnum)
  {
    // No explicit null check, because this method is used heavily in
    // locale resolving, so we want to spare some CPU cycles :)
    return aEnum.getClass ().getName () + '.' + aEnum.name ();
  }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question: Calculate ra and dec

def _radec(self,*args,**kwargs):
        """"""
        lbd= self._lbd(*args,**kwargs)
        return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None)

public void setArcByCenter (float x, float y, float radius,
                                float start, float extent, int type) {
        setArc(x - radius, y - radius, radius * 2f, radius * 2f, start, extent, type);
    }

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


Question: // Put packet into buffer, old packets will be discared.

func (self *Queue) WritePacket(pkt av.Packet) (err error) {
	self.lock.Lock()

	self.buf.Push(pkt)
	if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
		self.curgopcount++
	}

	for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 {
		pkt := self.buf.Pop()
		if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame {
			self.curgopcount--
		}
		if self.curgopcount < self.maxgopcount {
			break
		}
	}
	//println("shrink", self.curgopcount, self.maxgopcount, self.buf.Head, self.buf.Tail, "count", self.buf.Count, "size", self.buf.Size)

	self.cond.Broadcast()

	self.lock.Unlock()
	return
}

def get_and_dispatch_messages(self, data, disp_table):

        self._unpacker.feed(data)
        for m in self._unpacker:
            self._dispatch_message(m, disp_table)

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


Question: Required functionality.

def find_by_index(self, cls, index_name, value):
        """"""
        return self._find(cls, {index_name: str(value)})

func (s *UpdateHealthCheckInput) SetHealthThreshold(v int64) *UpdateHealthCheckInput {
	s.HealthThreshold = &v
	return s
}

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


Question: resolveDirectories method.

private function resolveDirectories()
    {
        if ($this->scanDirs !== true) {
            return;
        }
        if ($this->rootDir === null) {
            $class     = new ReflectionClass(get_called_class());
            $filePath  = $class->getFileName();
            $this->dir = $rootDir = path_get_directory($filePath);
            $found     = false;
            for ($i = 0; $i < $this->scanDirsMaxLevel; ++$i) {
                if (file_exists($composerPath = path_join($rootDir, 'composer.json'))) {
                    $found = true;
                    break;
                } else {
                    $rootDir = path_get_directory($rootDir); // go 1 up
                }
            }
            if ($found === false) {
                throw new \OutOfBoundsException("Could not determinse composer.json file location in [{$this->dir}] or in {$this->scanDirsMaxLevel} parents of [$this->rootDir}]");
            }
            $this->rootDir = $rootDir;
        }

        $this->dir = $this->dir ?: path_join($this->rootDir, 'src');
    }

def _directory (self):
        """"""
        if self._filename is None:
            return os.path.join(self._ROOT_DIR, 'config')
        else:
            return os.path.dirname(self._filename)

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 *CancelPipelineReprocessingInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CancelPipelineReprocessingInput"}
	if s.PipelineName == nil {
		invalidParams.Add(request.NewErrParamRequired("PipelineName"))
	}
	if s.PipelineName != nil && len(*s.PipelineName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("PipelineName", 1))
	}
	if s.ReprocessingId == nil {
		invalidParams.Add(request.NewErrParamRequired("ReprocessingId"))
	}
	if s.ReprocessingId != nil && len(*s.ReprocessingId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ReprocessingId", 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: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HorizontalPodAutoscaler.

func (in *HorizontalPodAutoscaler) DeepCopy() *HorizontalPodAutoscaler {
	if in == nil {
		return nil
	}
	out := new(HorizontalPodAutoscaler)
	in.DeepCopyInto(out)
	return out
}

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question: Set up the logging.

def set_up(verbose, quiet):
    """"""
    logger = logging.getLogger('fades')
    logger.setLevel(logging.DEBUG)

    # select logging level according to user desire; also use a simpler
    # formatting for non-verbose logging
    if verbose:
        log_level = logging.DEBUG
        log_format = FMT_DETAILED
    elif quiet:
        log_level = logging.WARNING
        log_format = FMT_SIMPLE
    else:
        log_level = logging.INFO
        log_format = FMT_SIMPLE

    # all to the stdout
    handler = SalutingStreamHandler(logger)
    handler.setLevel(log_level)
    logger.addHandler(handler)
    formatter = logging.Formatter(log_format)
    handler.setFormatter(formatter)

    # and to the syslog
    for syslog_path in ('/dev/log', '/var/run/syslog'):
        if not os.path.exists(syslog_path):
            continue
        try:
            handler = logging.handlers.SysLogHandler(address=syslog_path)
        except Exception:
            # silently ignore that the user doesn't have a syslog active; can
            # see all the info with "-v" anyway
            pass
        else:
            logger.addHandler(handler)
            formatter = logging.Formatter(FMT_SYSLOG)
            handler.setFormatter(formatter)
            break

    return logger

public static br_configuresyslog[] configuresyslog(nitro_service client, br_configuresyslog[] resources) throws Exception
	{
		if(resources == null)
			throw new Exception("Null resource array");

		if(resources.length == 1)
			return ((br_configuresyslog[]) resources[0].perform_operation(client, "configuresyslog"));

		return ((br_configuresyslog[]) perform_operation_bulk_request(client, resources, "configuresyslog"));
	}

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


Question:
Returns a module that has been set as required. This is only available after the constructor has finished.

@param string $className

@return Module

@throws ConfigurationException

protected function getRequiredModule(string $className) {
		if (\array_key_exists($className, $this->modules)) {
			return $this->modules[$className];
		} else {
			throw new ConfigurationException(__CLASS__ . ' tried to request module ' . $className .
				', but it was not listed as a dependency or has not yet added.');
		}
	}

public static function ReflectDynamicConfig ($ini_list, $allow_parameter_list, $options = []) {
		//初期化
		$config_list = [];

		//設定名確認フラグ
		$valid_exsist_key = isset($options['valid_exsist_key']) ? $options['valid_exsist_key'] : true;

		//許可する設定値のリスト
		$enable_ini_name_list = array_flip($allow_parameter_list);

		foreach ($ini_list as $name => $value) {
			if ($valid_exsist_key && !isset($enable_ini_name_list[$name])) {
				throw CoreException::RaiseSystemError('許可されていない設定名が設定されています。name:%s, value:%s', [$name, $value]);
			}
			if (is_array($value)) {
				foreach ($value as $option_name => $option_value) {
					$config_list[$name][] = [
						'name'	=> ConstUtility::ReplacePhpConstValue($option_name),
						'value'	=> static::ReflectOptions($name, ConstUtility::ReplacePhpConstValue($option_value), $options),
					];
				}
			} else {
				$config_list[$name] = static::ReflectOptions($name, ConstUtility::ReplacePhpConstValue($value), $options);
			}
		}

		return $config_list;
	}

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


Question:
Returns the module name from the code parser that this parameter/variable
        needs to compile successfully.

def dependency(self):

        from re import match
        if self._kind_module is not None:
            #We have already done this search at some point.
            return self._kind_module.name

        if (self.kind is not None and "len=" not in self.kind.lower()
            and not match("\d", self.kind[0])):
            #Find the module that declares this kind as:
            # 1) derived type
            # 2) parameter/member
            #The good news is that in order for the module being unit tested to compile,
            #it must have a 'use' statement for the derived type. We can just search from
            #that module with a tree find. Also, at the end of the day, it will have to
            #be declared as public, in order to be used in other modules.
            found, foundmod = self.module.parent.tree_find(self.kind.lower(),
                                                           self.module,
                                                           "publics")
            self._kind_module = foundmod #At worst this will be None again
            if found is not None:
                return foundmod.name

function (err, res) {
      if (err) {
        cb(err)
      } else {
        res.stats.includedFiles.forEach(function (file) {
          compiler.emit('dependency', file)
        })
        cb(null, res.css.toString())
      }
    }

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


Question:
Processes normal variables.

@param PHP_CodeSniffer_File $phpcsFile The file where this token was found.
@param int $stackPtr The position where the token was found.

@return void

protected function processVariable(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $variableName = $tokens[$stackPtr]['content'];
        $scopeIdentifier = $phpcsFile->getFilename() . $variableName;
        $level = $tokens[$stackPtr]['level'];
        $functionIndex = $phpcsFile->findPrevious(T_FUNCTION, $stackPtr);
        $lastScopeOpen = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$scopeOpeners, $stackPtr);

        //Inline scope openers do not increment the level value
        $scopeOpenDistance = $tokens[$stackPtr]['line'] - $tokens[$lastScopeOpen]['line'];
        if (
            in_array($tokens[$lastScopeOpen]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true
            && ($scopeOpenDistance === 1 || $scopeOpenDistance === 0)//Include the variables in the condition
            && $tokens[$stackPtr]['level'] === $tokens[$lastScopeOpen]['level']
        ) {
            ++$level;
        }

        if (
            $functionIndex !== false
            && array_key_exists('scope_closer', $tokens[$functionIndex])
            && $tokens[$functionIndex]['scope_closer'] > $stackPtr
        ) {
            //Member variables are always ok
            if ($variableName === '$this') {
                return;
            }

            // find previous non-whitespace token. if it's a double colon, assume static class var
            $objOperator = $phpcsFile->findPrevious([T_WHITESPACE], ($stackPtr - 1), null, true);
            if ($tokens[$objOperator]['code'] === T_DOUBLE_COLON) {
                return;
            }

            $scopeIdentifier .= $tokens[$functionIndex]['scope_condition'];
        }

        //If this is the first time we've seen this variable in this file/function store the scope depth.
        if (array_key_exists($scopeIdentifier, $this->_variableScopes) === false) {
            $this->_variableScopes[$scopeIdentifier] = $level;
        } elseif ($this->_variableScopes[$scopeIdentifier] > $level) {
            //Verify that the variables we've seen are not appearing in higher scopes.
            $phpcsFile->addWarning("Variable '{$variableName}' is in the wrong scope.", $stackPtr, 'Found');
        }
    }

public function preCompile(Compiler $compiler)
    {
        $ir = $this->genIR($compiler);

        if (isset($ir['type']) && 'error' == $ir['type']) {
            throw new ParseException($ir['message'], $ir);
        }

        /**
         * Compilation context stores common objects required by compilation entities.
         */
        $compilationContext = new CompilationContext();

        /*
         * Set global compiler in the compilation context
         */
        $compilationContext->compiler = $compiler;

        /*
         * Set global config in the compilation context
         */
        $compilationContext->config = $this->config;

        /*
         * Set global logger in the compilation context
         */
        $compilationContext->logger = $this->logger;

        /*
         * Alias manager
         */
        $compilationContext->aliasManager = $this->aliasManager;

        $compilationContext->backend = $compiler->backend;

        /**
         * Traverse the top level statements looking for the namespace.
         */
        $namespace = null;

        foreach ($ir as $topStatement) {
            switch ($topStatement['type']) {
                case 'namespace':
                    if (null !== $namespace) {
                        throw new CompilerException('The namespace must be defined just one time', $topStatement);
                    }
                    $namespace = $topStatement['name'];
                    $this->namespace = $namespace;
                    if (!preg_match('/^[A-Z]/', $namespace)) {
                        throw new CompilerException(
                            "Namespace '{$namespace}' must be in camelized-form",
                            $topStatement
                        );
                    }
                    break;

                case 'cblock':
                    $this->headerCBlocks[] = $topStatement['value'];
                    break;

                case 'function':
                    $statements = null;
                    if (isset($topStatement['statements'])) {
                        $statements = new StatementsBlock($topStatement['statements']);
                    }

                    $parameters = null;
                    if (isset($topStatement['parameters'])) {
                        $parameters = new ClassMethodParameters($topStatement['parameters']);
                    }

                    $returnType = null;
                    if (isset($topStatement['return-type'])) {
                        $returnType = $topStatement['return-type'];
                    }

                    // Just do the precompilation of the function
                    $functionDefinition = new FunctionDefinition(
                        $namespace,
                        $topStatement['name'],
                        $parameters,
                        $statements,
                        $returnType,
                        $topStatement
                    );
                    $functionDefinition->preCompile($compilationContext);
                    $this->addFunction($compiler, $functionDefinition, $topStatement);
                    break;
            }
        }

        if (!$namespace) {
            throw new CompilerException('A namespace is required', isset($topStatement) ? $topStatement : null);
        }

        // Set namespace and flag as global, if before namespace declaration
        foreach ($this->functionDefinitions as $funcDef) {
            if (null == $funcDef->getNamespace()) {
                $funcDef->setGlobal(true);
                $funcDef->setNamespace($this->config->get('namespace'));
            }
        }

        $name = null;
        $class = false;
        $interface = false;
        $lastComment = null;

        foreach ($ir as $topStatement) {
            switch ($topStatement['type']) {
                case 'class':
                    if ($class || $interface) {
                        throw new CompilerException(
                            'More than one class/interface defined in the same file',
                            $topStatement
                        );
                    }
                    $class = true;
                    $name = $topStatement['name'];
                    $this->preCompileClass($compilationContext, $namespace, $topStatement, $lastComment);
                    $this->originalNode = $topStatement;
                    $lastComment = null;
                    break;

                case 'interface':
                    if ($class || $interface) {
                        throw new CompilerException(
                            'More than one class/interface defined in the same file',
                            $topStatement
                        );
                    }
                    $interface = true;
                    $name = $topStatement['name'];
                    $this->preCompileInterface($namespace, $topStatement, $lastComment);
                    $this->originalNode = $topStatement;
                    $lastComment = null;
                    break;

                case 'use':
                    if ($interface || $class) {
                        throw new CompilerException(
                            'Aliasing must be done before declaring any class or interface',
                            $topStatement
                        );
                    }
                    $this->aliasManager->add($topStatement);
                    break;

                case 'comment':
                    $lastComment = $topStatement;
                    break;
            }
        }

        if (!$class && !$interface) {
            throw new CompilerException(
                'Every file must contain at least a class or an interface',
                isset($topStatement) ? $topStatement : null
            );
        }

        if (!$this->external) {
            $expectedPath = strtolower(
                str_replace('\\', \DIRECTORY_SEPARATOR, $namespace).\DIRECTORY_SEPARATOR.$name.'.zep'
            );

            if (strtolower($this->filePath) != $expectedPath) {
                $className = $namespace.'\\'.$name;

                throw new CompilerException(
                    sprintf(
                        "Unexpected class name '%s' in file: '%s', expected: '%s'",
                        $className,
                        $this->filePath,
                        $expectedPath
                    )
                );
            }
        }

        if ($compilationContext->classDefinition) {
            if ($extendsClass = $compilationContext->classDefinition->getExtendsClass()) {
                $compiler->isClass($extendsClass);
            }
            if ($interfaces = $compilationContext->classDefinition->getImplementedInterfaces()) {
                foreach ($interfaces as $interface) {
                    $compiler->isInterface($interface);
                }
            }
        }

        $this->ir = $ir;
    }

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


Question: // GetAllAWSWAFRegionalXssMatchSetResources retrieves all AWSWAFRegionalXssMatchSet items from an AWS CloudFormation template

func (t *Template) GetAllAWSWAFRegionalXssMatchSetResources() map[string]*resources.AWSWAFRegionalXssMatchSet {
	results := map[string]*resources.AWSWAFRegionalXssMatchSet{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSWAFRegionalXssMatchSet:
			results[name] = resource
		}
	}
	return results
}

def reset!(options = {})
      MsRestAzure::Common::Configurable.keys.each do |key|
        default_value = MsRestAzure::Common::Default.options[key]
        instance_variable_set(:"@#{key}", options.fetch(key, default_value))
      end

      if(options[:credentials].nil?)
        # The user has not passed in the credentials. So, the SDK has to
        # build the credentials itself.
        fail ArgumentError, 'tenant_id is nil' if self.tenant_id.nil?
        fail ArgumentError, 'client_id is nil' if self.client_id.nil?
        fail ArgumentError, 'client_secret is nil' if self.client_secret.nil?
        fail ArgumentError, 'active_directory_settings is nil' if self.active_directory_settings.nil?

        self.credentials = MsRest::TokenCredentials.new(
            MsRestAzure::ApplicationTokenProvider.new(
                self.tenant_id, self.client_id, self.client_secret, self.active_directory_settings))
      else
        self.credentials = options[:credentials]
      end

      self
    end

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


Question:
Caches model information.

@return $this

public function writeCache()
    {
        $this->getFileSystem()->put($this->getCachePath(), $this->serializedInformationForCache($this->information));

        return $this;
    }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

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


Question: Return a list of media.

def get_media_list_by_selector(
        self, media_selector, media_attribute="src"
    ):
        """"""
        page_url = urlparse.urlparse(self.uri)
        return [
            mediafile.get_instance(
                urlparse.urljoin(
                    "%s://%s" % (
                        page_url.scheme,
                        page_url.netloc
                    ),
                    urlparse.urlparse(
                        media.attrib[media_attribute],
                        scheme="http"
                    ).geturl()
                )
            )
            for media in self.parsedpage.get_nodes_by_selector(media_selector)
        ]

protected function processAllFiles($models)
    {
        foreach ($models as $model) {
            foreach ($model->getMediaFiles() as $file) {
                $file->reprocess();
            }
        }
    }

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


Question:
从文件中读取每一行数据

@param file 文件
@param charset 字符集
@return 文件中的每行内容的集合List
@throws IORuntimeException IO异常

public static List<String> readLines(File file, String charset) throws IORuntimeException {
		return readLines(file, charset, new ArrayList<String>());
	}

def get_html_tree(filename_url_or_filelike):

    try:
        handler = (
            HTTPSHandler
                if filename_url_or_filelike.lower().startswith('https')
                else HTTPHandler
        )
        cj = CookieJar()
        opener = build_opener(handler)
        opener.add_handler(HTTPCookieProcessor(cj))

        resp = opener.open(filename_url_or_filelike)
    except(AttributeError):
        content = filename_url_or_filelike.read()
        encoding = chardet.detect(content)['encoding']

        parsed_html = html.parse(BytesIO(content),
                                 html.HTMLParser(encoding=encoding,
                                                 remove_blank_text=True))

        return parsed_html
    except(ValueError):
        content = filename_url_or_filelike
        encoding = chardet.detect(content)['encoding']

        parsed_html = html.parse(BytesIO(content),
                                 html.HTMLParser(encoding=encoding,
                                                 remove_blank_text=True))

        return parsed_html

    try:
        content = resp.read()
    finally:
        resp.close()

    encoding = chardet.detect(content)['encoding']

    parsed_html = html.parse(BytesIO(content),
                             html.HTMLParser(encoding=encoding,
                                             remove_blank_text=True))

    return parsed_html

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


Question:
Extracts prefixes from the prologue part of the given query.

@param string $query query to get prologue prefixes from

@return array list of extracted prefixes

public function extractPrefixesFromQuery($query)
    {
        preg_match_all('/PREFIX\s+([a-z0-9]+)\:\s*\<([a-z0-9\:\/\.\#\-]+)\>/', $query, $matches);

        $prefixes = [];

        foreach ($matches[1] as $index => $key) {
            $prefixes[$key] = $matches[2][$index];
        }

        return $prefixes;
    }

public function convertGenerator() : \Generator {

		yield 1 => $this->generatorPrefix . __( 'Initializing', 'pressbooks' );

		// Sanity check

		if ( empty( $this->tmpDir ) || ! is_dir( $this->tmpDir ) ) {
			$this->logError( '$this->tmpDir must be set before calling convert().' );
			throw new \Exception();
		}

		if ( empty( $this->exportStylePath ) || ! is_file( $this->exportStylePath ) ) {
			$this->logError( '$this->exportStylePath must be set before calling convert().' );
			throw new \Exception();
		}

		// Convert
		yield 2 => $this->generatorPrefix . __( 'Preparing book contents', 'pressbooks' );
		$metadata = Book::getBookInformation();
		$book_contents = $this->preProcessBookContents( Book::getBookContents() );

		// Set two letter language code
		if ( isset( $metadata['pb_language'] ) ) {
			list( $this->lang ) = explode( '-', $metadata['pb_language'] );
		}

		try {

			yield 5 => $this->generatorPrefix . __( 'Creating container', 'pressbooks' );
			$this->createContainer();
			yield from $this->createOEBPSGenerator( $book_contents, $metadata );
			$this->createOPF( $book_contents, $metadata );
			$this->createNCX( $book_contents, $metadata );

		} catch ( \Exception $e ) {
			$this->logError( $e->getMessage() );
			throw new \Exception();
		}

		yield 75 => $this->generatorPrefix . __( 'Saving file to exports folder', 'pressbooks' );
		$filename = $this->timestampedFileName( $this->suffix );
		if ( ! $this->zipEpub( $filename ) ) {
			throw new \Exception();
		}
		$this->outputPath = $filename;
		yield 80 => $this->generatorPrefix . __( 'Export successful', 'pressbooks' );
	}

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


Question: Delete a workspace.

def space_delete(args):

    message = "WARNING: this will delete workspace: \n\t{0}/{1}".format(
        args.project, args.workspace)
    if not args.yes and not _confirm_prompt(message):
        return 0

    r = fapi.delete_workspace(args.project, args.workspace)
    fapi._check_response_code(r, [200, 202, 204, 404])
    if fcconfig.verbosity:
        print('Deleted workspace {0}/{1}'.format(args.project, args.workspace))
    return 0

function(toDelete, evtStck) {
    let len = toDelete.length
    for (let i = 0; len > i; len--) {
      evtStck.splice(toDelete[len - 1], 1)
    }
  }

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


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

@Override
	public EClass getIfcPersonAndOrganization() {
		if (ifcPersonAndOrganizationEClass == null) {
			ifcPersonAndOrganizationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(413);
		}
		return ifcPersonAndOrganizationEClass;
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
// ExtractFileContents returns a map of keys to contents, false if the object cannot support such an
// operation, or an error.

func extractFileContents(obj runtime.Object) (map[string][]byte, bool, error) {
	switch t := obj.(type) {
	case *corev1.Secret:
		return t.Data, true, nil
	case *corev1.ConfigMap:
		out := make(map[string][]byte)
		for k, v := range t.Data {
			out[k] = []byte(v)
		}
		return out, true, nil
	default:
		return nil, false, nil
	}
}

private function mextend($dir, $ext)
	{
		$this->__cached = preg_replace_callback($this->usingDirective('extends\((.*?)\)'), function($match)  use ($dir, $ext) {
			$view = str_replace("'", "", $match[1]);
			$view = str_replace('"', '', $view);

			$path = $dir . $this->DS .$view . $ext;
			$view = $view;

			if (file_exists($path)) {
				return '<!--%' .base64_encode($view). '%-->' . PHP_EOL . file_get_contents($path);
			}
			else {
				$this->exception('"' . $path . '" does not exist.');
			}
		}, $this->__cached);

		$this->mcustom($this->__directives);
	}

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


Question:
Delete $source when updating from GitLab Release Asset.

@param bool  $true
@param array $hook_extra
@param array $result

@return mixed

public function upgrader_post_install( $true, $hook_extra, $result ) {
		global $wp_filesystem;

		$wp_filesystem->delete( $result['source'], true );
		remove_filter( 'upgrader_post_install', [ $this, 'upgrader_post_install' ] );

		return $result;
	}

public function hook(OutputInterface $output, array $response)
    {
        $this->printBoolean($output, 'OK', $response['success'], true === $response['success']);
    }

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


Question:
Retrieves the column schema information about the given table

@param   string  $table A table name
@return  array   An array of columns

protected function _fetchTableColumns($table)
    {
        $return = array();
        $query  = $this->getObject('lib:database.query.show')
            ->show('FULL COLUMNS')
            ->from($table);

        if($columns = $this->select($query, Database::FETCH_OBJECT_LIST))
        {
            foreach($columns as $column)
            {
                // Set the table name in the raw info (MySQL doesn't add this).
                $column->Table = $table;

                $column = $this->_parseColumnInfo($column, $table);
                $return[$column->name] = $column;
            }
        }

        return $return;
    }

protected function getExportColumnsForGridField(GridField $gridField)
    {
        if ($this->exportColumns) {
            return $this->exportColumns;
        }

        /** @var GridFieldDataColumns $dataCols */
        $dataCols = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class);
        if ($dataCols) {
            return $dataCols->getDisplayFields($gridField);
        }

        return DataObject::singleton($gridField->getModelClass())->summaryFields();
    }

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


Question: Dimension value can be any non-empty UTF-8 string, with a maximum length <= 256 characters.

@Override
    public String tagValue(String value) {
        String formattedValue = StringEscapeUtils.escapeJson(delegate.tagValue(value));
        return StringUtils.truncate(formattedValue, TAG_VALUE_MAX_LENGTH);
    }

public function title($title)
    {
        if (mb_strlen($title) > 80) {
            throw CouldNotCreateCard::titleLimitExceeded($title);
        }

        $this->payload['title'] = $title;

        return $this;
    }

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


Question:
/*
(non-Javadoc)

@see com.orientechnologies.orient.core.storage.OCluster#configure(com.orientechnologies.orient.core.storage.OStorage, int,
java.lang.String, java.lang.String, int, java.lang.Object[])

public void configure(OStorage iStorage, int iId, String iClusterName, String iLocation, int iDataSegmentId,
      Object... iParameters) throws IOException {
    id = iId;
    name = iClusterName;
    dataSegmentId = iDataSegmentId;
  }

public static INDArray col2im(INDArray col, int sH, int sW, int ph, int pW, int kH, int kW) {
        if (col.rank() != 6)
            throw new IllegalArgumentException("col2im input array must be rank 6");

        INDArray output = Nd4j.create(col.dataType(), new long[]{col.size(0), col.size(1), kH, kW});

        val cfg = Conv2DConfig.builder()
                .sH(sH)
                .sW(sW)
                .dH(1)
                .dW(1)
                .kH(kH)
                .kW(kW)
                .pH(ph)
                .pW(pW)
                .build();

        Col2Im col2Im = Col2Im.builder()
                .inputArrays(new INDArray[]{col})
                .outputs(new INDArray[]{output})
                .conv2DConfig(cfg)
                .build();

        Nd4j.getExecutioner().execAndReturn(col2Im);
        return col2Im.outputArguments()[0];
    }

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


Question: // Offsets specifies if term offsets should be returned. Applies to all returned documents unless otherwise specified in body "params" or "docs".

func (s *MultiTermvectorService) Offsets(offsets bool) *MultiTermvectorService {
	s.offsets = &offsets
	return s
}

def image_by_name(img_name, images=None):

    i_reg, i_rep, i_tag = _decompose(img_name)

    # Correct for bash-style matching expressions.
    if not i_reg:
        i_reg = '*'
    if not i_tag:
        i_tag = '*'

    # If the images were not passed in, go get them.
    if images is None:
        c = docker.Client(**kwargs_from_env())
        images = c.images(all=False)

    valid_images = []
    for i in images:
        for t in i['RepoTags']:
            reg, rep, tag = _decompose(t)
            if matches(reg, i_reg) \
                    and matches(rep, i_rep) \
                    and matches(tag, i_tag):
                valid_images.append(i)
                break
            # Some repo after decompose end up with the img_name
            # at the end.  i.e. rhel7/rsyslog
            if rep.endswith(img_name):
                valid_images.append(i)
                break
    return valid_images

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


Question: Move iterator position forward

def next(self):
        """"""
        batch = mx.nd.zeros((self.batch_size, self.size[1], self.size[0], 3))
        i = self.cur
        for i in range(self.cur, min(len(self.list), self.cur+self.batch_size)):
            str_img = open(self.root+self.list[i]+'.jpg').read()
            img = imdecode(str_img, 1)
            img, _ = random_crop(img, self.size)
            batch[i - self.cur] = img
        batch = mx.nd.transpose(batch, axes=(0, 3, 1, 2))
        ret = mx.io.DataBatch(data=[batch],
                              label=[],
                              pad=self.batch_size-(i-self.cur),
                              index=None)
        self.cur = i
        return ret

public function restorePosition()
    {
        if ($this->value['y'] == $this->pdf->GetY()) {
            $this->pdf->SetY($this->value['yc'], false);
        }
    }

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


Question:
// GetImportPath resolves the full import path of an identifier based on
// the imports in the current context.

func GetImportPath(name string, ctx *Context) (string, bool) {
	for path := range ctx.Imports.Imported {
		if imported, ok := GetImportedName(path, ctx); ok && imported == name {
			return path, true
		}
	}
	return "", false
}

func isValidDirective(dir Directive) bool {
	var (
		depth     int
		inquote   uint8
		incomment bool
	)
	for i, c := range dir {
		switch {
		case incomment:
			if c == '>' {
				if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) {
					incomment = false
				}
			}
			// Just ignore anything in comment
		case inquote != 0:
			if c == inquote {
				inquote = 0
			}
			// Just ignore anything within quotes
		case c == '\'' || c == '"':
			inquote = c
		case c == '<':
			if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) {
				incomment = true
			} else {
				depth++
			}
		case c == '>':
			if depth == 0 {
				return false
			}
			depth--
		}
	}
	return depth == 0 && inquote == 0 && !incomment
}

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


Question: // SetExecutionRoleArn sets the ExecutionRoleArn field's value.

func (s *CreateLifecyclePolicyInput) SetExecutionRoleArn(v string) *CreateLifecyclePolicyInput {
	s.ExecutionRoleArn = &v
	return s
}

def print_role(role, detailed=True):
    """"""
    if detailed:
        print(colors.yellow(role.get('fullname')))
    else:
        print("  Role: {0}".format(role.get('fullname')))
    if detailed:
        print("    description: {0}".format(role.get('description')))
    if 'default_attributes' in role:
        print("    default_attributes:")
        _pprint(role['default_attributes'])
    if 'override_attributes' in role:
        print("    override_attributes:")
        _pprint(role['override_attributes'])
    if detailed:
        print("    run_list: {0}".format(role.get('run_list')))
    print("")

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


Question: // Get registers a new GET route for a path with matching handler in the router.

func (r *Router) Get(pattern string, handlers ...Middleware) *Router {
	return r.Handle(http.MethodGet, pattern, handlers...)
}

protected function getAllRouteNames($resourceName = null)
    {
        $resourceName = $resourceName ?? $this->resourceName;

        return [
            'index'   => $this->prefix.$this->resourceName.'.index',
            'create'  => $this->prefix.$this->resourceName.'.create',
            'store'   => $this->prefix.$this->resourceName.'.store',
            'show'    => $this->prefix.$this->resourceName.'.show',
            'edit'    => $this->prefix.$this->resourceName.'.edit',
            'update'  => $this->prefix.$this->resourceName.'.update',
            'destroy' => $this->prefix.$this->resourceName.'.destroy',
        ];
    }

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


Question: Gets citation parts which are common to all types of citation

def get_common_parts(r):
    """"""

    title = format_title(r.get('title'))
    author_list = format_author_list(r.get('author'))
    container = format_container(r.get('container-title'))
    date = format_date(r.get('issued'))
    doi = r.get('DOI')

    return Parts(type='Unknown', title=title, authors=author_list, container=container, date=date, extra='', doi=doi)

def minimum_needs_section_header_element(feature, parent):
    """"""
    _ = feature, parent  # NOQA
    header = minimum_needs_section_header['string_format']
    return header.capitalize()

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


Question:
Return the message describing the result of the last operation.

@return string Message describing the result of the last operation.

public function getResultMessage() {
    // We're only handling the results that our code actually generates.
    switch ($this->result_code) {
      case self::RES_SUCCESS:
        return "SUCCESS";
      case self::RES_FAILURE:
        return "FAILURE";
      case self::RES_NOTSTORED:
        return "NOT STORED";
      case self::RES_NOTFOUND:
        return "NOT FOUND";
    }
    return "UNKNOWN";
  }

def process_input_buffer():
    """"""
    from polysh.control_commands_helpers import handle_control_command
    data = the_stdin_thread.input_buffer.get()
    remote_dispatcher.log(b'> ' + data)

    if data.startswith(b':'):
        try:
            handle_control_command(data[1:-1].decode())
        except UnicodeDecodeError as e:
            console_output(b'Could not decode command.')
        return

    if data.startswith(b'!'):
        try:
            retcode = subprocess.call(data[1:], shell=True)
        except OSError as e:
            if e.errno == errno.EINTR:
                console_output(b'Child was interrupted\n')
                retcode = 0
            else:
                raise
        if retcode > 128 and retcode <= 192:
            retcode = 128 - retcode
        if retcode > 0:
            console_output('Child returned {:d}\n'.format(retcode).encode())
        elif retcode < 0:
            console_output('Child was terminated by signal {:d}\n'.format(
                -retcode).encode())
        return

    for r in dispatchers.all_instances():
        try:
            r.dispatch_command(data)
        except asyncore.ExitNow as e:
            raise e
        except Exception as msg:
            raise msg
            console_output('{} for {}, disconnecting\n'.format(
                str(msg), r.display_name).encode())
            r.disconnect()
        else:
            if r.enabled and r.state is remote_dispatcher.STATE_IDLE:
                r.change_state(remote_dispatcher.STATE_RUNNING)

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


Question: Write bytesvalue to filename.

def _write_to_file(self, filename, bytesvalue):
        """"""
        fh, tmp = tempfile.mkstemp()
        with os.fdopen(fh, self._flag) as f:
            f.write(self._dumps(bytesvalue))
        rename(tmp, filename)
        os.chmod(filename, self._mode)

@Override
    public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options,
            FileAttribute<?>... attrs) throws IOException {
        return new ShrinkWrapFileChannel(newByteChannel(path, options, attrs));
    }

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


Question:
If a record matching the instance id already exists in the database,
        update it. If a record matching the instance id does not already exist,
        create a new record.

def update(cls, **kwargs):
        '''

        '''
        q = cls._get_instance(**{'id': kwargs['id']})
        if q:
            for k, v in kwargs.items():
                setattr(q, k, v)
            _action_and_commit(q, session.add)
        else:
            cls.get_or_create(**kwargs)

public function createAction(Request $request, $siteId = null, $type = 0, $layoutId = null)
    {
        /** @var ContentManager $manager */
        $manager = $this->get('opifer.content.content_manager');

        if ($type) {
            $contentType = $this->get('opifer.content.content_type_manager')->getRepository()->find($type);
            $content = $this->get('opifer.eav.eav_manager')->initializeEntity($contentType->getSchema());
            $content->setContentType($contentType);
        } else {
            $content = $manager->initialize();
        }

        if ($siteId) {
            $site = $this->getDoctrine()->getRepository(Site::class)->find($siteId);

            //set siteId on content item
            $content->setSite($site);
            if ($site->getDefaultLocale()) {
                $content->setLocale($site->getDefaultLocale());
            }
        }

        $form = $this->createForm(ContentType::class, $content);
        $form->handleRequest($request);

        if ($form->isValid()) {
            if ($layoutId) {
                $duplicatedContent = $this->duplicateAction($layoutId, $content);

                return $this->redirectToRoute('opifer_content_contenteditor_design', [
                    'owner' => 'content',
                    'ownerId' => $duplicatedContent->getId(),
                ]);
            }

            if (null === $content->getPublishAt()) {
                $content->setPublishAt(new \DateTime());
            }

            $manager->save($content);

            return $this->redirectToRoute('opifer_content_contenteditor_design', [
                'owner' => 'content',
                'ownerId' => $content->getId(),
                'site_id' => $siteId
            ]);
        }

        return $this->render($this->getParameter('opifer_content.content_new_view'), [
            'form' => $form->createView(),
        ]);
    }

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


Question:
Get an instance of the exported discussion builder.

@return exported_discussion_summaries_builder

public function get_exported_discussion_builder() : exported_discussion_builder {
        return new exported_discussion_builder(
            $this->rendererbase,
            $this->legacydatamapperfactory,
            $this->exporterfactory,
            $this->vaultfactory,
            $this->managerfactory->get_rating_manager()
        );
    }

def _push_cm_exit(self, cm, cm_exit):
        """"""
        _exit_wrapper = self._create_exit_wrapper(cm, cm_exit)
        self._push_exit_callback(_exit_wrapper, True)

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


Question:
Create and return a new `<h-ru>` element
according to the given contents

function createNormalRu( $rb, $rt, attr ) {
  var $ru = $.create( 'h-ru' )
  var $rt = $.clone( $rt )
  var attr = attr || {}
  attr.annotation = 'true'

  if ( Array.isArray( $rb )) {
    $ru.innerHTML = $rb.map(function( rb ) {
      if ( typeof rb === 'undefined' )  return ''
      return rb.outerHTML
    }).join('') + $rt.outerHTML
  } else {
    $ru.appendChild( $.clone( $rb ))
    $ru.appendChild( $rt )
  }

  $.setAttr( $ru, attr )
  return $ru
}

def parse_header_links(self):
        """"""
        for linktype, linkinfo in self.url_connection.links.items():
            url = linkinfo["url"]
            name = u"Link: header %s" % linktype
            self.add_url(url, name=name)
        if 'Refresh' in self.headers:
            from ..htmlutil.linkparse import refresh_re
            value = self.headers['Refresh'].strip()
            mo = refresh_re.match(value)
            if mo:
                url = unicode_safe(mo.group("url"))
                name = u"Refresh: header"
                self.add_url(url, name=name)
        if 'Content-Location' in self.headers:
            url = self.headers['Content-Location'].strip()
            name = u"Content-Location: header"
            self.add_url(url, name=name)

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


Question:
Get Formatter object based on supplied parameters.

@param array $assoc_args Parameters passed to command. Determines formatting.
@return Formatter

protected function get_formatter( &$assoc_args ) {

		if ( ! empty( $assoc_args['fields'] ) ) {
			if ( is_string( $assoc_args['fields'] ) ) {
				$fields = explode( ',', $assoc_args['fields'] );
			} else {
				$fields = $assoc_args['fields'];
			}
		} else {
			$fields = $this->obj_fields;
		}
		return new Formatter( $assoc_args, $fields, $this->obj_type );
	}

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:
Convert a differential map to an integral map

        Here we are using log-log-quadrature to compute the integral quantities.

def _differential_to_integral(hpx_map):

        ebins = hpx_map.hpx.ebins
        ratio = ebins[1:] / ebins[0:-1]
        half_log_ratio = np.log(ratio) / 2.
        int_map = ((hpx_map.data[0:-1].T * ebins[0:-1]) +
                   (hpx_map.data[1:].T * ebins[1:])) * half_log_ratio
        return HpxMap(int_map.T, hpx_map.hpx)

def definition
      {
        method_logical_id => {
          type: "AWS::ApiGateway::Method",
          properties: {
            resource_id: "!Ref #{resource_id}",
            rest_api_id: "!Ref #{RestApi.logical_id}",
            http_method: @route.method,
            request_parameters: {},
            authorization_type: authorization_type,
            integration: {
              integration_http_method: "POST",
              type: "AWS_PROXY",
              uri: "!Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${{namespace}LambdaFunction.Arn}/invocations"
            },
            method_responses: []
          }
        }
      }
    end

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


Question: // SetPlayReadyDrm sets the PlayReadyDrm field's value.

func (s *CreateJobPlaylist) SetPlayReadyDrm(v *PlayReadyDrm) *CreateJobPlaylist {
	s.PlayReadyDrm = v
	return s
}

def setup_hook(config):
    """"""
    metadata = config['metadata']
    if sys.platform == 'win32':
        requires = metadata.get('requires_dist', '').split('\n')
        metadata['requires_dist'] = "\n".join(requires)
    config['metadata'] = metadata

    metadata['version'] = str(version)

    # pbr's setup_hook replaces easy_install.get_script_args with
    # their own version, override_get_script_args, prefering simpler
    # scripts which are not aware of multi-version.
    # prevent that by doing the opposite.  it's a horrible hack
    # but we are in patching wars already...
    from pbr import packaging

    def my_get_script_args(*args, **kwargs):
        return _main_module()._orig_get_script_args(*args, **kwargs)

    packaging.override_get_script_args = my_get_script_args
    easy_install.get_script_args = my_get_script_args

    # another hack to allow setup from tarball.
    orig_get_version = packaging.get_version

    def my_get_version(package_name, pre_version=None):
        if package_name == 'ryu':
            return str(version)
        return orig_get_version(package_name, pre_version)

    packaging.get_version = my_get_version

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


Question:
Returns a lost of dicts with the analysis request templates infomration
        [{'uid':'xxxx','id':'xxxx','title':'xxx','url':'xxx'}, ...]

def getAnalysisRequestTemplatesInfo(self):

        arts_list = []
        for art in self.context.ar_templates:
            pc = getToolByName(self.context, 'portal_catalog')
            contentFilter = {'portal_type': 'ARTemplate',
                             'UID': art}
            art_brain = pc(contentFilter)
            if len(art_brain) == 1:
                art_obj = art_brain[0].getObject()
                arts_list.append({
                    'uid': art_obj.UID(),
                    'id': art_obj.id,
                    'title': art_obj.title,
                    'url': art_obj.absolute_url(),
                })
        return arts_list

def _validate_id_types(self):
        ''''''

        for sequences in [self.uniparc_sequences, self.fasta_sequences, self.seqres_sequences, self.rosetta_sequences]:
            for chain_id, sequence in sequences.iteritems():
                sequence_id_types = set(map(type, sequence.ids()))
                if sequence_id_types:
                    assert(len(sequence_id_types) == 1)
                    assert(sequence_id_types.pop() == types.IntType)

        for chain_id, sequence in self.atom_sequences.iteritems():
            sequence_id_types = set(map(type, sequence.ids()))
            assert(len(sequence_id_types) == 1)
            sequence_id_type = sequence_id_types.pop()
            assert(sequence_id_type == types.StringType or sequence_id_type == types.UnicodeType)

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