Question: Return a list of Violations recorded in `src_path`.

def violations(self, src_path):

        if not any(src_path.endswith(ext) for ext in self.driver.supported_extensions):
            return []
        if src_path not in self.violations_dict:
            if self.reports:
                self.violations_dict = self.driver.parse_reports(self.reports)
            else:
                if self.driver_tool_installed is None:
                    self.driver_tool_installed = self.driver.installed()
                if not self.driver_tool_installed:
                    raise EnvironmentError("{} is not installed".format(self.driver.name))
                command = copy.deepcopy(self.driver.command)
                if self.options:
                    command.append(self.options)
                if os.path.exists(src_path):
                    command.append(src_path.encode(sys.getfilesystemencoding()))
                    output, _ = execute(command, self.driver.exit_codes)
                    self.violations_dict.update(self.driver.parse_reports([output]))

        return self.violations_dict[src_path]

public function rewind()
    {
        $uri = $this->xmlFileUri;

        if ($this->options["utf8Filter"]) {
            $uri = "php://filter/read=xmlutf8/resource=" . $uri;
        }

        if (!$this->reader
            ->open(
                $uri,
                $this->options["encoding"],
                $this->options["readerOptions"]
            )
        ) {
            throw new \Exception("$this->xmlFileUri cannot be opened");
        }

        // move to the first element
        while ($this->reader->read() && $this->reader->name !== $this->delimiterTagName) {
            // intentionally empty
        }
    }

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


Question:
// CamelCaseAttributesEqual returns true if the two options are equal.
// In case of one option being nil, the value of the other must be nil as well
// or be set to the default value of this option.

func CamelCaseAttributesEqual(o1, o2 *CamelCaseAttributesOption) bool {
	if o1 != nil {
		return o1.Equal(o2)
	}
	if o2 != nil {
		return o2.Equal(o1)
	}
	return true
}

public function create(string $className, string $typeName): Type
    {
        $type = new InputObjectType([
            'name' => $typeName,
            'fields' => function () use ($className, $typeName): array {
                $fieldsEnum = new EnumType([
                    'name' => $typeName . 'Field',
                    'values' => $this->getPossibleValues($className),
                    'description' => 'Fields available for `' . $typeName . '`',
                ]);
                $this->types->registerInstance($fieldsEnum);

                return [
                    [
                        'name' => 'field',
                        'type' => Type::nonNull($fieldsEnum),
                    ],
                    [
                        'name' => 'nullAsHighest',
                        'type' => Type::boolean(),
                        'description' => 'If true `NULL` values will be considered as the highest value, so appearing last in a `ASC` order, and first in a `DESC` order.',
                        'defaultValue' => false,
                    ],
                    [
                        'name' => 'order',
                        'type' => $this->types->get('SortingOrder'),
                        'defaultValue' => 'ASC',
                    ],
                ];
            },
        ]);

        return $type;
    }

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


Question: // Hostname reads HOSTNAME env var or os.Hostname used for your app

func Hostname() string {
	hostname := os.Getenv("HOSTNAME")
	if len(hostname) > 0 {
		return hostname
	}
	hostname, err := os.Hostname()
	if err == nil {
		return hostname
	}
	return "localhost"
}

func (f *Function) loadConfig(environment string) error {
	path := fmt.Sprintf("function.%s.json", environment)

	ok, err := f.tryConfig(path)
	if err != nil {
		return err
	}

	if ok {
		f.Log.WithField("config", path).Debug("loaded config")
		return nil
	}

	ok, err = f.tryConfig("function.json")
	if err != nil {
		return err
	}

	if ok {
		f.Log.WithField("config", "function.json").Debug("loaded config")
		return nil
	}

	return nil
}

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


Question:
// MakeJSONFileLogger creates an un-configured JSON logger that writes
// output to the specified file.

func MakeJSONFileLogger(file string) (Sender, error) {
	s, err := MakePlainFileLogger(file)
	if err != nil {
		return nil, err
	}

	if err = s.SetFormatter(MakeJSONFormatter()); err != nil {
		return nil, err
	}

	return s, nil
}

def Stop():

    if global_options.loglevel >= 1 and global_benchmark:
        t = time.time() - global_starting_time
        global_options.stdlog.write(
            "######### Time spent in benchmarked functions #########\n")
        global_options.stdlog.write("# function\tseconds\tpercent\n")
        for key, value in global_benchmark.items():
            global_options.stdlog.write(
                "# %s\t%6i\t%5.2f%%\n" % (key, value,
                                          (100.0 * float(value) / t)))
        global_options.stdlog.write(
            "#######################################################\n")

    if global_options.loglevel >= 1:
        global_options.stdlog.write(getFooter() + "\n")

    # close files
    if global_options.stdout != sys.stdout:
        global_options.stdout.close()
    # do not close log, otherwise error occurs in atext.py
    # if global_options.stdlog != sys.stdout:
    #   global_options.stdlog.close()

    if global_options.stderr != sys.stderr:
        global_options.stderr.close()

    if global_options.timeit_file:

        outfile = open(global_options.timeit_file, "a")

        if global_options.timeit_header:
            outfile.write("\t".join(
                ("name", "wall", "user", "sys", "cuser", "csys",
                 "host", "system", "release", "machine",
                 "start", "end", "path", "cmd")) + "\n")

        csystem, host, release, version, machine = map(str, os.uname())
        uusr, usys, c_usr, c_sys = map(lambda x: "%5.2f" % x, os.times()[:4])
        t_end = time.time()
        c_wall = "%5.2f" % (t_end - global_starting_time)

        if sys.argv[0] == "run.py":
            cmd = global_args[0]
            if len(global_args) > 1:
                cmd += " '" + "' '".join(global_args[1:]) + "'"
        else:
            cmd = sys.argv[0]

        result = "\t".join((global_options.timeit_name,
                            c_wall, uusr, usys, c_usr, c_sys,
                            host, csystem, release, machine,
                            time.asctime(time.localtime(global_starting_time)),
                            time.asctime(time.localtime(t_end)),
                            os.path.abspath(os.getcwd()),
                            cmd)) + "\n"

        outfile.write(result)
        outfile.close()

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


Question: //Gather collects kubernetes metrics from a given URL

func (k *Kubernetes) Gather(acc telegraf.Accumulator) error {
	acc.AddError(k.gatherSummary(k.URL, acc))
	return nil
}

func (l *gcsGateway) GetBucketInfo(ctx context.Context, bucket string) (minio.BucketInfo, error) {
	attrs, err := l.client.Bucket(bucket).Attrs(ctx)
	if err != nil {
		logger.LogIf(ctx, err)
		return minio.BucketInfo{}, gcsToObjectError(err, bucket)
	}

	return minio.BucketInfo{
		Name:    attrs.Name,
		Created: attrs.Created,
	}, nil
}

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


Question:
Create a new server request

@param      string                  $method
@param      UriInterface|string     $uri
@param      array                   $serverParams  The server parameters

@return     ServerRequestInterface

public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
  {
    # Copied from Guzzles ::fromGlobals(), but we need to support the $server array as
    # paramter, so we use that instead of the $_SERVER array guzzle uses by default

    $method = isset($server['REQUEST_METHOD']) ? $server['REQUEST_METHOD'] : 'GET';
    $headers = \function_exists('getallheaders') ? \getallheaders() : [];
    $uri = $uri;
    $body = new LazyOpenStream('php://input', 'r+');
    $protocol = isset($server['SERVER_PROTOCOL']) ? \str_replace('HTTP/', '', $server['SERVER_PROTOCOL']) : '1.1';

    $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $server);

    \logger()->debug('Created PSR-7 ServerRequest("'.$method.'","'.$url.'") (Guzzle)');

    return $serverRequest
        ->withCookieParams($_COOKIE)
        ->withQueryParams($_GET)
        ->withParsedBody($_POST)
        ->withUploadedFiles(ServerRequest::normalizeFiles($_FILES));
  }

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

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


Question:
Retrieve the escapeHtml helper

@return EscapeHtml

protected function getEscapeHtmlHelper()
    {
        if ($this->escapeHtmlHelper) {
            return $this->escapeHtmlHelper;
        }

        if (method_exists($this->view, 'plugin')) {
            $this->escapeHtmlHelper = $this->view->plugin('escapehtml');
        }

        if (!$this->escapeHtmlHelper instanceof EscapeHtml) {
            $this->escapeHtmlHelper = new EscapeHtml();
            $this->escapeHtmlHelper->setView($this->getView());
        }

        return $this->escapeHtmlHelper;
    }

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

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


Question:
Provides a display text for the constant values of the {@link Node} class that represent node types.

@param type the node type
@return the display text

@since XMLUnit 2.4.0

protected String nodeType(short type) {
        switch(type) {
        case Node.ELEMENT_NODE:                return "Element";
        case Node.DOCUMENT_TYPE_NODE:          return "Document Type";
        case Node.ENTITY_NODE:                 return "Entity";
        case Node.ENTITY_REFERENCE_NODE:       return "Entity Reference";
        case Node.NOTATION_NODE:               return "Notation";
        case Node.TEXT_NODE:                   return "Text";
        case Node.COMMENT_NODE:                return "Comment";
        case Node.CDATA_SECTION_NODE:          return "CDATA Section";
        case Node.ATTRIBUTE_NODE:              return "Attribute";
        case Node.PROCESSING_INSTRUCTION_NODE: return "Processing Instruction";
        default: break;
        }
        return Short.toString(type);
    }

protected function getFormatter(ModelInterface $model, $treeMode)
    {
        /** @var ListingConfigInterface $listing */
        $definition = $this->getEnvironment()->getDataDefinition();
        $listing    = $definition->getDefinition(Contao2BackendViewDefinitionInterface::NAME)->getListingConfig();

        if ($listing->hasLabelFormatter($model->getProviderName())) {
            return $listing->getLabelFormatter($model->getProviderName());
        }

        // If not in tree mode and custom label has been defined, use it.
        if (!$treeMode && $this->itemLabel) {
            $label     = (array) $this->itemLabel;
            $formatter = new DefaultModelFormatterConfig();
            $formatter->setPropertyNames($label['fields']);
            $formatter->setFormat($label['format']);
            $formatter->setMaxLength($label['maxCharacters']);
            return $formatter;
        }

        // If no label has been defined, use some default.
        $properties = [];
        foreach ($definition->getPropertiesDefinition()->getProperties() as $property) {
            if ('text' === $property->getWidgetType()) {
                $properties[] = $property->getName();
            }
        }

        return (new DefaultModelFormatterConfig())
            ->setPropertyNames($properties)
            ->setFormat(\str_repeat('%s ', \count($properties)));
    }

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


Question:
Returns the listener object for the given class.

@param listenerClass
the listener class
@return the listener object for the given type

public Object getListener(Class<?> listenerClass) {
    Object listener = listeners.get(listenerClass);
    if (listener == null) {
      listener = loadListener(listenerClass);
    }
    return listener;
  }

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

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


Question:
Migrate up

@return void

public function up()
    {
        if ($this->hasTable('users_groups')) {
            return;
        }

        $table = $this->table('users_groups');
        $table->addColumn('user_id', 'integer', ['limit' => 11, 'signed' => false, 'null' => false])
            ->addColumn('group_id', 'integer', ['limit' => 11, 'signed' => false, 'null' => false]);
        $table->addIndex('user_id', ['name' => 'FK_USER_ID', 'unique' => false])
            ->addIndex('group_id', ['name' => 'FK_GROUP_ID', 'unique' => false]);
        $table->create();

        $this->unsignedIntId($table);
        $table->save();

        $UsersGroups = \Cake\ORM\TableRegistry::get('UsersGroups');
        $UsersGroups->save($UsersGroups->newEntity([
            'user_id' => 1,
            'group_id' => 1
        ]));
    }

func Convert_apps_ControllerRevision_To_v1_ControllerRevision(in *apps.ControllerRevision, out *v1.ControllerRevision, s conversion.Scope) error {
	return autoConvert_apps_ControllerRevision_To_v1_ControllerRevision(in, out, s)
}

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


Question:
// Next allows to paginate after calling:
// Account.Follow* and User.Follow*
//
// New user list is stored inside Users
//
// returns false when list reach the end.

func (users *Users) Next() bool {
	if users.err != nil {
		return false
	}

	insta := users.inst
	endpoint := users.endpoint

	body, err := insta.sendRequest(
		&reqOptions{
			Endpoint: endpoint,
			Query: map[string]string{
				"max_id":             users.NextID,
				"ig_sig_key_version": goInstaSigKeyVersion,
				"rank_token":         insta.rankToken,
			},
		},
	)
	if err == nil {
		usrs := Users{}
		err = json.Unmarshal(body, &usrs)
		if err == nil {
			*users = usrs
			if !usrs.BigList || usrs.NextID == "" {
				users.err = ErrNoMore
			}
			users.inst = insta
			users.endpoint = endpoint
			users.setValues()
			return true
		}
	}
	users.err = err
	return false
}

protected function getPagesBlog()
    {
        $conditions = $this->query_filter;

        $conditions['status'] = 1;
        $conditions['blog_post'] = 1;
        $conditions['limit'] = $this->data_limit;
        $conditions['store_id'] = $this->store_id;

        $list = (array) $this->page->getList($conditions);
        $this->preparePagesBlog($list);
        return $list;
    }

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


Question: Marshall the given parameter object.

public void marshall(AbortMultipartUploadRequest abortMultipartUploadRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(abortMultipartUploadRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getVaultName(), VAULTNAME_BINDING);
            protocolMarshaller.marshall(abortMultipartUploadRequest.getUploadId(), UPLOADID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
// Info outputs device information (see "dmsetup info").
// If device name is empty, all device infos will be returned.

func Info(deviceName string) ([]*DeviceInfo, error) {
	output, err := dmsetup(
		"info",
		"--columns",
		"--noheadings",
		"-o",
		"name,blkdevname,attr,major,minor,open,segments,events",
		"--separator",
		" ",
		deviceName)

	if err != nil {
		return nil, err
	}

	var (
		lines   = strings.Split(output, "\n")
		devices = make([]*DeviceInfo, len(lines))
	)

	for i, line := range lines {
		var (
			attr = ""
			info = &DeviceInfo{}
		)

		_, err := fmt.Sscan(line,
			&info.Name,
			&info.BlockDeviceName,
			&attr,
			&info.Major,
			&info.Minor,
			&info.OpenCount,
			&info.TargetCount,
			&info.EventNumber)

		if err != nil {
			return nil, errors.Wrapf(err, "failed to parse line %q", line)
		}

		// Parse attributes (see "man 8 dmsetup" for details)
		info.Suspended = strings.Contains(attr, "s")
		info.ReadOnly = strings.Contains(attr, "r")
		info.TableLive = strings.Contains(attr, "L")
		info.TableInactive = strings.Contains(attr, "I")

		devices[i] = info
	}

	return devices, nil
}

private function displayVarietyDescription(VarietyDescriptionEntity $varietyDescription, $displayLabel = false): string
    {
        $this->initFieldDescription($varietyDescription);

        if ($displayLabel) {
            $help = $this->translator->trans('librinfo.help.' . $varietyDescription->getField(), [], 'messages');
            $label = $this->translator->trans('librinfo_description_' . $this->varietyDescription->getFieldset() . '_' . $varietyDescription->getField(), [], 'messages');

            if ($help != ' ') {
                $label .= ' <small>(' . $help . ')</small>';
            }

            return $label;
        } else {
            return $this->handleValueWidget();
        }
    }

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


Question: xarray version of pandas.core.nanops._maybe_null_out

def _maybe_null_out(result, axis, mask, min_count=1):

    if hasattr(axis, '__len__'):  # if tuple or list
        raise ValueError('min_count is not available for reduction '
                         'with more than one dimensions.')

    if axis is not None and getattr(result, 'ndim', False):
        null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0
        if null_mask.any():
            dtype, fill_value = dtypes.maybe_promote(result.dtype)
            result = result.astype(dtype)
            result[null_mask] = fill_value

    elif getattr(result, 'dtype', None) not in dtypes.NAT_TYPES:
        null_mask = mask.size - mask.sum()
        if null_mask < min_count:
            result = np.nan

    return result

func onPhaseImplementation(sctx sessionctx.Context, g *memo.Group) (plannercore.Plan, error) {
	prop := &property.PhysicalProperty{
		ExpectedCnt: math.MaxFloat64,
	}
	// TODO replace MaxFloat64 costLimit by variable from sctx, or other sources.
	impl, err := implGroup(g, prop, math.MaxFloat64)
	if err != nil {
		return nil, err
	}
	if impl == nil {
		return nil, plannercore.ErrInternal.GenWithStackByArgs("Can't find a proper physical plan for this query")
	}
	return impl.GetPlan(), nil
}

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


Question:
Converts binary string into decimal string.

@param string $bin    Binary string.
@param int    $length Minimum output length.

@return string Decimal string.

public static function binToDec($bin, $length = 0)
    {
        $gmp = gmp_init($bin, 2);
        $dec = gmp_strval($gmp, 10);

        return self::pad($dec, $length);
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question: // NewQueryCreator provides a mock function with given fields: channel

func (_m *ChannelStateRetriever) NewQueryCreator(channel string) (endorser.QueryCreator, error) {
	ret := _m.Called(channel)

	var r0 endorser.QueryCreator
	if rf, ok := ret.Get(0).(func(string) endorser.QueryCreator); ok {
		r0 = rf(channel)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(endorser.QueryCreator)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(channel)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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

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

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

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


Question:
Converts a DateTime object to a string (ISO 8601)

@param  string|DateTime $date The date (string or DateTime)
@return string

protected function convertDate($date) : string
    {
        if (is_a($date, 'DateTime')) {
            return (string) $date->format(DateTime::ISO8601);
        }

        return $date;
    }

func parseMonthly(monthlyStr string) (RetainIntervalSpec, error) {
	r, monthly, err := parseRetainNumber(monthlyStr)
	if err != nil {
		return r, err
	}
	if monthly == "" {
		return r, fmt.Errorf("Monthly schedule is missing")
	}
	dt := strings.Split(monthly, "@")
	if len(dt) == 1 {
		dt = append(dt, "0:0")
	}
	if len(dt) != 2 {
		return RetainIntervalSpec{},
			fmt.Errorf("Invalid monthly spec %v", monthlyStr)
	}
	d, err := strconv.Atoi(dt[0])
	if err != nil || d < 0 || d > 31 {
		return RetainIntervalSpec{},
			fmt.Errorf("Invalid day of month %v", dt[0])
	}
	h, m, err := timeOfDay(dt[1])
	if err != nil {
		return RetainIntervalSpec{}, err
	}
	r.IntervalSpec = Monthly(d, h, m).Spec()
	return r, nil
}

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


Question:
Gets attributes.

@param attributes the attributes
@param context    the context
@return the attributes

public static Map<String, Object> getRequestParameters(final Collection<String> attributes, final HttpServletRequest context) {
        return attributes.stream()
            .filter(a -> StringUtils.isNotBlank(context.getParameter(a)))
            .map(m -> {
                val values = context.getParameterValues(m);
                val valuesSet = new LinkedHashSet<Object>();
                if (values != null && values.length > 0) {
                    Arrays.stream(values).forEach(v -> valuesSet.addAll(Arrays.stream(v.split(" ")).collect(Collectors.toSet())));
                }
                return Pair.of(m, valuesSet);
            })
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }

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: // TmplPath 生成模板路径 args: ActionName,ControllerName,ModuleName

func (c *Context) TmplPath(args ...string) string {
	var mod, ctl, act = c.Module.Name, c.ControllerName, c.ActionName
	switch len(args) {
	case 3:
		mod = args[2]
		fallthrough
	case 2:
		ctl = args[1]
		fallthrough
	case 1:
		act = args[0]
	}
	return mod + `/` + ctl + `/` + act
}

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question: Depending on whether the user said "yes" or "no", send him to the right place.

@RequirePOST
    public HttpResponse doAct(@QueryParameter String no) throws IOException {
        if(no!=null) {
            disable(true);
            return HttpResponses.redirectViaContextPath("/manage");
        } else {
            return HttpResponses.redirectToDot();
        }
    }

protected int _nextsib(int identity)
  {
    // Boiler-plate code for each of the _xxx functions, except for the array.
    int info = (identity >= m_size) ? NOTPROCESSED : m_nextsib.elementAt(identity);

    // Check to see if the information requested has been processed, and,
    // if not, advance the iterator until we the information has been
    // processed.
    while (info == NOTPROCESSED)
    {
      boolean isMore = nextNode();

      if (identity >= m_size &&!isMore)
        return NULL;
      else
      {
        info = m_nextsib.elementAt(identity);
        if(info == NOTPROCESSED && !isMore)
          return NULL;
      }
    }

    return info;
  }

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


Question:
update the quota for the given path

@param path
the path to be used

private void updateQuotaForPath(String path) {
        Counts c = new Counts();
        getCounts(path, c);
        StatsTrack strack = new StatsTrack();
        strack.setBytes(c.bytes);
        strack.setCount(c.count);
        String statPath = Quotas.quotaZookeeper + path + "/" + Quotas.statNode;
        DataNode node = getNode(statPath);
        // it should exist
        if (node == null) {
            LOG.warn("Missing quota stat node " + statPath);
            return;
        }
        synchronized (node) {
            node.data = strack.toString().getBytes();
        }
    }

func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {

	// NOTE: Avatar must be either the hash/id of existing Avatar or
	// data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
	// to set a new avatar.
	// If left blank, avatar will be set to null/blank

	data := struct {
		Email       string `json:"email,omitempty"`
		Password    string `json:"password,omitempty"`
		Username    string `json:"username,omitempty"`
		Avatar      string `json:"avatar,omitempty"`
		NewPassword string `json:"new_password,omitempty"`
	}{email, password, username, avatar, newPassword}

	body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
	if err != nil {
		return
	}

	err = unmarshal(body, &st)
	return
}

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


Question:
Sets the padTop, padLeft, padBottom, and padRight around the table to the
specified value.

public BaseTableLayout<C, T> pad(float pad) {
        padTop = new FixedValue<C, T>(toolkit, pad);
        padLeft = new FixedValue<C, T>(toolkit, pad);
        padBottom = new FixedValue<C, T>(toolkit, pad);
        padRight = new FixedValue<C, T>(toolkit, pad);
        sizeInvalid = true;
        return this;
    }

@Override
  public int setPageID(P page) {
    int pageID = page.getPageID();
    if(pageID == -1) {
      pageID = getNextEmptyPageID();
      if(pageID == -1) {
        pageID = nextPageID++;
      }
      page.setPageID(pageID);
    }
    return pageID;
  }

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


Question:
Sort the list of recorded super block starts and remove duplicates.

Also adds exception handling blocks as block starts, since there is no explicit control flow to
these. Used for stack map table generation.

private void finalizeSuperBlockStarts() {
        if (GenerateStackMap) {
            for (int i = 0; i < itsExceptionTableTop; i++) {
                ExceptionTableEntry ete = itsExceptionTable[i];
                int handlerPC = getLabelPC(ete.itsHandlerLabel);
                addSuperBlockStart(handlerPC);
            }
            Arrays.sort(itsSuperBlockStarts, 0, itsSuperBlockStartsTop);
            int prev = itsSuperBlockStarts[0];
            int copyTo = 1;
            for (int i = 1; i < itsSuperBlockStartsTop; i++) {
                int curr = itsSuperBlockStarts[i];
                if (prev != curr) {
                    if (copyTo != i) {
                        itsSuperBlockStarts[copyTo] = curr;
                    }
                    copyTo++;
                    prev = curr;
                }
            }
            itsSuperBlockStartsTop = copyTo;
            if (itsSuperBlockStarts[copyTo - 1] == itsCodeBufferTop) {
                itsSuperBlockStartsTop--;
            }
        }
    }

def _handle_forward_execution_after_child_execution(self):

        self.add_state_execution_output_to_scoped_data(self.child_state.output_data, self.child_state)
        self.update_scoped_variables_with_output_dictionary(self.child_state.output_data, self.child_state)
        self.execution_history.push_return_history_item(
            self.child_state, CallType.EXECUTE, self, self.child_state.output_data)
        # not explicitly connected preempted outcomes are implicit connected to parent preempted outcome
        transition = self.get_transition_for_outcome(self.child_state, self.child_state.final_outcome)

        if transition is None:
            transition = self.handle_no_transition(self.child_state)
        # if the transition is still None, then the child_state was preempted or aborted, in this case
        # return
        if transition is None:
            return True

        self.last_transition = transition
        self.child_state = self.get_state_for_transition(transition)
        if transition is not None and self.child_state is self:
            self.final_outcome = self.outcomes[transition.to_outcome]

        if self.child_state is self:
            singleton.state_machine_execution_engine._modify_run_to_states(self)
        return False

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


Question:
Helper to extract a ClassResources full path.

ie: package.MyClass = package/MyClass.class

@param className
@return

public static ArchivePath getFullPathForClassResource(String className) {
        String classResourceDelimiter = className.replaceAll(DELIMITER_CLASS_NAME_PATH, DELIMITER_RESOURCE_PATH);
        String classFullPath = classResourceDelimiter + EXTENSION_CLASS;
        return new BasicPath(classFullPath);
    }

public String exportToHtml(String filePath, String fileName) {
        return OptionUtil.exportToHtml(this, filePath, fileName);
    }

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


Question: User Operation Logs ///////////////////////////

public List<HistoryEvent> createUserOperationLogEvents(UserOperationLogContext context) {
    List<HistoryEvent> historyEvents = new ArrayList<HistoryEvent>();

    String operationId = Context.getCommandContext().getOperationId();
    context.setOperationId(operationId);

    for (UserOperationLogContextEntry entry : context.getEntries()) {
      for (PropertyChange propertyChange : entry.getPropertyChanges()) {
        UserOperationLogEntryEventEntity evt = new UserOperationLogEntryEventEntity();

        initUserOperationLogEvent(evt, context, entry, propertyChange);

        historyEvents.add(evt);
      }
    }

    return historyEvents;
  }

public static void main(String[] args) throws Throwable {
		CliArguments arguments = CliArguments.parse(args);
		if (arguments.isSet() && !arguments.isUsageMode()) {
			CliRunner runner = new CliRunner(arguments);
			try {
				runner.run();
			} finally {
				runner.close();
			}
		} else {
			PrintWriter out = new PrintWriter(System.out);
			printUsage(out);
			FileHelper.safeClose(out);
		}
	}

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


Question:
Returns a JSON response.

@param mixed $data   The data to encode, or a valid JSON string if `$encode` == `false`.
@param bool  $encode Whether to JSON-encode the data.

@return \Brick\Http\Response

protected function json($data, bool $encode = true) : Response
    {
        if ($encode) {
            $data = json_encode($data);
        }

        return $this->createResponse($data, 'application/json');
    }

func ResponseMapper() MiddlewareFunc {
	return func(b *Bubble) error {
		err := b.Next()

		// first, error handling
		if err != nil {
			return b.writeErrorObject(err)
		}

		// second, error from handlers
		for idx := len(b.Returns) - 1; 0 <= idx; idx-- {
			rv := b.Returns[idx]
			if rv.Type().AssignableTo(errorType) && !rv.IsNil() {
				err := rv.Interface().(error)
				return b.writeErrorObject(err)
			}
		}

		// last, write payload
		for _, rv := range b.Returns {
			if rv.Type().AssignableTo(errorType) {
				continue
			}

			v := rv.Interface()
			if m, ok := v.(HTTPResponseModifier); ok {
				return m.Handle(b)
			} else if !rv.IsNil() {
				var resp []byte
				var err error
				if b.Debug {
					resp, err = json.MarshalIndent(v, "", "  ")
				} else {
					resp, err = json.Marshal(v)
				}
				if err != nil {
					http.Error(b.W, err.Error(), http.StatusInternalServerError)
					return err
				}
				b.W.Header().Set("Content-Type", "application/json; charset=UTF-8")
				b.W.WriteHeader(http.StatusOK)
				b.W.Write(resp)
				return nil
			} else {
				b.W.Header().Set("Content-Type", "application/json; charset=UTF-8")
				b.W.WriteHeader(http.StatusOK)
				if rv.Type().Kind() == reflect.Slice {
					b.W.Write([]byte("[]"))
				} else {
					b.W.Write([]byte("{}"))
				}
				return nil
			}
		}

		return nil
	}
}

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


Question:
Set Button Title.

@param $title

@throws CouldNotCreateCard
@return $this

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

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

        return $this;
    }

def create_resource(self, url, data):

        status_code, json_data = self.send_request(url, data, method='POST')

        if status_code != 201:
            msg = 'Expected 201 status code, got %s. Failed to create resource.'
            raise TagCubeAPIException(msg % status_code)

        try:
            return Resource(json_data)
        except KeyError:
            # Parse the error and raise an exception, errors look like:
            # {u'error': [u'The domain foo.com already exists.']}
            error_string = u' '.join(json_data['error'])
            raise TagCubeAPIException(error_string)

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


Question:
This remove method is most efficient when the element being removed
is the last element.  Equality is identity based, not equals() based.
Only the first matching element is removed.

@param element the element to remove

@Override
   public boolean remove(Object element)
   {
      for (int index = size - 1; index >= 0; index--) {
         if (element == elementData[index]) {
            final int numMoved = size - index - 1;
            if (numMoved > 0) {
               System.arraycopy(elementData, index + 1, elementData, index, numMoved);
            }
            elementData[--size] = null;
            return true;
         }
      }

      return false;
   }

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

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


Question: // prefixedInstances returns instances with the specified prefix.

func (env *environ) prefixedInstances(prefix string) ([]*environInstance, error) {
	containers, err := env.server().AliveContainers(prefix)
	err = errors.Trace(err)

	// Turn lxd.Container values into *environInstance values,
	// whether or not we got an error.
	var results []*environInstance
	for _, c := range containers {
		c := c
		inst := newInstance(&c, env)
		results = append(results, inst)
	}
	return results, err
}

func Render(typ Type, input interface{}, urlPrefix string, metas map[string]string) []byte {
	var rawBytes []byte
	switch v := input.(type) {
	case []byte:
		rawBytes = v
	case string:
		rawBytes = []byte(v)
	default:
		panic(fmt.Sprintf("unrecognized input content type: %T", input))
	}

	urlPrefix = strings.TrimRight(strings.Replace(urlPrefix, " ", "%20", -1), "/")
	var rawHTML []byte
	switch typ {
	case MARKDOWN:
		rawHTML = RawMarkdown(rawBytes, urlPrefix)
	case ORG_MODE:
		rawHTML = RawOrgMode(rawBytes, urlPrefix)
	default:
		return rawBytes // Do nothing if syntax type is not recognized
	}

	rawHTML = postProcessHTML(rawHTML, urlPrefix, metas)
	return SanitizeBytes(rawHTML)
}

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


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

public EClass getIfcOrganization() {
		if (ifcOrganizationEClass == null) {
			ifcOrganizationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(339);
		}
		return ifcOrganizationEClass;
	}

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:
Wraps super().get(...) in order to return 404 status code if
        the page parameter is invalid

def get(self, request, *args, **kwargs):

        response = super().get(request, args, kwargs)
        try:
            response.render()
        except Http404:
            request.GET = request.GET.copy()
            request.GET['page'] = '1'
            response = super().get(request, args, kwargs)
            response.status_code = 404

        return response

def callback(self, ch, method, properties, body):

        index = method.routing_key.split('.')[1]
        index = index.replace('/', '-')
        failed = False
        body = str(body)
        try:
            doc = json.loads(body)
        except Exception as e:  # pragma: no cover
            try:
                body = body.strip().replace('"', '\"')
                body = '{"log":"' + body + '"}'
                doc = json.loads(body)
            except Exception as e:  # pragma: no cover
                failed = True

        if not failed:
            try:
                self.es_conn.index(index=index,
                                   doc_type=method.routing_key.split('.')[1],
                                   id=method.routing_key + '.' +
                                   str(uuid.uuid4()),
                                   body=doc)
            except Exception as e:  # pragma: no cover
                print('Failed to send document to elasticsearch because: ' + str(e))

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


Question: Recursively attempts to join the cluster.

private void join(Iterator<MemberState> iterator) {
    if (iterator.hasNext()) {
      cancelJoinTimer();
      joinTimeout = context.getThreadContext().schedule(context.getElectionTimeout().multipliedBy(2), () -> {
        join(iterator);
      });

      MemberState member = iterator.next();
      LOGGER.debug("{} - Attempting to join via {}", member().address(), member.getMember().serverAddress());

      context.getConnections().getConnection(member.getMember().serverAddress()).thenCompose(connection -> {
        JoinRequest request = JoinRequest.builder()
          .withMember(new ServerMember(member().type(), member().serverAddress(), member().clientAddress(), member().updated()))
          .build();
        return connection.<JoinRequest, JoinResponse>sendAndReceive(request);
      }).whenComplete((response, error) -> {
        // Cancel the join timer.
        cancelJoinTimer();

        if (error == null) {
          if (response.status() == Response.Status.OK) {
            LOGGER.info("{} - Successfully joined via {}", member().address(), member.getMember().serverAddress());

            Configuration configuration = new Configuration(response.index(), response.term(), response.timestamp(), response.members());

            // Configure the cluster with the join response.
            // Commit the configuration as we know it was committed via the successful join response.
            configure(configuration).commit();

            // If the local member is not present in the configuration, fail the future.
            if (!members.contains(this.member)) {
              joinFuture.completeExceptionally(new IllegalStateException("not a member of the cluster"));
            } else if (joinFuture != null) {
              joinFuture.complete(null);
            }
          } else if (response.error() == null || response.error() == CopycatError.Type.CONFIGURATION_ERROR) {
            // If the response error is null, that indicates that no error occurred but the leader was
            // in a state that was incapable of handling the join request. Attempt to join the leader
            // again after an election timeout.
            LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
            resetJoinTimer();
          } else {
            // If the response error was non-null, attempt to join via the next server in the members list.
            LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
            join(iterator);
          }
        } else {
          LOGGER.debug("{} - Failed to join {}", member().address(), member.getMember().address());
          join(iterator);
        }
      });
    }
    // If join attempts remain, schedule another attempt after two election timeouts. This allows enough time
    // for servers to potentially timeout and elect a leader.
    else {
      LOGGER.debug("{} - Failed to join cluster, retrying...", member.address());
      resetJoinTimer();
    }
  }

protected function createRedisClusterInstance(array $servers, array $options)
    {
        return new RedisCluster(
            null,
            array_values($servers),
            $options['timeout'] ?? 0,
            $options['read_timeout'] ?? 0,
            isset($options['persistent']) && $options['persistent']
        );
    }

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


Question:
Function setNormalName

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 10/22/18 21:03

@param bool $value

@return bool

public function setNormalName($value = FALSE)
    {
        $this->normal_name = $value;
        $this->debug->info(__FUNCTION__, 'setNormalName: ' . json_encode($value));

        return $this->normal_name;
    }

func (u *Userinfo) Password() (string, bool) {
	if u.passwordSet {
		return u.password, true
	}
	return "", false
}

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


Question: Load all bookmarks but those from a specific file.

def load_bookmarks_without_file(filename):
    """"""
    bookmarks = _load_all_bookmarks()
    return {k: v for k, v in bookmarks.items() if v[0] != filename}

def clear_provider_links(self):

        # Implemented from template for osid.learning.ActivityForm.clear_assets_template
        if (self.get_provider_links_metadata().is_read_only() or
                self.get_provider_links_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['providerLinkIds'] = self._provider_links_default

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


Question: // SetSlateAdUrl sets the SlateAdUrl field's value.

func (s *PlaybackConfiguration) SetSlateAdUrl(v string) *PlaybackConfiguration {
	s.SlateAdUrl = &v
	return s
}

def clear_provider_links(self):

        # Implemented from template for osid.learning.ActivityForm.clear_assets_template
        if (self.get_provider_links_metadata().is_read_only() or
                self.get_provider_links_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['providerLinkIds'] = self._provider_links_default

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


Question: to start in the correct order

private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases)
        throws DockerAccessException, MojoExecutionException {
        final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>();
        for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) {
            final ImageConfiguration imageConfig = (ImageConfiguration) resolvable;

            // Still to check: How to work with linking, volumes, etc ....
            //String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry);
            RunImageConfiguration runConfig = imageConfig.getRunConfiguration();

            RegistryService.RegistryConfig registryConfig = getRegistryConfig(pullRegistry);
            ImagePullManager pullManager = getImagePullManager(determinePullPolicy(runConfig), autoPull);

            hub.getRegistryService().pullImageWithPolicy(imageConfig.getName(), pullManager, registryConfig,
                                                         queryService.hasImage(imageConfig.getName()));

            NetworkConfig config = runConfig.getNetworkingConfig();
            List<String> bindMounts = extractBindMounts(runConfig.getVolumeConfiguration());
            List<VolumeConfiguration> volumes = getVolumes();
            if(!bindMounts.isEmpty() && volumes != null) {
                runService.createVolumesAsPerVolumeBinds(hub, bindMounts, volumes);
            }
            if (autoCreateCustomNetworks && config.isCustomNetwork()) {
                runService.createCustomNetworkIfNotExistant(config.getCustomNetwork());
            }
            imagesWaitingToStart.add(imageConfig);
            updateAliasesSet(imageAliases, imageConfig.getAlias());
        }
        return imagesWaitingToStart;
    }

public function cmdGetOrder()
    {
        $result = $this->getListOrder();
        $this->outputFormat($result);
        $this->outputFormatTableOrder($result);
        $this->output();
    }

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


Question: to pubkey in hex, 32 bytes

def address_to_pubkey(addr)
      return unless addr.size == 52

      prefix = ADDRESS_PREFIX[addr[0,2]]
      return unless prefix

      v = Bitcoin.decode_base58(addr)
      return if v[0,4] != prefix

      bytes = [v[0, 68]].pack('H*')
      return if v[68, 8] != sha256d(bytes)[0, 8]

      v[4, 64]
    end

def sha1(self):

        if self._sha1 is None:
            self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
        return self._sha1

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


Question:
Apply a modification to the underlying point sources, with the
        same parameters for all sources

def modify(self, modification, parameters):

        for src in self:
            src.modify(modification, parameters)

def remove(self):

        if self._multiscat is None:
            return

        self._multiscat.deallocate(self.id)
        self._multiscat = None

        self._viewer_state.remove_global_callback(self._update_scatter)
        self.state.remove_global_callback(self._update_scatter)

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


Question:
@param entity
@param setMethod
@param value

@throws Exception 下午4:06:04 created by Darwin(Tianxin)

private void load2Entity(Object entity, Method setMethod, Object value) throws Exception {
        try {
            if (value != null) {
                setMethod.invoke(entity, value);
            }
        } catch (Exception e) {
            String sValue = value.toString();
            String sValueClass = value.getClass().toString();
            System.out.println("Error in " + setMethod.getName() + " invoke with param :" + sValue + " type is " +
                    sValueClass);
            throw e;
        }
    }

protected String argumentTypeString(final Type type) {
        if (type instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final List<String> subs = new ArrayList<>();
            for (final Type actualType : parameterizedType.getActualTypeArguments())
                subs.add(argumentTypeString(actualType));
            return argumentTypeString(((ParameterizedType) type).getRawType()) + "[" + String.join(",", subs) + "]";
        } else if (type instanceof GenericArrayType) {
            return argumentTypeString(((GenericArrayType) type).getGenericComponentType()) + "[]";
        } else if (type instanceof WildcardType) {
            throw new RuntimeException("We don't support wildcards in arguments: " + type);
        } else if (type instanceof Class<?>) {
            return ((Class) type).getSimpleName();
        } else {
            throw new DocException("Unknown type: " + type);
        }
    }

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


Question:
Here we replace a piece of data in a db block with new data

    Args:
       db (int): The db to use
       start(int): The start within the db
       size(int): The size of the data in bytes
       _butearray (enumerable): The data to put in the db

def set_db_row(db, start, size, _bytearray):

    client.db_write(db, start, size, _bytearray)

func (f *FilterStore) PutFilter(hash *chainhash.Hash,
	filter *gcs.Filter, fType FilterType) error {

	return walletdb.Update(f.db, func(tx walletdb.ReadWriteTx) error {
		filters := tx.ReadWriteBucket(filterBucket)

		var targetBucket walletdb.ReadWriteBucket
		switch fType {
		case RegularFilter:
			targetBucket = filters.NestedReadWriteBucket(regBucket)
		default:
			return fmt.Errorf("unknown filter type: %v", fType)
		}

		if filter == nil {
			return targetBucket.Put(hash[:], nil)
		}

		bytes, err := filter.NBytes()
		if err != nil {
			return err
		}

		return targetBucket.Put(hash[:], bytes)
	})
}

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


Question: /* AST helpers: treeWalk

function loc(old, repl) {
    ['start','end','loc','range'].forEach(function (k) {
        if (k in old && !(k in repl))
            repl[k] = old[k];
    });
}

final public function walk(callable $callback)
    {
        $callback($this);

        foreach ($this->getChildren() as $child) {
            $child->walk($callback);
        }
    }

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


Question:
获得模板
@param string|int $key
@return null

public function getTemplateDir($key = null)
    {
        if ($key === null) {
            if (count($this->templateDirs) > 0) {
                return $this->templateDirs;
            }
            return null;
        }
        if (is_string($key) === 'string' || is_int($key)) {
            return isset($this->templateDirs[$key]) ? $this->templateDirs[$key] : null;
        }
        return null;
    }

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:
Returns existing connection by config name or instantiate new one.
Вазвращает существующее подключение по имени из конига или создаёт новое.

@param string $name connection name defined in config

@return AbstractDb\DriverInterface

@throws DbException

public static function connection($name = 'default')
    {
        $name = $name == 'default' ? self::$config['connection']['default'] : $name;

        return isset(self::$connection[$name])
            ? self::$connection[$name]
            : self::$connection[$name] = self::createForConnection($name);
    }

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: Zeros out (tare) all of the load cells.

def _tare(self):

        for ser in self._serials:
            ser.write('TARE\r')
            ser.flush()
            ser.flushInput()
            ser.flushOutput()
        time.sleep(0.02)

function(ev, newList, oldList) {
                        teardownList();
                        // make an empty list if the compute returns null or undefined
                        list = newList || [];
                        // list might be a plain array
                        if (list.bind) {
                            list.bind('add', add)
                                .bind('remove', remove);
                        }
                        add({}, list, 0);
                    }

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


Question: Expire all the objects with the key having a given prefix.

def ExpirePrefix(self, prefix):
    """"""
    for key in list(self._hash):
      if key.startswith(prefix):
        self.ExpireObject(key)

public function replicate(array $attributes = [])
    {
        $groupPrefix = isset($attributes['groupPrefix']) ? $attributes['groupPrefix'] : '';

        return new ManagerProxy($this, $this->namer, $groupPrefix);
    }

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


Question:
// ImageSurfaceCreateFromPNGStream creates an ImageSurface from a stream of
// PNG data.

func ImageSurfaceCreateFromPNGStream(r io.Reader) (*ImageSurface, error) {
	data := readClosure{r: r}
	key := goPointers.put(data)
	surf := &ImageSurface{wrapSurface(C.cairo_image_surface_create_from_png_stream(
		(C.cairo_read_func_t)(unsafe.Pointer(C.gocairo_read_func)),
		unsafe.Pointer(&key)))}
	goPointers.clear(key)
	// TODO: which should we prefer between readClosure.err and status?
	// Perhaps test against CAIRO_STATUS_WRITE_ERROR?  Needs a test case.
	return surf, surf.status()
}

def _render_filenames(filenames, zip_file, saltenv, template):
    '''

    '''
    if not template:
        return (filenames, zip_file)

    # render the path as a template using path_template_engine as the engine
    if template not in salt.utils.templates.TEMPLATE_REGISTRY:
        raise CommandExecutionError(
            'Attempted to render file paths with unavailable engine '
            '{0}'.format(template)
        )

    kwargs = {}
    kwargs['salt'] = __salt__
    kwargs['pillar'] = __pillar__
    kwargs['grains'] = __grains__
    kwargs['opts'] = __opts__
    kwargs['saltenv'] = saltenv

    def _render(contents):
        '''
        Render :param:`contents` into a literal pathname by writing it to a
        temp file, rendering that file, and returning the result.
        '''
        # write out path to temp file
        tmp_path_fn = salt.utils.files.mkstemp()
        with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_:
            fp_.write(salt.utils.stringutils.to_str(contents))
        data = salt.utils.templates.TEMPLATE_REGISTRY[template](
            tmp_path_fn,
            to_str=True,
            **kwargs
        )
        salt.utils.files.safe_rm(tmp_path_fn)
        if not data['result']:
            # Failed to render the template
            raise CommandExecutionError(
                'Failed to render file path with error: {0}'.format(
                    data['data']
                )
            )
        else:
            return data['data']

    filenames = _render(filenames)
    zip_file = _render(zip_file)
    return (filenames, zip_file)

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


Question:
// Handler returns an http.Handler that serves the metadata and SSO
// URLs

func (idp *IdentityProvider) Handler() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc(idp.MetadataURL.Path, idp.ServeMetadata)
	mux.HandleFunc(idp.SSOURL.Path, idp.ServeSSO)
	return mux
}

func (e *Environment) InstallHandlersWithMiddleware(r *router.Router, base router.MiddlewareChain) {
	warmup.InstallHandlers(r, base)

	if e.ExtraHandlers != nil {
		e.ExtraHandlers(r, base)
	}
}

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


Question:
Cancels a potfolio request and cleans up the tempdata
and redirects the user back to where they started

@param bool $logreturn options to return to porfolio log or caller return page
@return void
@uses exit

public function cancel_request($logreturn=false) {
        global $CFG;
        if (!isset($this)) {
            return;
        }
        $this->process_stage_cleanup(true);
        if ($logreturn) {
            redirect($CFG->wwwroot . '/user/portfoliologs.php');
        }
        redirect($this->caller->get_return_url());
        exit;
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $configurationPath = $input->getOption('configurationPath');
        $deploymentName = $input->getArgument('deploymentName');
        $deployment = $this->factory->getDeployment($deploymentName, $configurationPath);
        $workflow = $deployment->getWorkflow();

        if (! $deployment instanceof FailedDeployment) {
            $output->writeln('<success>Deployment ' . $deployment->getName() . '</success>');
            $output->writeln('');
            $output->writeln('Workflow: <success>' . $workflow->getName() . '</success>');

            if ($workflow instanceof SimpleWorkflow) {
                $value = $workflow->isEnableRollback() ? 'true' : 'false';
                $output->writeln('    <comment>Rollback enabled:</comment> <info>' . $value . '</info>');
            }

            $output->writeln('');

            $this->printNodes($deployment->getNodes());

            $this->printApplications($deployment->getApplications(), $deployment->getWorkflow());
        }
    }

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


Question:
Gets a request that adds a bookmark to a collection

@param bookmarkId        id of bookmark to add to collection
@param collectionId    id of collection to add the bookmark to
@return      request to add a bookmark to a collection

public BoxRequestsBookmark.AddBookmarkToCollection getAddToCollectionRequest(String bookmarkId, String collectionId) {
        BoxRequestsBookmark.AddBookmarkToCollection request = new BoxRequestsBookmark.AddBookmarkToCollection(bookmarkId, collectionId, getBookmarkInfoUrl(bookmarkId), mSession);
        return request;
    }

def get_atlas_peers(hostport, timeout=30, my_hostport=None, proxy=None):

    assert hostport or proxy, 'need either hostport or proxy'

    peers_schema = {
        'type': 'object',
        'properties': {
            'peers': {
                'type': 'array',
                'items': {
                    'type': 'string',
                    'pattern': '^([^:]+):([1-9][0-9]{1,4})$',
                },
            },
        },
        'required': [
            'peers'
        ],
    }

    schema = json_response_schema( peers_schema )

    if proxy is None:
        proxy = connect_hostport(hostport)

    peers = None
    try:
        peer_list_resp = proxy.get_atlas_peers()
        peer_list_resp = json_validate(schema, peer_list_resp)
        if json_is_error(peer_list_resp):
            return peer_list_resp

        # verify that all strings are host:ports
        for peer_hostport in peer_list_resp['peers']:
            peer_host, peer_port = url_to_host_port(peer_hostport)
            if peer_host is None or peer_port is None:
                return {'error': 'Server did not return valid Atlas peers', 'http_status': 503}

        peers = peer_list_resp

    except ValidationError as ve:
        if BLOCKSTACK_DEBUG:
            log.exception(ve)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node {}.  Try again with `--debug`.'.format(hostport), 'http_status': 500}
        return resp

    return peers

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


Question:
/*!
\static
\return the status of the approval collaboration item \a $approvalID.

static function checkApproval( $approvalID )
    {
        $collaborationItem = eZCollaborationItem::fetch( $approvalID );
        if ( $collaborationItem !== null )
        {
            return $collaborationItem->attribute( 'data_int3' );
        }
        return false;
    }

protected void validateFull(
        CmsUUID structureId,
        Map<String, String> sitePaths,
        final AsyncCallback<Map<String, String>> errorCallback) {

        validateAliases(structureId, sitePaths, errorCallback);
    }

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


Question: launch an HTTP to preview the website

def preview():  # pragma: no coverage
    """"""
    Handler = http.server.SimpleHTTPRequestHandler
    socketserver.TCPServer.allow_reuse_address = True
    port = CONFIG['http_port']
    httpd = socketserver.TCPServer(("", port), Handler)
    os.chdir(CONFIG['output_to'])
    try:
        logger.info("and ready to test at "
                    "http://127.0.0.1:%d" % CONFIG['http_port'])
        logger.info("Hit Ctrl+C to exit")
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.shutdown()

func (s *GetSampledRequestsOutput) SetSampledRequests(v []*SampledHTTPRequest) *GetSampledRequestsOutput {
	s.SampledRequests = v
	return s
}

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


Question:
Replies the JVM operations that correspond to the given URIs.

@param container the container of the operations.
@param operationUris the URIs.
@return the JVM operations.

public List<JvmOperation> getJvmOperationsFromURIs(XtendTypeDeclaration container, String... operationUris) {
		// Collect the JvmOperation prior to any modification for ensuring that
		// URI are pointing the JvmOperations.
		final List<JvmOperation> operations = new ArrayList<>();
		final ResourceSet resourceSet = container.eResource().getResourceSet();
		for (final String operationUriAsString : operationUris) {
			final URI operationURI = URI.createURI(operationUriAsString);
			final EObject overridden = resourceSet.getEObject(operationURI, true);
			if (overridden instanceof JvmOperation) {
				final JvmOperation operation = (JvmOperation) overridden;
				if (this.annotationFinder.findAnnotation(operation, DefaultValueUse.class) == null) {
					operations.add(operation);
				}
			}
		}
		return operations;
	}

public <T> T as(Class<T> type) {
        return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getDeclaringClass() == Object.class)
                    return method.invoke(this, args);

                Configuration cn = method.getAnnotation(Configuration.class);

                Class<?> r = method.getReturnType();
                String key = getKey(method,cn);

                String v = source.apply(key);
                if (v==null && cn!=null && !cn.defaultValue().equals(UNSPECIFIED))
                    v = cn.defaultValue();

                if (v==null)    return null;    // TODO: check how the primitive types are handled here

                return ConvertUtils.convert(v,r);
            }

            private String getKey(Method method, Configuration c) {
                if (c!=null && !c.name().equals(UNSPECIFIED))
                    return c.name();        // name override

                String n = method.getName();
                for (String p : GETTER_PREFIX) {
                    if (n.startsWith(p))
                        return Introspector.decapitalize(n.substring(p.length()));
                }
                return n;
            }
        }));
    }

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


Question:
Ask for a new file, using the superclass method, but if none is found,
wait for a while and ask again. This will continue until we get a server
shutdown signal.

@Override
    protected synchronized JournalInputFile openNextFile()
            throws JournalException {
        while (open) {
            JournalInputFile nextFile = super.openNextFile();
            if (nextFile != null) {
                return nextFile;
            }
            try {
                wait(pollingIntervalMillis);
            } catch (InterruptedException e) {
                // no special action on interrupt.
            }
        }
        return null;
    }

def stop(self):
        '''

        '''
        self._server.shutdown()
        self._server.server_close()
        self._thread.join()
        self.running = False

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


Question:
Returns the uploaded file.

@return UploadedFile|null

public function getFileUpload()
    {
        $propertyName = $this->getFileUploadPropertyName(__FUNCTION__);

        if (isset($this->fileUploads[$propertyName])) {
            return $this->fileUploads[$propertyName];
        }
    }

public function postAction(Request $request)
    {
        try {
            $attribute = $this->getManager()->save(
                $request->request->all(),
                $this->getLocale($request),
                $this->getUser()->getId()
            );
            $view = $this->view($attribute, 200);
        } catch (AttributeDependencyNotFoundException $exc) {
            $exception = new EntityNotFoundException($exc->getEntityName(), $exc->getId());
            $view = $this->view($exception->toArray(), 400);
        } catch (MissingAttributeException $exc) {
            $exception = new MissingArgumentException(self::$entityName, $exc->getAttribute());
            $view = $this->view($exception->toArray(), 400);
        }

        return $this->handleView($view);
    }

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


Question: Makes a text widget.

def _makeExtraWidgets(self):

        self.textWidget = urwid.Text(self.text)
        return [self.textWidget]

def font(self, prefix, size):
        """"""
        font = QFont(self.fontname[prefix])
        font.setPixelSize(size)
        if prefix[-1] == 's':  # solid style
            font.setStyleName('Solid')
        return font

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


Question:
Retrieves the highest page of the groups.

@return int

public function getHighestGroupPage()
    {
        $max = 1;
        $path = $this->prefixWithNamespace('groupPage');
        $groupPages = $this->argumentsAccessor->get($path, []);
        foreach ($groupPages as $groups) {
            if (!is_array($groups)) continue;
            foreach ($groups as $groupItemPage) {
                if ($groupItemPage > $max) {
                    $max = $groupItemPage;
                }
            }
        }

        return $max;
    }

protected function render_paging_bar(paging_bar $pagingbar) {
        // Any more than 10 is not usable and causes weird wrapping of the pagination.
        $pagingbar->maxdisplay = 10;
        return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
    }

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


Question:
/*
Peter can you document this method? TODO

@param moved
@param fixed
@return

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question: // newTemplates returns a Templates

func newTemplates(c *TemplateClient, namespace string) *templates {
	return &templates{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

public function get_resources() {

        if (empty($this->resources)) {
            $this->resources = array();
            $this->resources[] = new \ltiservice_toolproxy\local\resources\toolproxy($this);
        }

        return $this->resources;

    }

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


Question:
Set terminal width and height

Resets the screen as well

@param int $x
@param int $y
@access public

function setDimensions($x, $y)
    {
        $this->max_x = $x - 1;
        $this->max_y = $y - 1;
        $this->x = $this->y = 0;
        $this->history = $this->history_attrs = array();
        $this->attr_row = array_fill(0, $this->max_x + 2, $this->base_attr_cell);
        $this->screen = array_fill(0, $this->max_y + 1, '');
        $this->attrs = array_fill(0, $this->max_y + 1, $this->attr_row);
        $this->ansi = '';
    }

def process(self, txt, mode):

        result = ''
        if mode == 'ADD':  # already in add mode, so add data
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Adding Text : ', txt)
                result = self.cmd_add(txt)
        elif mode == 'QUERY':
            if txt in self.all_commands['cmd'][0]:
                self.show_output('Returning to Command mode')
                mode = 'COMMAND'
                self.prompt = '> '
            else:
                self.show_output('Query : ', txt)
                result = self.cmd_query(txt)
        else:
            if txt in self.all_commands['exit'][0]:
                self.cmd_exit()

            elif txt in self.all_commands['help'][0]:
                self.cmd_help()

            elif txt in self.all_commands['cmd'][0]:
                result = 'Returning to Command mode'
                mode = 'COMMAND'
                self.prompt = '> '

            elif txt in self.all_commands['add'][0]:
                result = 'Entering Add mode'
                mode = 'ADD'
                self.prompt = 'ADD > '

            elif txt in self.all_commands['query'][0]:
                result = 'Entering Query mode'
                mode = 'QUERY'
                self.prompt = '?? > '
            else:
                result = 'Unknown command - type help for list of commands'

        return result, mode

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


Question: updates the assets manifest with the latest release manifest so that webpack bundles remain largely the same

function updateManifest() {
  const {stdout: branch} = exec(`git rev-parse --abbrev-ref HEAD`)

  if (!branch.includes("release")) {
    return;
  }

  console.log("[copy-assets] update assets manifest");

  const last = lastRelease();
  exec(`git cat-file -p ${last}:assets/module-manifest.json > assets/module-manifest.json`);
}

function Resource( pkg, config ) {
	var key;

	// Properties
	this.pkg = pkg;
	this.config = {};

	// Initialization
	for ( key in config ) {
		if ( Object.prototype.hasOwnProperty.call( config, key ) ) {
			this.config[key] = config[key];
		}
	}
}

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


Question:
Whether this table has a header to display

Each column is asked whether is has a header to display.

protected function hasHeader()
    {
        $has_header = false;

        foreach ($this->columns as $column) {
            if ($column->hasHeader()) {
                $has_header = true;
                break;
            }
        }

        return $has_header;
    }

private function getColumns($data)
        {
            $cols = [];

            foreach ($data[0] as $key => $value) {
                if (is_numeric($key)){
                    if (is_string($data[1][$key])) {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'number'];
                    }

                    $this->_skipFirstRow = true;
                } else {
                    if (is_string($value)) {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'number'];
                    }
                }
            }

            return $cols;
        }

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


Question:
Create an instance of {@link JAXBElement }{@code <}{@link DateAttributeType }{@code >}

@param value
Java instance representing xml element's value.
@return
the new instance of {@link JAXBElement }{@code <}{@link DateAttributeType }{@code >}

@XmlElementDecl(namespace = "http://www.opengis.net/citygml/generics/2.0", name = "dateAttribute", substitutionHeadNamespace = "http://www.opengis.net/citygml/generics/2.0", substitutionHeadName = "_genericAttribute")
    public JAXBElement<DateAttributeType> createDateAttribute(DateAttributeType value) {
        return new JAXBElement<DateAttributeType>(_DateAttribute_QNAME, DateAttributeType.class, null, value);
    }

@Override
    public void startElement(final String uri, final String localName, final String qName,
                             final Attributes atts) throws SAXException {
        ignoreStack.push(MAP_RELTABLE.matches(atts) ? false : ignoreStack.isEmpty() || ignoreStack.peek());

        Attributes res = atts;
        if (ignoreStack.peek() && MAP_TOPICREF.matches(res)) {
            final URI href = toURI(res.getValue(ATTRIBUTE_NAME_HREF));
            final URI copyTo = toURI(res.getValue(ATTRIBUTE_NAME_COPY_TO));
            final URI source = copyTo != null ? copyTo : href;
            final String scope = res.getValue(ATTRIBUTE_NAME_SCOPE);
            final String format = res.getValue(ATTRIBUTE_NAME_FORMAT);
            // FIXME: handle cascading
            final String processingRole = res.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE);
            if (source != null &&
                    (scope == null || scope.equals(ATTR_SCOPE_VALUE_LOCAL)) &&
                    (format == null || format.equals(ATTR_FORMAT_VALUE_DITA)) &&
                    (processingRole == null || processingRole.equals(ATTR_PROCESSING_ROLE_VALUE_NORMAL))) {
                final URI file = stripFragment(source);
                Integer count = topicrefCount.getOrDefault(file, 0);
                count++;
                topicrefCount.put(file, count);
                if (count > 1) { // not only reference to this topic
                    final FileInfo srcFi = job.getFileInfo(currentFile.resolve(stripFragment(source)));
                    if (srcFi != null) {
                        final FileInfo dstFi = generateCopyToTarget(srcFi, count);
                        copyToMap.put(dstFi, srcFi);

                        final URI dstTempAbs = job.tempDirURI.resolve(dstFi.uri);
                        final URI targetRel = getRelativePath(currentFile, dstTempAbs);
                        final URI target = setFragment(targetRel, href.getFragment());

                        final AttributesImpl buf = new AttributesImpl(atts);
                        XMLUtils.addOrSetAttribute(buf, ATTRIBUTE_NAME_COPY_TO, target.toString());
                        res = buf;
                    }
                }
            }
        }

        getContentHandler().startElement(uri, localName, qName, res);
    }

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


Question:
Builds nested tree from single category list.

@param array $dataSet  A set of nodes.
@param int   $maxLevel Maximum levels deep of the tree to build.

@return array

private function buildTree($dataSet, $maxLevel = 0)
    {
        $tree = new \ArrayIterator();
        $references = new \ArrayIterator();

        /** @var DocumentIterator $dataSet */
        foreach ($dataSet as $node) {
            if ($node->isActive()) {
                $this->buildNode($node, $references, $tree, $maxLevel);
            }
        }

        $this->expandNodes($references);

        $this->sortChildTree($tree);

        return $tree;
    }

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
Check that `value` is a valid instance of `ruby_type` through `===` or
 raise an error.

def dress(value, handler = DressHelper.new)
      handler.failed!(self, value) unless ruby_type===value
      value
    end

def outdated?
      @outdated = []
      fields.each do |fld|
        if fld.transition?
          # call r_trans method with local val to compare local with remote val
          # SomeTrans.remote_transfer_method( l_obj.field )
          virtual_l_val = eval "#{fld.r_trans} l_obj.send( fld.l_name )"
          @outdated << fld if virtual_l_val != r_obj.send( fld.r_name )
        else
          # no transfer method, directly compare values
          @outdated << fld if r_obj.send( fld.r_name ) != l_obj.send( fld.l_name )
        end
      end
      !@outdated.empty?
    end

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


Question: Set AxisProperties and PropertySets

def _set_axis_properties(self, axis):
        """"""
        if not getattr(axis, 'properties'):
            axis.properties = AxisProperties()
            for prop in ['ticks', 'axis', 'major_ticks', 'minor_ticks',
                         'title', 'labels']:
                setattr(axis.properties, prop, PropertySet())

public function setValues(array $values = array())
    {
        foreach ($values as $k => $v) {
            $this->set($k, $v);
        }

        return $this;
    }

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 *GetContactInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetContactInput"}
	if s.ContactArn == nil {
		invalidParams.Add(request.NewErrParamRequired("ContactArn"))
	}

	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:
Add directory to store built-in plugins to `module_dir` parameter.
        Default directory to store plugins is `BLACKBIRD_INSTALL_DIR/plugins`.
        :rtype: None
        :return: None

def add_default_module_dir(self):

        default_module_dir = os.path.join(
            os.path.abspath(os.path.curdir),
            'plugins'
        )
        module_dir_params = {
            'module_dir': [default_module_dir]
        }

        if 'module_dir' in self.config['global']:
            module_dir_params['module_dir'].append(
                self.config['global']['module_dir']
            )
        self.config['global'].update(
            module_dir_params
        )

def implode(self, env):

        juicer.utils.Log.log_debug("imploding %s" % self.cart_name)

        # rm -r self.remotes_storage()
        if os.path.exists(self.remotes_storage):
            for item in os.listdir(self.remotes_storage):
                ipath = os.path.expanduser(self.remotes_storage + '/' + item)
                if os.path.exists(ipath):
                    juicer.utils.Log.log_debug("removing %s" % ipath)
                    os.remove(ipath)
                juicer.utils.Log.log_debug("removing %s's remote item storage dir" % self.cart_name)
                os.rmdir(self.remotes_storage)

        # rm cart_file()
        if os.path.exists(self.cart_file()):
            juicer.utils.Log.log_debug("removing %s's cart file" % self.cart_name)
            os.remove(self.cart_file())

        # db.carts.delete(self.name)
        juicer.utils.Log.log_debug("removing %s from the database" % self.cart_name)
        juicer.utils.cart_db()[env].remove({'_id': self.cart_name})

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


Question: Return True if room name successfully changed.

def set_room_name(self, name):
        """"""
        try:
            self.client.api.set_room_name(self.room_id, name)
            self.name = name
            return True
        except MatrixRequestError:
            return False

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

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


Question:
Accept a string/object
and resolve it into the plugin format above
@param item
@returns {*}

function resolvePlugin(item) {
    /**
     * Handle when string was given, such as plugins: ['bs-html-injector']
     */
    if (typeof item === "string") {
        return getFromString(item);
    }

    if (!isMap(item)) {
        return new Plugin().mergeDeep({
            errors: [new Error("Plugin not supported in this format")]
        });
    }

    if (item.has("module")) {
        var nameOrObj = item.get("module");
        var options = item.get("options");

        /**
         * The 'module' key can be a string, this allows
         * inline plugin references, but with options
         * eg:
         *
         * bs.init({
         *     plugins: [
         *         {
         *             module: './myjs-file.js'
         *             options: {
         *                 files: "*.html"
         *             }
         *         }
         *     ]
         * });
         */
        if (typeof nameOrObj === "string") {
            return getFromString(nameOrObj).mergeDeep({
                options: options
            });
        }

        /**
         * If the plugin was given completely inline (because it needs options)
         * eg:
         *
         * bs.init({
         *     plugins: [
         *         {
         *             module: {
         *                 plugin: function() {
         *                     console.log('My plugin code')
         *                 }
         *             },
         *             options: {
         *                 files: "*.html"
         *             }
         *         }
         *     ]
         * })
         */
        if (Immutable.Map.isMap(nameOrObj)) {
            return new Plugin({
                module: nameOrObj,
                options: options
            });
        }
    }

    /**
     * If a module was given directly. For example, ater calling require.
     *
     * eg:
     *    var myplugin = require('./some-js');
     *    bs.init({plugins: [myplugin]});
     */
    if (item.has("plugin")) {
        return new Plugin({
            module: item
        });
    }

    /**
     * If we reach here, the plugin option was used incorrectly
     */
    return new Plugin().mergeDeep({
        errors: [new Error("Plugin was not configured correctly")]
    });
}

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

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

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


Question: // SetDescription sets the Description field's value.

func (s *CreateEnvironmentInput) SetDescription(v string) *CreateEnvironmentInput {
	s.Description = &v
	return s
}

def _descr_str(descr, data, region):

    if data:
        name = dd.get_sample_name(data)
        if name:
            descr = "{0} : {1}".format(descr, name)
        elif "work_bam" in data:
            descr = "{0} : {1}".format(descr, os.path.basename(data["work_bam"]))
    if region:
        descr = "{0} : {1}".format(descr, region)
    return descr

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


Question: Map some function in all board positions and return a new board

function mapBoard(board, func) {
    return board.map(function (col) {
        return col.map(function (p) {
            return func(p);
        });
    });
}

func (l *waiterList) PushFront(e *Entry) {
	waiterElementMapper{}.linkerFor(e).SetNext(l.head)
	waiterElementMapper{}.linkerFor(e).SetPrev(nil)

	if l.head != nil {
		waiterElementMapper{}.linkerFor(l.head).SetPrev(e)
	} else {
		l.tail = e
	}

	l.head = e
}

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