Question:
// Setup creates a new networking namespace and executes network plugins to
// set up networking. It returns in the new pod namespace

func Setup(podRoot string, podID types.UUID, fps []commonnet.ForwardedPort, netList common.NetList, localConfig, flavor string, noDNS, debug bool) (*Networking, error) {

	stderr = log.New(os.Stderr, "networking", debug)
	debuglog = debug

	if flavor == "kvm" {
		return kvmSetup(podRoot, podID, fps, netList, localConfig, noDNS)
	}

	// TODO(jonboulle): currently podRoot is _always_ ".", and behaviour in other
	// circumstances is untested. This should be cleaned up.
	n := Networking{
		podEnv: podEnv{
			podRoot:      podRoot,
			podID:        podID,
			netsLoadList: netList,
			localConfig:  localConfig,
		},
	}

	err := n.mountNetnsDirectory()
	if err != nil {
		return nil, err
	}

	// Create the network namespace (and save its name in a file)
	err = n.podNSCreate()
	if err != nil {
		return nil, err
	}

	n.nets, err = n.loadNets()
	if err != nil {
		return nil, errwrap.Wrap(errors.New("error loading network definitions"), err)
	}

	if err := n.setupNets(n.nets, noDNS); err != nil {
		return nil, err
	}

	if len(fps) > 0 {
		if err = n.enableDefaultLocalnetRouting(); err != nil {
			return nil, err
		}
		podIP, err := n.GetForwardableNetPodIP()
		if err != nil {
			return nil, err
		}
		if err := n.setupForwarding(); err != nil {
			n.teardownForwarding()
			return nil, err
		}
		if err := n.forwardPorts(fps, podIP); err != nil {
			n.teardownForwarding()
			return nil, err
		}
	}

	// Switch to the podNS
	if err := n.podNS.Set(); err != nil {
		return nil, err
	}

	if err = loUp(); err != nil {
		return nil, err
	}

	return &n, nil
}

def local(tool, slug, config_loader, offline=False):

    # Parse slug
    slug = Slug(slug, offline=offline)

    local_path = Path(LOCAL_PATH).expanduser() / slug.org / slug.repo

    git = Git(f"-C {shlex.quote(str(local_path))}")
    if not local_path.exists():
        _run(Git()(f"init {shlex.quote(str(local_path))}"))
        _run(git(f"remote add origin https://github.com/{slug.org}/{slug.repo}"))

    if not offline:
        # Get latest version of checks
        _run(git(f"fetch origin {slug.branch}"))

    # Ensure that local copy of the repo is identical to remote copy
    _run(git(f"checkout -f -B {slug.branch} origin/{slug.branch}"))
    _run(git(f"reset --hard HEAD"))

    problem_path = (local_path / slug.problem).absolute()

    if not problem_path.exists():
        raise InvalidSlugError(_("{} does not exist at {}/{}").format(slug.problem, slug.org, slug.repo))

    # Get config
    try:
        with open(problem_path / ".cs50.yaml") as f:
            try:
                config = config_loader.load(f.read())
            except InvalidConfigError:
                raise InvalidSlugError(
                    _("Invalid slug for {}. Did you mean something else?").format(tool))
    except FileNotFoundError:
        raise InvalidSlugError(_("Invalid slug. Did you mean something else?"))

    return problem_path

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


Question: // Find returns the current value or a not found error.

func (v Var) Find(path Ref) (Value, error) {
	if len(path) == 0 {
		return v, nil
	}
	return nil, fmt.Errorf("find: not found")
}

public function define(string $option)
    {
        if (!array_key_exists($option, $this->options)) {
            throw new OptionsException("Undefined relation option '{$option}'");
        }

        return $this->options[$option];
    }

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


Question:
Build sequence for Circle CI 2.0 config.yml

    builds the circleci structure
    also links individual jobs into a workflow graph

def generate_circle_output():

    base = new_base()
    workflow = networkx.DiGraph()
    LOG.info('%s python versions', len(python_versions))
    LOG.info('%s mbed cloud hosts', len(mbed_cloud_hosts))

    job, content = new_tpip()
    base['jobs'].update({job: content})
    workflow.add_node(job)

    job, content = new_newscheck()
    base['jobs'].update({job: content})
    workflow.add_node(
        job,
        workflow=dict(
            filters=dict(
                branches=dict(
                    # we ignore this check for builds directly on the base branches
                    ignore=['master', 'integration']
                )
            )
        )
    )

    job, content = new_build_documentation()
    base['jobs'].update({job: content})
    workflow.add_node(
        job,
        workflow=dict(
            requires=['build_py2', 'build_py3'],
            filters = dict(
                branches=dict(
                    # Only update the documentation on release branches
                    only=['master', 'beta']
        )
    )
    )
    )

    preload_job, content = new_preload()
    base['jobs'].update({preload_job: content})
    workflow.add_node(job)

    for py_ver in python_versions.values():
        build_job, build_content = new_build(py_ver=py_ver)
        base['jobs'].update({build_job: build_content})
        workflow.add_edge(preload_job, build_job)

        for cloud_host in mbed_cloud_hosts.values():
            test_job, test_content = new_test(py_ver=py_ver, cloud_host=cloud_host)
            base['jobs'].update({test_job: test_content})
            workflow.add_edge(build_job, test_job)

    for release_target in release_target_map.values():
        deploy_job, deploy_content = new_deploy(
            py_ver=python_versions['three'],
            release_target=release_target
        )
        base['jobs'].update({deploy_job: deploy_content})

    # wire up the release gates (clicky buttons)
    workflow.add_edge(
        test_name(python_versions['three'], mbed_cloud_hosts['osii']),
        release_name(release_target_map['beta']),
        type='approval',
    )
    workflow.add_edge(
        test_name(python_versions['three'], mbed_cloud_hosts['production']),
        release_name(release_target_map['prod']),
        type='approval',
        filters=dict(branches=dict(only='master')),
    )
    workflow.add_edge(
        test_name(python_versions['two'], mbed_cloud_hosts['production']),
        release_name(release_target_map['prod']),
    )

    # we only want to deploy in certain conditions
    workflow.add_edge(
        release_name(release_target_map['beta']),
        deploy_name(python_versions['three'], release_target_map['beta'])
    )

    workflow.add_edge(
        release_name(release_target_map['prod']),
        deploy_name(python_versions['three'], release_target_map['prod'])
    )

    workflow_jobs = base['workflows']['python_sdk_workflow']['jobs']

    # build the workflow graph
    for job_name in networkx.topological_sort(workflow):
        job_config = {}
        per_node_config = workflow.nodes[job_name].get('workflow')
        if per_node_config:
            job_config.update(per_node_config)
        workflow_jobs.append({job_name: job_config})
        for edge in workflow.in_edges(job_name):
            job_config.update(workflow.get_edge_data(*edge))
            job_config.setdefault('requires', []).append(edge[0])

    LOG.info('%s circle jobs', len(base['jobs']))
    return dict(base)

public static function generate($args, $opts, $console)
    {
        $checklist = new ConsoleKit\Widgets\Checklist($console);
        foreach ($args as $action) {
            $console->writeln("Generating '$action'");
            $filename = ltrim($action, '/') . '.php';

            $actionsDir = (array) Atomik::get('atomik.dirs.actions');
            $actionsDir = array_shift($actionsDir);
            $checklist->step("Creating action file in $actionsDir", function() use ($actionsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($actionsDir, $filename),
                    "<?php\n\n// Logic goes here\n");
            });

            $viewsDir = (array) Atomik::get('atomik.dirs.views');
            $viewsDir = array_shift($viewsDir);
            $checklist->step("Creating view file in $viewsDir", function() use ($viewsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($viewsDir, $filename));
            });

            Atomik::fireEvent('Console::Generate', array($action));
        }
    }

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


Question:
Returns an array of "local" pages given a page number and range.

@param  Paginator\Paginator $paginator
@param  int $pageRange Unused
@return array

public function getPages(Paginator $paginator, $pageRange = null)
    {
        $pageRange  = $paginator->getPageRange();
        $pageNumber = $paginator->getCurrentPageNumber();

        $delta = $pageNumber % $pageRange;

        if ($delta == 0) {
            $delta = $pageRange;
        }

        $offset     = $pageNumber - $delta;
        $lowerBound = $offset + 1;
        $upperBound = $offset + $pageRange;

        return $paginator->getPagesInRange($lowerBound, $upperBound);
    }

public function match($pathinfo)
    {
        $routes = array();
        $this->debug(sprintf('match: Matching %s', $pathinfo));

        foreach ($this->matchers as $matcher) {
            try {
                $routes = $matcher->match($pathinfo);
                break;
            } catch (ResourceNotFoundException $e) {
            } catch (MethodNotAllowedException $e) {
            }
        }

        if (!isset($routes['_route']) || !isset($routes['_controller'])) {
            $mesg = 'match: No Routes Found.';
            $this->alert($mesg);
            throw new RoutingException($mesg);
        }

        $this->debug(sprintf('match: Route matched %s', $routes['_route']));

        return($routes);
    }

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


Question: // FindActionsByName finds Actions with the given name.

func (m *Model) FindActionsByName(name string) ([]Action, error) {
	var results []Action
	var doc actionDoc

	actions, closer := m.st.db().GetCollection(actionsC)
	defer closer()

	iter := actions.Find(bson.D{{"name", name}}).Iter()
	for iter.Next(&doc) {
		results = append(results, newAction(m.st, doc))
	}
	return results, errors.Trace(iter.Close())
}

public function getTeamDrops(Dropzone $dropzone, User $user)
    {
        $drops = $this->dropRepo->findTeamDrops($dropzone, $user);

        return $drops;
    }

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


Question: Call compile function in a safe way.

public final function compile()
	{
		try {
			$q = $this->compileQuery();
			if ($this->log_query) {
				error_log(sprintf("SQL Query (compile):\n%s", $this->query_sql));
			}
			return $q;
		}
		catch (\Exception $ex) {
			// Make sure unfinished query will not make it to the output.
			ob_end_clean();
			throw $ex;
		}
	}

public static Object dotGetUnsafe(final Map map, final String pathString) {
        return dotGetUnsafe(map, Object.class, pathString);
    }

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


Question:
Generates a GraphQL Mutation to create a record
@param string $typeName
@param Type[] $typeFields
@return string

public static function generate(string $typeName, array $typeFields): string
    {
        $mutationName = 'create' . $typeName;

        $arguments = RelationArgumentGenerator::generate($typeFields);
        $arguments = array_merge($arguments, InputFieldsArgumentGenerator::generate($typeFields));

        if (count($arguments) < 1) {
            return '';
        }

        $mutation = sprintf('    %s(%s)', $mutationName, implode(', ', $arguments));
        $mutation .= sprintf(': %1$s @create(model: "%1$s")', $typeName);

        if (config('lighthouse-utils.authorization')) {
            $permission = sprintf('create%1$s', $typeName);
            $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission);
        }

        GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null);

        return $mutation;
    }

def build_collection_query_object(name, additional_parameters, *args)
    root = "/#{name.to_s}"
    if args.empty?
      #nothing to add
    elsif args.size == 1
      if args.first.to_s =~ /\d+/
        id_metadata = find_id_metadata(name.to_s)
        root << build_id_path(args.first, id_metadata)
      else
        root << "(#{args.first})"
      end
    else
      root << "(#{args.join(',')})"
    end
    QueryBuilder.new(root, additional_parameters)
  end

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


Question: // setArray stores a set of uint16s as data.

func (c *Container) setArray(array []uint16) {
	if roaringParanoia {
		if c.typ != containerArray {
			panic("attempt to write non-array's array")
		}
	}
	// no array: start with our default 5-value array
	if array == nil {
		c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedArraySize
		return
	}
	h := (*reflect.SliceHeader)(unsafe.Pointer(&array))
	if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
		// nothing to do but update length
		c.len = int32(h.Len)
		return
	}
	// array we can fit in data store:
	if len(array) <= stashedArraySize {
		copy(c.data[:stashedArraySize], array)
		c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(array)), stashedArraySize
		c.mapped = false // this is no longer using a hypothetical mmapped input array
		return
	}
	c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
	runtime.KeepAlive(&array)
}

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:
set events, so can set event->handler by config

@param array $events array($eventName => $handler)
@return void

public function setEvents(array $events)
	{
		if ($events) {
			$this->ensureEvents();

			foreach ($events as $name => $handler) {
				$this->on($name, $handler);
			}
		}
	}

protected function resolveResponse()
    {
        if ($evtResponse = $this->fire('kernel.request')) {
            return $evtResponse;
        }

        $controller = $this->router()->match($this->request());

        if (empty($controller)) {
            throw new AppException('No controller was returned from router');
        }

        if ($evtResponse = $this->fire('kernel.route')) {
            return $evtResponse;
        }

        if ($evtResponse = $this->fire('kernel.controller')) {
            return $evtResponse;
        }

        $response = $this->callController($controller);

        if ($evtResponse = $this->fire('kernel.response', $response)) {
            return $evtResponse;
        }

        return $response;
    }

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


Question:
Returns the correct format for the length in bytes of the remaining bytes

@param ClientInterface $client
@param string $rawMQTTHeaders
@return int

private function performRemainingLengthFieldOperations(
        string &$rawMQTTHeaders,
        ClientInterface $client
    ): int {
        // Early return: assume defaults if first digit has a value under 128, no further need for complex checks
        if (ord($rawMQTTHeaders{1}) < 128) {
            return ord($rawMQTTHeaders{1});
        }

        // If we have less than 4 bytes now, we should really try to recover the rest of the remaining field data
        if (strlen($rawMQTTHeaders) < 4) {
            // At this point we could actually read at least 128 as a minimum, but restrict it to what we need right now
            $rawMQTTHeaders .= $client->readBrokerData(4 - strlen($rawMQTTHeaders));
        }

        $remainingBytes = Utilities::convertRemainingLengthStringToInt(substr($rawMQTTHeaders, 1, 4));

        // Estimate how much longer is the remaining length field, this will also set $this->sizeOfRemainingLengthField
        $this->calculateSizeOfRemainingLengthField($remainingBytes);
        return $remainingBytes;
    }

func (*Model) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _Model_OneofMarshaler, _Model_OneofUnmarshaler, _Model_OneofSizer, []interface{}{
		(*Model_TranslationModelMetadata)(nil),
		(*Model_ImageClassificationModelMetadata)(nil),
		(*Model_TextClassificationModelMetadata)(nil),
		(*Model_ImageObjectDetectionModelMetadata)(nil),
		(*Model_VideoClassificationModelMetadata)(nil),
		(*Model_TextExtractionModelMetadata)(nil),
		(*Model_TablesModelMetadata)(nil),
		(*Model_TextSentimentModelMetadata)(nil),
	}
}

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


Question:
Make the hmtx table.

        **This should not be called externally.** Subclasses
        may override or supplement this method to handle the
        table creation in a different way if desired.

def setupTable_hmtx(self):

        if "hmtx" not in self.tables:
            return

        self.otf["hmtx"] = hmtx = newTable("hmtx")
        hmtx.metrics = {}
        for glyphName, glyph in self.allGlyphs.items():
            width = otRound(glyph.width)
            if width < 0:
                raise ValueError(
                    "The width should not be negative: '%s'" % (glyphName))
            bounds = self.glyphBoundingBoxes[glyphName]
            left = bounds.xMin if bounds else 0
            hmtx[glyphName] = (width, left)

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

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

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

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


Question: // GetHosts returns a list of all registered hosts

func (f *Facade) GetHosts(ctx datastore.Context) ([]host.Host, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetHosts"))
	return f.hostStore.GetN(ctx, 10000)
}

func (r *hijackRecorder) WriteHeader(code int) {
	resp := http.Response{StatusCode: code, Header: r.Header()}
	_ = resp.Write(r.conn)
}

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


Question:
The weekdays where the recurrence will be applied.  In RFC5545 this is
        called BYDAY, but is renamed by dateutil to avoid ambiguity.

def byweekday(self):

        retval = []
        if self.rule._byweekday:
            retval += [Weekday(day) for day in self.rule._byweekday]
        if self.rule._bynweekday:
            retval += [Weekday(day, n) for day, n in self.rule._bynweekday]
        return retval

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

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

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

			minutes.keys.each do |epoch|

				products.each do |product|

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

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

					end

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

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

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

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

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


Question:
Check if assets configuration is the same as last saved configuration

@param  array $aAssetsType
@return boolean
@throws \RuntimeException
@throws \LogicException

public function assetsConfigurationHasChanged(array $aAssetsType = null)
    {
        $aAssetsType = $aAssetsType ? array_unique($aAssetsType) : array(\AssetsBundle\AssetFile\AssetFile::ASSET_CSS, \AssetsBundle\AssetFile\AssetFile::ASSET_LESS, \AssetsBundle\AssetFile\AssetFile::ASSET_JS, \AssetsBundle\AssetFile\AssetFile::ASSET_MEDIA);

        //Retrieve saved onfiguration file
        if (file_exists($sConfigFilePath = $this->getConfigurationFilePath())) {
            \Zend\Stdlib\ErrorHandler::start();
            $aConfig = include $sConfigFilePath;
            \Zend\Stdlib\ErrorHandler::stop(true);

            if ($aConfig === false || !is_array($aConfig)) {
                throw new \RuntimeException('Unable to get file content from file "' . $sConfigFilePath . '"');
            }

            //Get assets configuration
            $aAssets = $this->getOptions()->getAssets();

            //Check if configuration has changed for each type of asset
            foreach ($aAssetsType as $sAssetType) {
                if (!\AssetsBundle\AssetFile\AssetFile::assetFileTypeExists($sAssetType)) {
                    throw new \LogicException('Asset type "' . $sAssetType . '" does not exist');
                }
                if (empty($aAssets[$sAssetType]) && !empty($aConfig[$sAssetType])) {
                    return true;
                } elseif (!empty($aAssets[$sAssetType])) {
                    if (empty($aConfig[$sAssetType])) {
                        return true;
                    } elseif (array_diff($aAssets[$sAssetType], $aConfig[$sAssetType]) || array_diff($aConfig[$sAssetType], $aAssets[$sAssetType])
                    ) {
                        return true;
                    }
                }
            }
            return false;
        }
        return true;
    }

public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        $xml = $this->parseFile($path);
        $xml->registerXPathNamespace('config', 'http://thelia.net/schema/dic/config');

        $this->removeScope($xml);

        $this->container->addResource(new FileResource($path));

        $this->parseLoops($xml);

        $this->parseFilters($xml);

        $this->parseTemplateDirectives($xml);

        $this->parseParameters($xml);

        $this->parseCommands($xml);

        $this->parseForms($xml);

        $this->parseDefinitions($xml, $path);

        $this->parseHooks($xml, $path, $type);

        $this->propelOnlyRun(
            [$this, "parseExportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseExports"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImports"],
            $xml
        );
    }

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


@Override
  public void taskStateChange(TaskStatus.State state, TaskInProgress tip,
      TaskAttemptID taskid, String host) {
    LOG.info("The state of " + taskid + " changed to " + state +
        " on host " + host);
    processTaskResource(state, tip, taskid);
  }

def text message
      @suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
      @suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor

      message_col = 3
      r = 2
      display_length = @suggested_w-4
      display_length -= message_col
      clr = @color || :white
      bgclr = @bgcolor || :black

      if message.is_a? Array
        l = longest_in_list message
        if l > @suggested_w
          if l < FFI::NCurses.COLS
            #@suggested_w = l
            @suggested_w = FFI::NCurses.COLS-2
          else
            @suggested_w = FFI::NCurses.COLS-2
          end
          display_length = @suggested_w-6
        end
        # reduce width and height if you can based on array contents
      else
        message = wrap_text(message, display_length).split("\n")
      end
      # now that we have moved to textpad that +8 was causing black lines to remain after the text
      message_height = message.size #+ 8
      # reduce if possible if its not required.
      #
      r1 = (FFI::NCurses.LINES-@suggested_h)/2
      r1 = r1.floor
      w = @suggested_w
      c1 = (FFI::NCurses.COLS-w)/2
      c1 = c1.floor
      @suggested_row = r1
      @suggested_col = c1
      brow = @button_row || @suggested_h-4
      available_ht = brow - r + 1
      message_height = [message_height, available_ht].min
      # replaced 2014-04-14 - 23:51
      message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
        :row => r, :col => message_col, :width => display_length, :suppress_borders => true,
        :height => message_height, :bgcolor => bgclr , :color => clr}
      #message_label.set_content message
      yield message_label if block_given?

    end

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


Question:
Check if authenticate user has role

@param string $role

@return bool|null return NULL if user is not authenticated

public function hasRole($role)
    {
        if ($this->user() === null) {
            return null;
        }

        return in_array($role, $this->roles, true);
    }

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

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

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


Question: A stacked graph has many data sets.  Return legend information for all of them.

def legend_data
      if relevant_data?
        retval = []
        layers.each do |layer|
          retval << layer.legend_data
        end
        retval
      else
        nil
      end
    end

def display(self, dset_id: str):

        # update result
        self.skd[dset_id].compute()
        # build layout
        self.build_layout(dset_id=dset_id)
        # display widgets
        display(self._('dashboard'))
        # display data table and chart
        self._display_result(dset_id=dset_id)

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


Question:
Create a new instance from a data file path.

@param resource|null $context

@throws SyntaxError If the file does not exist or is not readable

public static function createFromDataPath(string $path, $context = null): self
    {
        $file_args = [$path, false];
        $mime_args = [$path, FILEINFO_MIME];
        if (null !== $context) {
            $file_args[] = $context;
            $mime_args[] = $context;
        }

        $raw = @file_get_contents(...$file_args);
        if (false === $raw) {
            throw new SyntaxError(sprintf('The file `%s` does not exist or is not readable', $path));
        }

        return Uri::createFromComponents([
            'scheme' => 'data',
            'path' => str_replace(' ', '', (new finfo(FILEINFO_MIME))->file(...$mime_args)).';base64,'.base64_encode($raw),
        ]);
    }

public function firstOrCreate(array $attributes = [])
    {
        $this->applyCriteria();
        $this->applyScope();

        $model = $this->model->firstOrCreate($attributes);
        $this->resetModel();

        return $this->parserResult($model);
    }

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


Question:
Gets the title part of the KSS Comment Block

@return string

protected function getTitleComment()
    {
        $titleComment = null;

        foreach ($this->getCommentSections() as $commentSection) {
            // Identify the title by the # markdown header syntax
            if (preg_match('/^\s*#/i', $commentSection)) {
                $titleComment = $commentSection;
                break;
            }
        }

        return $titleComment;
    }

def extract_value_from_output(canary, split_offset, kal_out):

    retval = ""
    while retval == "":
        for line in kal_out.splitlines():
            if canary in line:
                retval = str(line.split()[split_offset])
        if retval == "":
            retval = None
    return retval

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


Question:
Most use cases do not require this method. Will still keep it accessible so that one can disable it
until the averageSpeedEncodedValue is moved out of the FlagEncoder.

@Deprecated

protected void setSpeed(boolean reverse, IntsRef edgeFlags, double speed) {
        if (speed < 0 || Double.isNaN(speed))
            throw new IllegalArgumentException("Speed cannot be negative or NaN: " + speed + ", flags:" + BitUtil.LITTLE.toBitString(edgeFlags));

        if (speed < speedFactor / 2) {
            speedEncoder.setDecimal(reverse, edgeFlags, 0);
            accessEnc.setBool(reverse, edgeFlags, false);
            return;
        }

        if (speed > getMaxSpeed())
            speed = getMaxSpeed();

        speedEncoder.setDecimal(reverse, edgeFlags, speed);
    }

func (f *CustomUplinkFunctions) decode(payload []byte, port uint8) (map[string]interface{}, error) {
	if f.Decoder == "" {
		return nil, nil
	}

	env := map[string]interface{}{
		"payload": payload,
		"port":    port,
	}
	code := fmt.Sprintf(`
		%s;
		Decoder(payload.slice(0), port);
	`, f.Decoder)

	value, err := functions.RunCode("Decoder", code, env, timeOut, f.Logger)
	if err != nil {
		return nil, err
	}

	m, ok := value.(map[string]interface{})
	if !ok {
		return nil, errors.NewErrInvalidArgument("Decoder", "does not return an object")
	}
	return m, nil
}

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


Question:
Starts the timer.

If the timer is already started, this method does nothing.

@return void

public function start() : void
    {
        if ($this->startTime === null) {
            $this->startTime = $this->clock->getTime();
        }
    }

def next_state(self):
        """"""
        if(self.roaster.get_roaster_state() == 'roasting'):
            self.roaster.time_remaining = 20
            self.roaster.cool()
        elif(self.roaster.get_roaster_state() == 'cooling'):
            self.roaster.idle()

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


Question: // DeleteAllModelGroups implements Firewaller interface.

func (c *legacyNovaFirewaller) DeleteAllModelGroups(ctx context.ProviderCallContext) error {
	return deleteSecurityGroupsMatchingName(ctx, c.deleteSecurityGroups, c.jujuGroupRegexp())
}

public function buildSection(string $name, array $definition): SectionInterface
    {
        $section = new Section($name);
        $this->setExcluded($section, $definition);
        $this->setPreCommand($section, $definition);
        $this->setPostCommand($section, $definition);

        return $section;
    }

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


Question:
//func generateKey(key, filepath string) string {
//	return key + `#` + filepath
//}
//
//func getFileKeyNPath(configKey string) []string {
//	return strings.Split(configKey, `#`)
//}

func (fSource *fileSource) Cleanup() error {

	fSource.filelock.Lock()
	defer fSource.filelock.Unlock()

	if fileConfigSource == nil || fSource == nil {
		return nil
	}

	if fSource.watchPool != nil && fSource.watchPool.watcher != nil {
		fSource.watchPool.watcher.Close()
	}

	if fSource.watchPool != nil {
		fSource.watchPool.fileSource = nil
		fSource.watchPool.callback = nil
		fSource.watchPool = nil
	}
	fSource.Configurations = nil
	fSource.files = make([]file, 0)
	return nil
}

func LoadConfig() (*Config, error) {
	// Load the configuration according to the spec.
	task := "Load Git-related configuration"
	spec := newConfigSpec()
	if err := loader.LoadConfig(spec); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Get the remote name, which may be stored in git config.
	task = "Get the remote name for the main project repository"
	remoteName, err := GetConfigString(GitConfigKeyRemote)
	if err != nil {
		return nil, errs.NewError(task, err)
	}
	if remoteName == "" {
		remoteName = DefaultRemoteName
	}

	// Return the main config struct.
	return &Config{
		LocalConfig: *spec.local,
		RemoteName:  remoteName,
	}, nil
}

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


Question:
https://tapatalk.com/api/api_section.php?id=7#get_box
@param string $boxId
@param int $startNum
@param int $endNum

public function get_box($boxId, $startNum = null, $endNum = null)
    {
        try {
            $manager = $this->container->get('symbb.extension.tapatalk.manager.user');
            return $manager->getBox($boxId, $startNum, $endNum);
        } catch (\Exception $exc) {
            return $this->errorResponse($exc);
        }
    }

def push(self, code, msg=None):
        """"""
        if msg is None:
            msg = str(code)
        else:
            msg = '%s %s' % (code, msg)

        if not msg.endswith(self.LINE_TERMINATOR):
            msg += self.LINE_TERMINATOR
        self._channel.write(msg)

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


Question:
Batch update called by the fitting method.

        Args:
            train_events (list of Event): Positive training events.
            test_events (list of Event): Test events.
            n_epoch (int): Number of epochs for the batch training.

def __batch_update(self, train_events, test_events, n_epoch):

        for epoch in range(n_epoch):
            # SGD requires us to shuffle events in each iteration
            # * if n_epoch == 1
            #   => shuffle is not required because it is a deterministic training (i.e. matrix sketching)
            if n_epoch != 1:
                np.random.shuffle(train_events)

            # train
            for e in train_events:
                self.rec.update(e, batch_train=True)

            # test
            MPR = self.__batch_evaluate(test_events)
            if self.debug:
                logger.debug('epoch %2d: MPR = %f' % (epoch + 1, MPR))

def attention_lm_moe_base_ae():
  """"""
  hparams = attention_lm_moe_base_long_seq()
  hparams.attention_type = AttentionType.LOCAL_EXPERTS

  hparams.learning_rate = 0.05
  hparams.learning_rate_warmup_steps = 10000
  # According to noam, ("n", "da") seems better for harder-to-learn models
  # hparams.layer_preprocess_sequence = "n"
  # hparams.layer_postprocess_sequence = "da"
  return hparams

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


Question:
Delete Mock Volume.

@param volumeId
volumeId to be deleted
@return Mock volume.

public MockVolume deleteVolume(final String volumeId) {

        if (volumeId != null && allMockVolumes.containsKey(volumeId)) {
            return  allMockVolumes.remove(volumeId);
        }

        return null;
    }

public function getDeleteRequest($ids)
    {
        return new StorageDataRequest(
            [$this->sourceDataAdapter, $this->cacheDataAdapter, $ids],
            function (DataAdapterInterface $sourceData, DataAdapterInterface $cacheData, $ids) {
                $request = $sourceData->getDeleteRequest($ids);
                $request->send();
                $result = $request->fetch();
                $cacheData->getDeleteRequest($ids)->send();

                return $result;
            }
        );
    }

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


Question:
Parses a given URL path to get the resulting class name and created parameters.

@param  string $url The url path.
@return array Returns an array with the keys `controller` and `parameters`.

public function parse($url) {
		// iterate all rules
		$hit = false;

		foreach ($this->_routes as $rule => $new_class) {
			$regex		= trim($rule, '/');

			// rebuild route to a preg pattern
			if (preg_match($regex, $url, $parameters)) {
				$class = preg_replace($regex, $new_class, $url);
				$class = str_replace('/', '_', $class);
				unset($parameters[0]);
				$hit = true;
				break;
			}
		}

		if ($hit === false) {
			$class = call_user_func($this->_fallback, $url);
		}

		$class_shards = explode('\\', $class);
		$class_shards[count($class_shards)-1] = ucfirst(strtolower($class_shards[count($class_shards)-1]));
		$class = implode('\\', $class_shards);

		return [
			'controller'		=> $class,
			'parameters'		=> isset($parameters) ? $parameters : [],
		];
	}

protected function makeControllerInstance()
    {
        list($this->controllerClass, $this->controllerMethod) = explode('@', $this->action['uses']);

        $this->container->instance($this->controllerClass,
            $this->controller = $this->container->make($this->controllerClass));

        return $this->controller;
    }

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


Question: // SetName sets the Name field's value.

func (s *UpdateMaintenanceWindowTaskOutput) SetName(v string) *UpdateMaintenanceWindowTaskOutput {
	s.Name = &v
	return s
}

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

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

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


Question:
存储指定字段的指定名称的动态验证规则

@param string      $field
@param string      $name
@param string|null $rule

@throws LaravelSmsException

public function storeRule($field, $name, $rule = null)
    {
        self::validateFieldName($field);
        if (is_array($name)) {
            foreach ($name as $k => $v) {
                $this->storeRule($field, $k, $v);
            }

            return;
        }
        if ($rule === null && is_string($name)) {
            $rule = $name;
            $name = null;
        }
        if (empty($name) || !is_string($name)) {
            $name = Util::pathOfUrl(URL::current(), function ($e) use ($field) {
                throw new LaravelSmsException("Expected a name for the dynamic rule which belongs to field `$field`.");
            });
        }
        $allRules = $this->retrieveRules($field);
        $allRules[$name] = $rule;
        $key = $this->generateKey(self::DYNAMIC_RULE_KEY, $field);
        self::storage()->set($key, $allRules);
    }

public function create()
    {
        // Is this user allowed to do this?
        if (!$this->repository->isUserAllowed('create'))
        {
            Session::flash('status_code', 400 );
            $message = "You are not allowed to create ".$this->table_type_plural;
            Session::flash('message', $message);
            return view('formhandling::warnings/' . config('lasallecmsadmin.admin_template_name') . '/user_not_allowed', [
                'package_title'        => $this->package_title,
                'table_type_plural'    => $this->table_type_plural,
                'table_type_singular'  => $this->table_type_singular,
                'resource_route_name'  => $this->resource_route_name,
                'HTMLHelper'           => HTMLHelper::class,
            ]);
        }

        return view('formhandling::lookuptables/' . config('lasallecmsadmin.admin_template_name') . '/create', [
            'package_title'        => $this->package_title,
            'table_type_plural'    => $this->table_type_plural,
            'table_type_singular'  => $this->table_type_singular,
            'resource_route_name'  => $this->resource_route_name,
            'DatesHelper'          => DatesHelper::class,
            'HTMLHelper'           => HTMLHelper::class,
        ]);
    }

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


Question:
Caches the commerce tax method in the entity cache if it is enabled.

@param commerceTaxMethod the commerce tax method

@Override
	public void cacheResult(CommerceTaxMethod commerceTaxMethod) {
		entityCache.putResult(CommerceTaxMethodModelImpl.ENTITY_CACHE_ENABLED,
			CommerceTaxMethodImpl.class, commerceTaxMethod.getPrimaryKey(),
			commerceTaxMethod);

		finderCache.putResult(FINDER_PATH_FETCH_BY_G_E,
			new Object[] {
				commerceTaxMethod.getGroupId(), commerceTaxMethod.getEngineKey()
			}, commerceTaxMethod);

		commerceTaxMethod.resetOriginalValues();
	}

public void marshall(ElastiCacheInstanceDetails elastiCacheInstanceDetails, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getNodeType(), NODETYPE_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getProductDescription(), PRODUCTDESCRIPTION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
_filename is not used
            Args:
                _filename(string)

def output(self, _filename):

        for contract in self.slither.contracts_derived:
            txt = "\nContract %s"%contract.name
            table = PrettyTable(["Function",
                                 "require or assert"])
            for function in contract.functions:
                require = function.all_slithir_operations()
                require = [ir for ir in require if isinstance(ir, SolidityCall) and ir.function in require_or_assert]
                require = [ir.node for ir in require]
                table.add_row([function.name, self._convert([str(m.expression) for m in set(require)])])
            txt += "\n"+str(table)
            self.info(txt)

def _ParseShellItemPathSegment(self, shell_item):

    path_segment = None

    if isinstance(shell_item, pyfwsi.root_folder):
      description = shell_folder_ids.DESCRIPTIONS.get(
          shell_item.shell_folder_identifier, None)

      if description:
        path_segment = description
      else:
        path_segment = '{{{0:s}}}'.format(shell_item.shell_folder_identifier)

      path_segment = '<{0:s}>'.format(path_segment)

    elif isinstance(shell_item, pyfwsi.volume):
      if shell_item.name:
        path_segment = shell_item.name
      elif shell_item.identifier:
        path_segment = '{{{0:s}}}'.format(shell_item.identifier)

    elif isinstance(shell_item, pyfwsi.file_entry):
      long_name = ''
      for extension_block in shell_item.extension_blocks:
        if isinstance(extension_block, pyfwsi.file_entry_extension):
          long_name = extension_block.long_name

      if long_name:
        path_segment = long_name
      elif shell_item.name:
        path_segment = shell_item.name

    elif isinstance(shell_item, pyfwsi.network_location):
      if shell_item.location:
        path_segment = shell_item.location

    if path_segment is None and shell_item.class_type == 0x00:
      # TODO: check for signature 0x23febbee
      pass

    if path_segment is None:
      path_segment = '<UNKNOWN: 0x{0:02x}>'.format(shell_item.class_type)

    return path_segment

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


Question:
Return only those items which exist in both lists.

@param array $listToClean All fields.

@return array

public function filterByUpdatableFields(array $listToClean)
    {
        $allowedFields = $this->updatableFields->getUpdatableFields();

        $cleanedList = $listToClean;
        if ($allowedFields->count() > 0) {
            $cleanedList = $this->filterFieldsByWhiteList($allowedFields, $listToClean);
        }

        return $cleanedList;
    }

public function handle()
    {
        if (! Schema::hasTable('carts')) {
            $this->error('No carts table found.');
            exit;
        }

        $this->comment('Cleaning carts data...');

        $validHours = config('cart_manager.cart_data_validity');

        $query = Cart::where('updated_at', '<', Carbon::now()->subHours($validHours));

        $cartIds = $query->get(['id']);

        if ($cartIds->isNotEmpty()) {
            $cartsDeleted = $query->delete();

            CartItem::whereIn('cart_id', $cartIds->pluck('id')->toArray())->delete();

            $this->info("$cartsDeleted older cart record(s) removed from the table.");
        } else {
            $this->info('No older cart records found.');
        }

        $this->comment('Task complete.');
    }

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


Question: // BuildTagsURL constructs a url to list the tags in the named repository.

func (ub *URLBuilder) BuildTagsURL(name reference.Named) (string, error) {
	route := ub.cloneRoute(RouteNameTags)

	tagsURL, err := route.URL("name", name.Name())
	if err != nil {
		return "", err
	}

	return tagsURL.String(), nil
}

public function getRelatedUrl(string $propertyName) : string
    {
        return (!empty($this->relationshipSelfUrl[$propertyName]['related']))
            ? $this->relationshipSelfUrl[$propertyName]['related']
            : '';
    }

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


Question: // Exists returns true if the given id is registered with this driver.

func (d *Driver) Exists(id string) bool {
	_, err := os.Lstat(d.dir(id))
	logrus.Debugf("lcowdriver: exists: id %s %t", id, err == nil)
	return err == nil
}

public static void assureServerExist(final Server server, final String serverId) throws MojoExecutionException {
        if (server == null) {
            throw new MojoExecutionException(String.format("Server not found in settings.xml. ServerId=%s", serverId));
        }
    }

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


Question:
@param  Schema $schema

@return bool

protected function execSchema(Schema $schema)
    {
        $query = $schema->build($this->database);

        return $this->database->exec(trim($query));
    }

func (s *DescribeDBParameterGroupsOutput) SetDBParameterGroups(v []*DBParameterGroup) *DescribeDBParameterGroupsOutput {
	s.DBParameterGroups = v
	return s
}

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


Question:
Directory size

@access public

@param string $dirName directory name

@return integer
@static

public static function dirSize($dirName)
    {
        $totalSize = 0;
        if ($dirStream = opendir($dirName)) {
            while (false !== ($fileName = readdir($dirStream))) {
                if ($fileName !== '.' && $fileName !== '..') {
                    if (is_file($dirName.'/'.$fileName)) {
                        $totalSize += filesize($dirName.'/'.$fileName);
                    }

                    if (is_dir($dirName.'/'.$fileName)) {
                        $totalSize += self::dirSize($dirName.'/'.$fileName);
                    }
                }
            }
        }

        closedir($dirStream);

        return $totalSize;
    }

func (p *Parameter) StoreStrLen_or_IndPtr(v api.SQLLEN) *api.SQLLEN {
	p.StrLen_or_IndPtr = v
	return &p.StrLen_or_IndPtr

}

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


Question:
// ClientHandshake is not implemented for a `serverTransportCredentials`, use
// a `clientTransportCredentials` if you require `ClientHandshake`.

func (tc *serverTransportCredentials) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	return nil, nil, ClientHandshakeNopErr
}

func Register(controller string, username string, password string, email string,
	sslVerify bool) error {

	u, err := url.Parse(controller)
	httpClient := client.CreateHTTPClient(sslVerify)

	if err != nil {
		return err
	}

	controllerURL, err := chooseScheme(*u)

	if err != nil {
		return err
	}

	if err = client.CheckConnection(httpClient, controllerURL); err != nil {
		return err
	}

	if username == "" {
		fmt.Print("username: ")
		fmt.Scanln(&username)
	}

	if password == "" {
		fmt.Print("password: ")
		password, err = readPassword()
		fmt.Printf("\npassword (confirm): ")
		passwordConfirm, err := readPassword()
		fmt.Println()

		if err != nil {
			return err
		}

		if password != passwordConfirm {
			return errors.New("Password mismatch, aborting registration.")
		}
	}

	if email == "" {
		fmt.Print("email: ")
		fmt.Scanln(&email)
	}

	c := &client.Client{ControllerURL: controllerURL, SSLVerify: sslVerify, HTTPClient: httpClient}

	tempClient, err := client.New()

	if err == nil {
		c.Token = tempClient.Token
	}

	err = auth.Register(c, username, password, email)

	c.Token = ""

	if err != nil {
		fmt.Fprint(os.Stderr, "Registration failed: ")
		return err
	}

	fmt.Printf("Registered %s\n", username)
	return doLogin(c, username, password)
}

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


Question: Converts rdata to a String

String
rrToString()
{
	StringBuffer sb = new StringBuffer();
	sb.append(next);
	if (!types.empty()) {
		sb.append(' ');
		sb.append(types.toString());
	}
	return sb.toString();
}

public function exec($command)
    {
        if (!$this->connected) {
            throw new NotAuthenticatedException('Client has not connected to the Rcon server.');
        }

        $this->write(self::SERVERDATA_EXECCOMMAND, $command);

        return $this->read()[0]['S1'];
    }

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


Question:
/*!
Returns the content.

function objectAttributeContent( $contentObjectAttribute )
    {
        $value = $contentObjectAttribute->attribute( 'data_text' );

        $countryList = explode( ',', $value );
        $resultList = array();
        foreach ( $countryList as $alpha2 )
        {
            $eZCountry = eZCountryType::fetchCountry( $alpha2, 'Alpha2' );
            $resultList[$alpha2] = $eZCountry ? $eZCountry : '';
        }
        // Supporting of previous version format.
        // For backwards compatibility.
        if ( count( $resultList ) == 1 and $resultList[$value] == '' )
            $resultList = $value;

        $content = array( 'value' => $resultList );
        return $content;
    }

def _parseIsComment(self):

        self._iscomment = (
            self._element.startswith("<!--") and self._element.endswith("-->")
        )

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


Question:
Identify the type of hash in a hash string.

    Args:
      hash_str: A string value that may be a hash.

    Returns:
      A string description of the type of hash.

def GetHashType(self, hash_str):

    # Return the type of the first matching hash.
    for hash_type, hash_re in self.hashes:
      if hash_re.match(hash_str):
        return hash_type
    # No hash matched.
    return "EMPTY"

def color=(hex)
      valid_colors = Type::Color.constants.map { |c| Type::Color.const_get(c) }
      unless hex.nil? || valid_colors.include?(hex.to_s.downcase)
        raise ArgumentError, "Unable to set color to an invalid color.\nUse one of #{valid_colors}"
      end

      @color = hex
    end

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


Question:
Add to pathlist Python library paths to be skipped from module
        reloading.

def create_pathlist(self, initial_pathlist):

        # Get standard installation paths
        try:
            paths = sysconfig.get_paths()
            standard_paths = [paths['stdlib'],
                              paths['purelib'],
                              paths['scripts'],
                              paths['data']]
        except Exception:
            standard_paths = []

        # Get user installation path
        # See Spyder issue 8776
        try:
            import site
            if getattr(site, 'getusersitepackages', False):
                # Virtualenvs don't have this function but
                # conda envs do
                user_path = [site.getusersitepackages()]
            elif getattr(site, 'USER_SITE', False):
                # However, it seems virtualenvs have this
                # constant
                user_path = [site.USER_SITE]
            else:
                user_path = []
        except Exception:
            user_path = []

        return initial_pathlist + standard_paths + user_path

def clean(docs=False, bytecode=False, extra=''):
    ''''''
    patterns = ['build', 'dist', 'cover', 'docs/_build', '**/*.pyc', '*.egg-info', '.tox', '**/__pycache__']
    for pattern in patterns:
        print('Removing {0}'.format(pattern))
        lrun('rm -rf {0}'.format(pattern))

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


Question: // CREATE REST call

func httpCreatePolicy(w http.ResponseWriter, r *http.Request, vars map[string]string) (interface{}, error) {
	log.Debugf("Received httpGetPolicy: %+v", vars)

	var obj Policy
	key := vars["key"]

	// Get object from the request
	err := json.NewDecoder(r.Body).Decode(&obj)
	if err != nil {
		log.Errorf("Error decoding policy create request. Err %v", err)
		return nil, err
	}

	// set the key
	obj.Key = key

	// Create the object
	err = CreatePolicy(&obj)
	if err != nil {
		log.Errorf("CreatePolicy error for: %+v. Err: %v", obj, err)
		return nil, err
	}

	// Return the obj
	return obj, nil
}

def processRequest(cls, ps, **kw):

        resource = kw['resource']
        request = kw['request']
        method =  getattr(resource, 'soap_%s' %
                           _get_element_nsuri_name(ps.body_root)[-1])

        try:
            req,rsp = method(ps, request=request)
        except Exception, ex:
            raise

        return rsp

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


Question: return an astroid.Getattr node as string

def visit_attribute(self, node):
        """"""
        return "%s.%s" % (self._precedence_parens(node, node.expr), node.attrname)

def _parse(self):

        responses = []
        for child in self._element:
            weight = int_attribute(child, 'weight', 1)
            self._log.debug('Parsing random entry with weight {weight}: {entry}'
                            .format(weight=weight, entry=child.text))

            # If the random element doesn't contain any tags, just store the text and return
            if not len(child):
                responses.append((child.text, weight))
                continue

            # Otherwise, parse all the available tags
            responses.append((tuple(self.trigger.agentml.parse_tags(child, self.trigger)), weight))
        self._responses = tuple(responses)

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


Question: Deserialize a DataONE Exception XML doc.

def deserialize(dataone_exception_xml):
    """"""
    # logging.debug('dataone_exception_xml="{}"'
    # .format(d1_common.xml.pretty_xml(dataone_exception_xml)))
    try:
        dataone_exception_pyxb = d1_common.xml.deserialize_d1_exception(
            dataone_exception_xml
        )
    except ValueError as e:
        raise ServiceFailure(
            detailCode='0',
            description='Deserialization failed. error="{}" doc="{}"'.format(
                str(e),
                '<empty response>'
                if not dataone_exception_xml
                else dataone_exception_xml,
            ),
            traceInformation=traceback.format_exc(),
        )
    else:
        x = create_exception_by_name(
            dataone_exception_pyxb.name,
            dataone_exception_pyxb.detailCode,
            dataone_exception_pyxb.description,
            _get_trace_information_content(dataone_exception_pyxb),
            dataone_exception_pyxb.identifier,
            dataone_exception_pyxb.nodeId,
        )
        return x

public function saveOrder($serialize)
    {
        $tree = json_decode($serialize, true);

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new \InvalidArgumentException(json_last_error_msg());
        }

        $this->model->saveOrder($tree);

        return true;
    }

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


Question:
Provided with a $response from callbacks convert it into a JavaScript code.

@param array|jsExpressionable $response response from callbacks,
@param string                 $chain    JavaScript string

public function getAjaxec($response, $chain = null)
    {
        if (is_array($response) && $response[0] instanceof View) {
            $response = $response[0];
        }

        if ($response instanceof View) {
            $response = new jsExpression('$([html]).modal("show")', [
                        'html' => '

 '.
                        $response->render()
                        .'

',
                    ]);
        }

        if ($response === $chain) {
            $response = null;
        }

        $actions = [];

        if ($chain && $chain->_chain) {
            $actions[] = $chain;
        }

        $response = $this->flatternArray($response);

        foreach ($response as $r) {
            if (is_string($r)) {
                $actions[] = new jsExpression('alert([])', [$r]);
            } elseif ($r instanceof jsExpressionable) {
                $actions[] = $r;
            } elseif ($r === null) {
                continue;
            } else {
                throw new Exception(['Incorrect callback. Must be string or action.', 'r' => $r]);
            }
        }

        $ajaxec = implode(";\n", array_map(function (jsExpressionable $r) {
            return $r->jsRender();
        }, $actions));

        return $ajaxec;
    }

function erroz(error) {

    var errorFn = function (data) {

        //apply all attributes on the instance
        for (var errKey in errorFn.prototype) {
            if (errorFn.prototype.hasOwnProperty(errKey)) {
                this[errKey] = errorFn.prototype[errKey];
            }
        }

        //overwrite message if invoked with string
        if (typeof data === "string") {
            this.message = data;
            data = {};
        }

        this.data = data || {};

        this.message = this.message || erroz.options.renderMessage(error.template || "", this.data);

        errorFn.super_.call(this, this.constructor);
    };

    util.inherits(errorFn, AbstractError);

    //add static error properties (name, status, etc)
    for (var errKey in error) {
        if (error.hasOwnProperty(errKey)) {
            errorFn.prototype[errKey] = error[errKey];
        }
    }

    /**
     * return an object containing only JSend attributes
     * @returns {{status: *, code: *, message: *, data: (*|string|Object[]|Object|String)}}
     */
    errorFn.prototype.toJSend = function () {
        var data = this.data;

        if (erroz.options.includeStack && this.stack) {
            data.stack = this.stack;
        }

        if (!this.status) {
            this.status = deriveStatusFromStatusCode(this.statusCode);
        }

        return {
            status: this.status,
            code: this.code,
            message: this.message,
            data: data
        };
    };

    return errorFn;
}

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


Question: JoinedStr(expr* values)

def visit_JoinedStr(self, node):

        self.result += "f\'"
        self.visit_joined_str(node)
        self.result += "'"

def format_prettytable(table):
    """"""
    for i, row in enumerate(table.rows):
        for j, item in enumerate(row):
            table.rows[i][j] = format_output(item)

    ptable = table.prettytable()
    ptable.hrules = prettytable.FRAME
    ptable.horizontal_char = '.'
    ptable.vertical_char = ':'
    ptable.junction_char = ':'
    return ptable

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


Question: Sets up the {@link RecyclerView} that is used to display the turn lanes.

private void initializeTurnLaneRecyclerView() {
    turnLaneAdapter = new TurnLaneAdapter();
    rvTurnLanes.setAdapter(turnLaneAdapter);
    rvTurnLanes.setHasFixedSize(true);
    rvTurnLanes.setLayoutManager(new LinearLayoutManager(getContext(),
      LinearLayoutManager.HORIZONTAL, false));
  }

def put(self, targetId):

        json = request.get_json()
        if 'hinge' in json:
            logger.info('Storing target ' + targetId)
            if self._targetController.storeFromHinge(targetId, json['hinge']):
                logger.info('Stored target ' + targetId)
                return None, 200
            else:
                return None, 500
        else:
            return None, 400

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


Question:
Returns the tool types.

@param bool $orphanedonly Retrieve only tool proxies that do not have a corresponding tool type
@return array of tool types
@since Moodle 3.1
@throws moodle_exception

public static function get_tool_proxies($orphanedonly) {
        global $PAGE;
        $params = self::validate_parameters(self::get_tool_proxies_parameters(),
                                            array(
                                                'orphanedonly' => $orphanedonly
                                            ));
        $orphanedonly = $params['orphanedonly'];

        $proxies = array();
        $context = context_system::instance();

        self::validate_context($context);
        require_capability('moodle/site:config', $context);

        $proxies = lti_get_tool_proxies($orphanedonly);

        return array_map('serialise_tool_proxy', $proxies);
    }

public function render_backup_files_viewer(backup_files_viewer $viewer) {
        global $CFG;
        $files = $viewer->files;

        $async = async_helper::is_async_enabled();

        $tablehead = array(
                get_string('filename', 'backup'),
                get_string('time'),
                get_string('size'),
                get_string('download'),
                get_string('restore'));
        if ($async) {
            $tablehead[] = get_string('status', 'backup');
        }

        $table = new html_table();
        $table->attributes['class'] = 'backup-files-table generaltable';
        $table->head = $tablehead;
        $table->width = '100%';
        $table->data = array();

        // First add in progress asynchronous backups.
        // Only if asynchronous backups are enabled.
        // Also only render async status in correct area. Courese OR activity (not both).
        if ($async
                && (($viewer->filearea == 'course' && $viewer->currentcontext->contextlevel == CONTEXT_COURSE)
                || ($viewer->filearea == 'activity' && $viewer->currentcontext->contextlevel == CONTEXT_MODULE))
                ) {
                    $table->data = \async_helper::get_async_backups($this, $viewer->currentcontext->instanceid);
        }

        // Add completed backups.
        foreach ($files as $file) {
            if ($file->is_directory()) {
                continue;
            }
            $fileurl = moodle_url::make_pluginfile_url(
                $file->get_contextid(),
                $file->get_component(),
                $file->get_filearea(),
                null,
                $file->get_filepath(),
                $file->get_filename(),
                true
            );
            $params = array();
            $params['action'] = 'choosebackupfile';
            $params['filename'] = $file->get_filename();
            $params['filepath'] = $file->get_filepath();
            $params['component'] = $file->get_component();
            $params['filearea'] = $file->get_filearea();
            $params['filecontextid'] = $file->get_contextid();
            $params['contextid'] = $viewer->currentcontext->id;
            $params['itemid'] = $file->get_itemid();
            $restoreurl = new moodle_url('/backup/restorefile.php', $params);
            $restorelink = html_writer::link($restoreurl, get_string('restore'));
            $downloadlink = html_writer::link($fileurl, get_string('download'));

            // Conditional display of the restore and download links, initially only for the 'automated' filearea.
            if ($params['filearea'] == 'automated') {
                if (!has_capability('moodle/restore:viewautomatedfilearea', $viewer->currentcontext)) {
                    $restorelink = '';
                }
                if (!can_download_from_backup_filearea($params['filearea'], $viewer->currentcontext)) {
                    $downloadlink = '';
                }
            }
            $tabledata = array(
                $file->get_filename(),
                userdate ($file->get_timemodified()),
                display_size ($file->get_filesize()),
                $downloadlink,
                $restorelink
            );
            if ($async) {
                $tabledata[] = $this->get_status_display(backup::STATUS_FINISHED_OK, null);
            }

            $table->data[] = $tabledata;
        }

        $html = html_writer::table($table);

        // For automated backups, the ability to manage backup files is controlled by the ability to download them.
        // All files must be from the same file area in a backup_files_viewer.
        $canmanagebackups = true;
        if ($viewer->filearea == 'automated') {
            if (!can_download_from_backup_filearea($viewer->filearea, $viewer->currentcontext)) {
                $canmanagebackups = false;
            }
        }

        if ($canmanagebackups) {
            $html .= $this->output->single_button(
                new moodle_url('/backup/backupfilesedit.php', array(
                        'currentcontext' => $viewer->currentcontext->id,
                        'contextid' => $viewer->filecontext->id,
                        'filearea' => $viewer->filearea,
                        'component' => $viewer->component,
                        'returnurl' => $this->page->url->out())
                ),
                get_string('managefiles', 'backup'),
                'post'
            );
        }

        return $html;
    }

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


Question:
Set filename

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2013-11-22

@param  string $filename

@return Image

public function setFilename($filename = null)
    {
        $this->filename = $filename;

        $sub_dir = '';
        $sub_dir .= substr($filename, 0, 2).DIRECTORY_SEPARATOR;
        $sub_dir .= substr($filename, 2, 2).DIRECTORY_SEPARATOR;
        $sub_dir .= substr($filename, 4, 2);

        $this->setSubDir($sub_dir);
        $this->setPath($sub_dir.DIRECTORY_SEPARATOR.$filename);

        return $this;
    }

def define(args, &task_block)
      desc "Generate a Changelog from GitHub"

      yield(*[self, args].slice(0, task_block.arity)) if task_block

      # clear any (auto-)pre-existing task
      Rake::Task[@name].clear if Rake::Task.task_defined?(@name)

      task @name do
        # mimick parse_options
        options = Parser.default_options

        OPTIONS.each do |o|
          v = instance_variable_get("@#{o}")
          options[o.to_sym] = v unless v.nil?
        end
        abort "user and project are required." unless options[:user] && options[:project]
        generator = Generator.new options

        log = generator.compound_changelog

        output_filename = (options[:output]).to_s
        File.open(output_filename, "w") { |file| file.write(log) }
        puts "Done!"
        puts "Generated log placed in #{Dir.pwd}/#{output_filename}"
      end
    end

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


Question:
Compile a select query into SQL

@param  Builder  $query

@return  string

public function compileSelect(Builder $query) {
    $this->beforeGet($query);
    return $this->grammar->compileSelect($query);
  }

func (p *LogicalJoin) constructInnerTableScan(ds *DataSource, pk *expression.Column, outerJoinKeys []*expression.Column, us *LogicalUnionScan) PhysicalPlan {
	ranges := ranger.FullIntRange(mysql.HasUnsignedFlag(pk.RetType.Flag))
	ts := PhysicalTableScan{
		Table:           ds.tableInfo,
		Columns:         ds.Columns,
		TableAsName:     ds.TableAsName,
		DBName:          ds.DBName,
		filterCondition: ds.pushedDownConds,
		Ranges:          ranges,
		rangeDecidedBy:  outerJoinKeys,
	}.Init(ds.ctx)
	ts.SetSchema(ds.schema)

	ts.stats = property.NewSimpleStats(1)
	ts.stats.StatsVersion = ds.statisticTable.Version
	if ds.statisticTable.Pseudo {
		ts.stats.StatsVersion = statistics.PseudoVersion
	}

	copTask := &copTask{
		tablePlan:         ts,
		indexPlanFinished: true,
	}
	selStats := ts.stats.Scale(selectionFactor)
	ts.addPushedDownSelection(copTask, selStats)
	t := finishCopTask(ds.ctx, copTask)
	reader := t.plan()
	return p.constructInnerUnionScan(us, reader)
}

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


Question:
Execute the console command.
@param Input  $input
@param Output $output
@return int|null|void

public function execute(Input $input, Output $output)
    {
        $connector = $input->getArgument('connector') ?: $this->app->config->get('queue.connector', 'sync');

        $queue = $input->getOption('queue') ?: $this->app->config->get("queue.{$connector}", 'default');
        $delay = $input->getOption('delay');
        $sleep = $input->getOption('sleep');
        $tries = $input->getOption('tries');

        $this->listenForEvents();

        if ($input->getOption('once')) {
            $this->worker->runNextJob($connector, $queue, $delay, $sleep, $tries);
        } else {
            $memory  = $input->getOption('memory');
            $timeout = $input->getOption('timeout');
            $this->worker->daemon($connector, $queue, $delay, $sleep, $tries, $memory, $timeout);
        }
    }

function run(cmd){

        var proc = require('child_process'),
            done = grunt.task.current.async(); // Tells Grunt that an async task is complete

        proc.exec(cmd,
            function(error, stdout, stderr){
                if(stderr){
                    grunt.log.writeln('ERROR: ' + stderr).error();
                }
                grunt.log.writeln(stdout);
                done(error);
            }
        );
    }

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


Question: Chart for most visited pages legend.

def most_visited_pages_legend_chart():
    """"""
    return {
        'chart': {
            'type': 'bar',
            'height': 200,
        },
        'title': {
            'text': _('Legend')
        },
        'xAxis': {
            'categories': [
                _('Project URL'),
                _('Old project URL'),
                _('Asset URL'),
                _('Old asset URL'),
                _('Common asset URL'),
                _('False-negative project URL'),
                _('Suspicious URL (potential attack)')
            ],
            'title': {
                'text': None
            }
        },
        'yAxis': {
            'title': {
                'text': None,
                'align': 'high'
            },
            'labels': {
                'overflow': 'justify'
            }
        },
        'tooltip': {
            'enabled': False
        },
        'legend': {
            'enabled': False
        },
        'credits': {
            'enabled': False
        },
        'series': [{
            'name': _('Legend'),
            'data': [
                {'color': URL_TYPE_COLOR[PROJECT], 'y': 1},
                {'color': URL_TYPE_COLOR[OLD_PROJECT], 'y': 1},
                {'color': URL_TYPE_COLOR[ASSET], 'y': 1},
                {'color': URL_TYPE_COLOR[OLD_ASSET], 'y': 1},
                {'color': URL_TYPE_COLOR[COMMON_ASSET], 'y': 1},
                {'color': URL_TYPE_COLOR[FALSE_NEGATIVE], 'y': 1},
                {'color': URL_TYPE_COLOR[SUSPICIOUS], 'y': 1},
            ]
        }]
    }

def comicDownloaded(self, comic, filename, text=None):
        """"""
        pageInfo = self.getPageInfo(comic.name, comic.referrer)
        pageInfo['images'][comic.url] = os.path.basename(filename)

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


Question:
Hidden attribute setter and checker

Accepts parameter "null", "0" and "1".
"null" eg no parameter means to check for a set hidden attribute
"0" means to remove hidden attribute
"1" means to set hidden attribute

@param int $state

public function isHidden(int $state = null)
    {
        $attrib = 'hidden';

        if (empty($state)) {
            return $this->checkAttribute($attrib);
        }

        if ($state == 0) {
            $this->removeAttribute($attrib);
        }
        else {
            $this->addAttribute($attrib);
        }
    }

protected function get_registered_options() {
		$rest_options = array();

		foreach ( get_registered_settings() as $name => $args ) {
			if ( empty( $args['show_in_rest'] ) ) {
				continue;
			}

			$rest_args = array();
			if ( is_array( $args['show_in_rest'] ) ) {
				$rest_args = $args['show_in_rest'];
			}

			$defaults = array(
				'name'   => ! empty( $rest_args['name'] ) ? $rest_args['name'] : $name,
				'schema' => array(),
			);
			$rest_args = array_merge( $defaults, $rest_args );

			$default_schema = array(
				'type'        => empty( $args['type'] ) ? null : $args['type'],
				'description' => empty( $args['description'] ) ? '' : $args['description'],
				'default'     => isset( $args['default'] ) ? $args['default'] : null,
			);

			$rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
			$rest_args['option_name'] = $name;

			// Skip over settings that don't have a defined type in the schema.
			if ( empty( $rest_args['schema']['type'] ) ) {
				continue;
			}

			// Whitelist the supported types for settings, as we don't want invalid types
			// to be updated with arbitrary values that we can't do decent sanitizing for.
			if ( ! in_array( $rest_args['schema']['type'], array( 'number', 'string', 'boolean' ), true ) ) {
				continue;
			}

			$rest_options[ $rest_args['name'] ] = $rest_args;
		}

		return $rest_options;
	}

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


Question: // Determines if two types can be automatically converted between.

func areTypesCompatible(xt, yt reflect.Type) bool {
	return xt.AssignableTo(unhackType(yt)) || yt.AssignableTo(unhackType(xt))
}

private static Class<? extends HelpViewBase> getViewClass(HelpViewType viewType) {
        switch (viewType) {
            case TOC:
                return HelpViewContents.class;

            case KEYWORD:
                return HelpViewIndex.class;

            case INDEX:
                return HelpViewIndex.class;

            case SEARCH:
                return HelpViewSearch.class;

            case HISTORY:
                return HelpViewHistory.class;

            case GLOSSARY:
                return HelpViewIndex.class;

            default:
                return null;
        }
    }

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


Question:
Synchronize tables.

@throws \Throwable

public function run()
    {
        $hasChanges = false;
        foreach ($this->tables as $table) {
            if (
                $table->getComparator()->hasChanges()
                || $table->getStatus() == AbstractTable::STATUS_DECLARED_DROPPED
            ) {
                $hasChanges = true;
                break;
            }
        }

        if (!$hasChanges) {
            //Nothing to do
            return;
        }

        $this->beginTransaction();

        try {
            //Drop not-needed foreign keys and alter everything else
            $this->dropForeignKeys();

            //Drop not-needed indexes
            $this->dropIndexes();

            //Other changes [NEW TABLES WILL BE CREATED HERE!]
            foreach ($this->commitChanges() as $table) {
                $table->save(HandlerInterface::CREATE_FOREIGN_KEYS, true);
            }
        } catch (\Throwable $e) {
            $this->rollbackTransaction();
            throw $e;
        }

        $this->commitTransaction();
    }

public function setModel($model)
	{
		$this->model = $model;

		$this->from($this->model->metableTable() . ' AS m');

		if ($this->model->metableTableSoftDeletes()) {
			$this->whereNull('m.' . $this->model->getDeletedAtColumn());
		}

		return $this;
	}

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


Question:
Add role override if exists

@param RoleInterface|string     $role      Role name or object
@param ResourceCollection|array $resources Role resources

public function addRole($role, array $resources = [])
    {
        if ($role instanceof RoleInterface) {
            $this->roles[$role->getName()] = $role;
        } else {
            $role = new Role($role, $resources);
            $this->roles[$role->getName()] = $role;
        }
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question: Return the Spec for ApicalTMSequenceRegion.

def getSpec(cls):

    spec = {
      "description": ApicalTMSequenceRegion.__doc__,
      "singleNodeOnly": True,
      "inputs": {
        "activeColumns": {
          "description": ("An array of 0's and 1's representing the active "
                          "minicolumns, i.e. the input to the TemporalMemory"),
          "dataType": "Real32",
          "count": 0,
          "required": True,
          "regionLevel": True,
          "isDefaultInput": True,
          "requireSplitterMap": False
        },
        "resetIn": {
          "description": ("A boolean flag that indicates whether"
                          " or not the input vector received in this compute cycle"
                          " represents the first presentation in a"
                          " new temporal sequence."),
          "dataType": "Real32",
          "count": 1,
          "required": False,
          "regionLevel": True,
          "isDefaultInput": False,
          "requireSplitterMap": False
        },
        "apicalInput": {
          "description": "An array of 0's and 1's representing top down input."
          " The input will be provided to apical dendrites.",
          "dataType": "Real32",
          "count": 0,
          "required": False,
          "regionLevel": True,
          "isDefaultInput": False,
          "requireSplitterMap": False
        },
        "apicalGrowthCandidates": {
          "description": ("An array of 0's and 1's representing apical input "
                          "that can be learned on new synapses on apical "
                          "segments. If this input is a length-0 array, the "
                          "whole apicalInput is used."),
          "dataType": "Real32",
          "count": 0,
          "required": False,
          "regionLevel": True,
          "isDefaultInput": False,
          "requireSplitterMap": False
        },
      },
      "outputs": {
        "nextPredictedCells": {
          "description": ("A binary output containing a 1 for every "
                          "cell that is predicted for the next timestep."),
          "dataType": "Real32",
          "count": 0,
          "regionLevel": True,
          "isDefaultOutput": False
        },

        "predictedActiveCells": {
          "description": ("A binary output containing a 1 for every "
                          "cell that transitioned from predicted to active."),
          "dataType": "Real32",
          "count": 0,
          "regionLevel": True,
          "isDefaultOutput": False
        },

        "activeCells": {
          "description": ("A binary output containing a 1 for every "
                          "cell that is currently active."),
          "dataType": "Real32",
          "count": 0,
          "regionLevel": True,
          "isDefaultOutput": True
        },

        "winnerCells": {
          "description": ("A binary output containing a 1 for every "
                          "'winner' cell in the TM."),
          "dataType": "Real32",
          "count": 0,
          "regionLevel": True,
          "isDefaultOutput": False
        },
      },

      "parameters": {
        # Input sizes (the network API doesn't provide these during initialize)
        "columnCount": {
          "description": ("The size of the 'activeColumns' input " +
                          "(i.e. the number of columns)"),
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },
        "apicalInputWidth": {
          "description": "The size of the 'apicalInput' input",
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },

        "learn": {
          "description": "True if the TM should learn.",
          "accessMode": "ReadWrite",
          "dataType": "Bool",
          "count": 1,
          "defaultValue": "true"
        },
        "cellsPerColumn": {
          "description": "Number of cells per column",
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },
        "activationThreshold": {
          "description": ("If the number of active connected synapses on a "
                          "segment is at least this threshold, the segment "
                          "is said to be active."),
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },
        "reducedBasalThreshold": {
          "description": ("Activation threshold of basal segments for cells "
                          "with active apical segments (with apicalTiebreak "
                          "implementation). "),
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },
        "initialPermanence": {
          "description": "Initial permanence of a new synapse.",
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1,
          "constraints": ""
        },
        "connectedPermanence": {
          "description": ("If the permanence value for a synapse is greater "
                          "than this value, it is said to be connected."),
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1,
          "constraints": ""
        },
        "minThreshold": {
          "description": ("If the number of synapses active on a segment is at "
                          "least this threshold, it is selected as the best "
                          "matching cell in a bursting column."),
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1,
          "constraints": ""
        },
        "sampleSize": {
          "description": ("The desired number of active synapses for an " +
                          "active cell"),
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1
        },
        "learnOnOneCell": {
          "description": ("If True, the winner cell for each column will be"
                          " fixed between resets."),
          "accessMode": "Read",
          "dataType": "Bool",
          "count": 1,
          "defaultValue": "false"
        },
        "maxSynapsesPerSegment": {
          "description": "The maximum number of synapses per segment",
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1
        },
        "maxSegmentsPerCell": {
          "description": "The maximum number of segments per cell",
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1
        },
        "permanenceIncrement": {
          "description": ("Amount by which permanences of synapses are "
                          "incremented during learning."),
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1
        },
        "permanenceDecrement": {
          "description": ("Amount by which permanences of synapses are "
                          "decremented during learning."),
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1
        },
        "basalPredictedSegmentDecrement": {
          "description": ("Amount by which active permanences of synapses of "
                          "previously predicted but inactive segments are "
                          "decremented."),
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1
        },
        "apicalPredictedSegmentDecrement": {
          "description": ("Amount by which active permanences of synapses of "
                          "previously predicted but inactive segments are "
                          "decremented."),
          "accessMode": "Read",
          "dataType": "Real32",
          "count": 1
        },
        "seed": {
          "description": "Seed for the random number generator.",
          "accessMode": "Read",
          "dataType": "UInt32",
          "count": 1
        },
        "implementation": {
          "description": "Apical implementation",
          "accessMode": "Read",
          "dataType": "Byte",
          "count": 0,
          "constraints": ("enum: ApicalTiebreak, ApicalTiebreakCPP, ApicalDependent"),
          "defaultValue": "ApicalTiebreakCPP"
        },
      },
    }

    return spec

def indication(self, apdu):
        """"""
        if _debug: ServerSSM._debug("indication %r", apdu)

        if self.state == IDLE:
            self.idle(apdu)
        elif self.state == SEGMENTED_REQUEST:
            self.segmented_request(apdu)
        elif self.state == AWAIT_RESPONSE:
            self.await_response(apdu)
        elif self.state == SEGMENTED_RESPONSE:
            self.segmented_response(apdu)
        else:
            if _debug: ServerSSM._debug("    - invalid state")

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


Question:
Validate config file for missing/invalid settings.

@throws \InvalidArgumentException

protected function validateConfig()
    {
        $message = null;
        if (empty($this->config['api_key'])) {
            $message = 'Geocoder Config: Api Key is mandatory for using Google API.';
        }
        elseif (empty($this->config['request_url'])) {
            $message = 'Geocoder Config: Request URL is mandatory for using Google API.';
        }
        elseif (empty($this->config['output_format'])) {
            $message = 'Geocoder Config: Output Format is mandatory for using Google API.';
        }
        elseif ( ! in_array($this->config['output_format'], self::SUPPORTED_FORMATS)) {
            $message = 'Geocoder Config: Given Format is not supported.';
        }

        if ($message) {
            throw  new \InvalidArgumentException($message);
        }
    }

public function addConfigurationSetting($name, $value)
    {
        $this->checkConnectionUp("Cannot set configuration once a connection is made with the server.")
            ->configurator->set($name, $value);

        return $this;
    }

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


Question:
Unregister MBean.
@param bean

public void unregister(ZKMBeanInfo bean) {
        if(bean==null)
            return;
        String path=mapBean2Path.get(bean);
        try {
            unregister(path,bean);
        }
        catch (InstanceNotFoundException e) {
            LOG.warn("InstanceNotFoundException during unregister usually means more than one Zookeeper server has been running in a single JVM");
            LOG.warn("InstanceNotFoundException during unregister can be safely ignored during automated tests.");
        }
        catch (JMException e) {
            LOG.warn("Error during unregister", e);
        }
        mapBean2Path.remove(bean);
        mapName2Bean.remove(bean.getName());
    }

public function remove($key, $class = null) {

		if (isset($this->_data[$key])) {

			if (empty($class) || $this->_data[$key] instanceof $class) {
				unset($this->_data[$key]);
			}
		}

		if (isset($this->registered[$key])) {

			if (empty($class) || $class === $this->registered[$key]) {
				unset($this->registered[$key]);
			}
		}

		return $this;
	}

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


Question: // Get retrieves a Role if name exists.

func (s *RolesStore) Get(ctx context.Context, name string) (*chronograf.Role, error) {
	return s.GetF(ctx, name)
}

public function team($teamId)
	{
		$team = $this->info['teams'];
		if (isset($team[$teamId]))
		{
			return $team[$teamId];
		}

		return null;
	}

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


Question: Dynamically creates an image type handler for the specified image type

def image(image_format, doc=None):
    """"""
    @on_valid('image/{0}'.format(image_format))
    def image_handler(data, **kwargs):
        if hasattr(data, 'read'):
            return data
        elif hasattr(data, 'save'):
            output = stream()
            if introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save):
                data.save(output, format=image_format.upper())
            else:
                data.save(output)
            output.seek(0)
            return output
        elif hasattr(data, 'render'):
            return data.render()
        elif os.path.isfile(data):
            return open(data, 'rb')

    image_handler.__doc__ = doc or "{0} formatted image".format(image_format)
    return image_handler

function setRHandler($resOrigin)
    {
        if (!is_resource($resOrigin))
            throw new \InvalidArgumentException(sprintf(
                'This is not valid stream resource. given: "%s"',
                is_object($resOrigin) ? get_class($resOrigin) : gettype($resOrigin)
            ));

        $this->rHandler = $resOrigin;
        return $this;
    }

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


Question: Writes the rendered content to the output file.

def process
      FileUtils.mkdir_p(output_path.dirname)
      output_path.open('w') do |f|
        f.write render
      end
    end

public function main()
    {
        $this->out('Welcome to the Proffer shell.');
        $this->out('This shell can be used to regenerate thumbnails and cleanup unlinked images.');
        $this->hr();
        $this->out($this->OptionParser->help());
    }

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


Question: // getBlockTxTablesDefinition returns block & transaction structures

func getBlockTxTablesDefinition() types.EventTables {
	return types.EventTables{
		types.SQLBlockTableName: &types.SQLTable{
			Name: types.SQLBlockTableName,
			Columns: []*types.SQLTableColumn{
				{
					Name:    types.SQLColumnLabelHeight,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelBlockHeader,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
			},
		},

		types.SQLTxTableName: &types.SQLTable{
			Name: types.SQLTxTableName,
			Columns: []*types.SQLTableColumn{
				// transaction table
				{
					Name:    types.SQLColumnLabelHeight,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelTxHash,
					Type:    types.SQLColumnTypeVarchar,
					Length:  txs.HashLengthHex,
					Primary: true,
				},
				{
					Name:    types.SQLColumnLabelIndex,
					Type:    types.SQLColumnTypeNumeric,
					Length:  0,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelTxType,
					Type:    types.SQLColumnTypeVarchar,
					Length:  100,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelEnvelope,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelEvents,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelResult,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelReceipt,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
				{
					Name:    types.SQLColumnLabelException,
					Type:    types.SQLColumnTypeJSON,
					Primary: false,
				},
			},
		},
	}
}

def send(self, msg, timeout=None):

        arb_id = msg.arbitration_id
        if msg.is_extended_id:
            arb_id |= NC_FL_CAN_ARBID_XTD
        raw_msg = TxMessageStruct(arb_id,
                                  bool(msg.is_remote_frame),
                                  msg.dlc,
                                  CanData(*msg.data))
        nican.ncWrite(
            self.handle, ctypes.sizeof(raw_msg), ctypes.byref(raw_msg))

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


Question: // ObjectPacks returns the list of availables packfiles

func (d *DotGit) ObjectPacks() ([]plumbing.Hash, error) {
	if !d.options.ExclusiveAccess {
		return d.objectPacks()
	}

	err := d.genPackList()
	if err != nil {
		return nil, err
	}

	return d.packList, nil
}

public function output($filename, $append = false)
    {
        $this->outputTo = is_array($filename) ? $filename : [$filename];
        $this->outputMode = $append === false ? 'w' : 'a';

        return $this;
    }

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