Question:
// WriteNamespaces will writes namespaces list into graph.
//
// Deprecated: see Config.WriteNamespaces

func WriteNamespaces(w quad.Writer, n *voc.Namespaces) error {
	return global.WriteNamespaces(w, n)
}

def performance_log_message(self):
        """"""
        message = m.Message()
        table = m.Table(style_class='table table-condensed table-striped')
        row = m.Row()
        row.add(m.Cell(tr('Function'), header=True))
        row.add(m.Cell(tr('Time'), header=True))
        if setting(key='memory_profile', expected_type=bool):
            row.add(m.Cell(tr('Memory'), header=True))
        table.add(row)

        if self.performance_log is None:
            message.add(table)
            return message

        indent = -1

        def display_tree(tree, space):
            space += 1
            new_row = m.Row()

            # This is a kind of hack to display the tree with indentation
            text = '|'
            text += '*' * space

            if tree.children:
                text += '\ '
            else:
                text += '| '
            text += tree.__str__()

            busy = tr('Busy')
            new_row.add(m.Cell(text))
            time = tree.elapsed_time
            if time is None:
                time = busy
            new_row.add(m.Cell(time))
            if setting(key='memory_profile', expected_type=bool):
                memory_used = tree.memory_used
                if memory_used is None:
                    memory_used = busy
                new_row.add(m.Cell(memory_used))
            table.add(new_row)
            if tree.children:
                for child in tree.children:
                    display_tree(child, space)
            space -= 1

        # noinspection PyTypeChecker
        display_tree(self.performance_log, indent)
        message.add(table)

        return message

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


Question: // getStringValue get string value associated to a label

func getStringValue(labels map[string]string, labelName string, defaultValue string) string {
	if value, ok := labels[labelName]; ok && len(value) > 0 {
		return value
	}
	return defaultValue
}

func (s *CreateApplicationVersionInput) SetVersionLabel(v string) *CreateApplicationVersionInput {
	s.VersionLabel = &v
	return s
}

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


Question:
Read a submission from the specified file.

@param file file, must not be null
@return a submission read from the specified file
@throws IOException if an I/O error occurs

public static Submission readSubmission(final File file) throws IOException {
        checkNotNull(file);
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            return readSubmission(reader);
        }
    }

public List<SuggestedFix> drive(Scanner scanner, Pattern includeFilePattern) {
    JsFlumeCallback callback = new JsFlumeCallback(scanner, includeFilePattern);
    NodeTraversal.traverse(compiler, rootNode, callback);
    List<SuggestedFix> fixes = callback.getFixes();
    fixes.addAll(scanner.processAllMatches(callback.getMatches()));
    return fixes;
  }

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


Question: Read a 4-byte integer from string

private function fourBytesToInt($s)
	{
		return (ord($s[0]) << 24) + (ord($s[1]) << 16) + (ord($s[2]) << 8) + ord($s[3]);
	}

function clientConnectionRequestPDU(opt, cookie) {
	var self = {
		len : new type.UInt8(function() {
			return new type.Component(self).size() - 1;
		}),
		code : new type.UInt8(MessageType.X224_TPDU_CONNECTION_REQUEST, { constant : true }),
		padding : new type.Component([new type.UInt16Le(), new type.UInt16Le(), new type.UInt8()]),
		cookie : cookie || new type.Factory( function (s) {
			var offset = 0;
			while (true) {
				var token = s.buffer.readUInt16LE(s.offset + offset);
				if (token === 0x0a0d) {
					self.cookie = new type.BinaryString(null, { readLength : new type.CallableValue(offset + 2) }).read(s);
					return;
				}
				else {
					offset += 1;
				}
			}
		}, { conditional : function () {
			return self.len.value > 14;
		}}),
		protocolNeg : negotiation({ optional : true })
	};

	return new type.Component(self, opt);
}

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


Question:
@param mixed $value

@return static

public static function create($value)
    {
        $class = static::class;
        if (!array_key_exists($class, self::$instances)) {
            self::$instances[$class] = [];
        }
        if (!array_key_exists($value, self::$instances[$class])) {
            self::$instances[$class][$value] = new static($value);
        }

        return self::$instances[$class][$value];
    }

public Long getParameterTime(String name) throws RepositoryConfigurationException
   {
      try
      {
         return StringNumberParser.parseTime(getParameterValue(name));
      }
      catch (NumberFormatException e)
      {
         throw new RepositoryConfigurationException(name + ": unparseable time (as Long). " + e, e);
      }
   }

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


Question: // Geocoder constructs data geocoder

func Geocoder(addressToLocation AddressToLocation, LocationToAddress LocationToAddress) geo.Geocoder {
	return dataGeocoder{
		AddressToLocation: addressToLocation,
		LocationToAddress: LocationToAddress,
	}
}

private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) {
        return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj);
    }

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


Question:
<p>
The types of events that Amazon Pinpoint sends to the specified event destinations.
</p>

@param matchingEventTypes
The types of events that Amazon Pinpoint sends to the specified event destinations.
@see EventType

public void setMatchingEventTypes(java.util.Collection<String> matchingEventTypes) {
        if (matchingEventTypes == null) {
            this.matchingEventTypes = null;
            return;
        }

        this.matchingEventTypes = new java.util.ArrayList<String>(matchingEventTypes);
    }

void checkMEs(JsMessagingEngine[] MEList) throws ResourceException
    {
        final String methodName = "checkMEs";
        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.entry(this, TRACE, methodName, new Object[] { MEList });
        }

        // Filter out any non preferred MEs. User specified target data is used to perform this filter.
        // If no target data is set then all the MEs are considered "preferred" for point to point and
        // non durable pub sub, but none of them are considered preferred for durable pub sub (which has
        // a preference for the durable subscription home)
        JsMessagingEngine[] preferredMEs = _destinationStrategy.getPreferredLocalMEs(MEList);

        // TODO: Can we wrapper the connect call if a try catch block, if engine is being reloaded then absorb the
        // exception (trace a warning) and let us kick off a timer (if one is needed).

        // Try to connect to the list of filtered MEs.
        try {
            connect(preferredMEs, _targetType, _targetSignificance, _target, true);
            SibTr.info(TRACE, "TARGETTED_CONNECTION_SUCCESSFUL_CWSIV0556", new Object[] { ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
                                                                                _endpointConfiguration.getDestination().getDestinationName() });
        } catch (Exception e) {

            // After attempting to create connections check to see if we should continue to check for more connections
            // or not. If we should then kick of a timer to try again after a user specified interval.
            SibTr.warning(TRACE, SibTr.Suppressor.ALL_FOR_A_WHILE, "CONNECT_FAILED_CWSIV0782",
                          new Object[] { _endpointConfiguration.getDestination().getDestinationName(),
                                        _endpointConfiguration.getBusName(),
                                        ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(),
                                        e });
            if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled())
            {
                SibTr.debug(TRACE, "Failed to obtain a connection - retry after a set interval");
            }
            clearTimer();
            // deactivate will close the connections
            // The connection might be successful but session might fail due to authorization error
            // Hence before retrying, old connection must be closed
            deactivate();
            kickOffTimer();

        }

        //its possible that there was no exception thrown and connection was not successfull
        // in that case a check is made to see if an retry attempt is needed
        if (_destinationStrategy.isTimerNeeded())
        {
            clearTimer();
            kickOffTimer();
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
        {
            SibTr.exit(TRACE, methodName);
        }
    }

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


Question:
Gets a dependency locator by its name.

@param name the name of the dependency to locate.
@return the dependency locator or null if locator was not configured.

private Object find(String name) {
		if (name == null)
			throw new NullPointerException("Dependency name cannot be null");
		if (_references == null)
			throw new NullPointerException("References shall be set");

		return _dependencies.get(name);
	}

public ProjectsDetails createProjects() {
        ProjectsDetails projects = new ProjectsDetails(new ArrayList<>(), StatusCode.SUCCESS, Constants.EMPTY_STRING);
        // Use FSA a as a package manger extractor for Debian/RPM/Arch Linux/Alpine

        // Check if scanPackageManager==true - This is the first priority and overrides other scans
        if (config.isScanProjectManager()) {
            Collection<AgentProjectInfo> tempProjects = new PackageManagerExtractor().createProjects();
            ProjectsDetails projectsDetails = new ProjectsDetails(tempProjects, StatusCode.SUCCESS, Constants.EMPTY_STRING);
            String projectName = config.getRequest().getProjectName();
            addSingleProjectToProjects(projectsDetails, projectName, projects);
            return projects;
        }

        // Check if docker.scanImages==true - This scans Docker Images, and should not scan any folders, so we exit
        // after the scan is done
        if (config.isScanDockerImages()) {
            Collection<AgentProjectInfo> tempDockerProjects = new DockerResolver(config).resolveDockerImages();
            return new ProjectsDetails(tempDockerProjects, StatusCode.SUCCESS, Constants.EMPTY_STRING);
        }

        if (config.isSetUpMuiltiModuleFile()) {
            ViaMultiModuleAnalyzer viaMultiModuleAnalyzer = new ViaMultiModuleAnalyzer(config.getDependencyDirs().get(0),
                    new MavenDependencyResolver(false, new String[]{Constants.NONE}, false,
                            false, false, false), Constants.TARGET, config.getAnalyzeMultiModule());
            if (viaMultiModuleAnalyzer.getBomFiles().isEmpty()) {
                viaMultiModuleAnalyzer = new ViaMultiModuleAnalyzer(config.getDependencyDirs().get(0),
                        new GradleDependencyResolver(false, false, false, Constants.EMPTY_STRING, new String[]{Constants.NONE},
                                Constants.EMPTY_STRING, false),
                        Constants.BUILD + File.separator + Constants.LIBS, config.getAnalyzeMultiModule());
            }
            if (!viaMultiModuleAnalyzer.getBomFiles().isEmpty()) {
                viaMultiModuleAnalyzer.writeFile();
            } else {
                logger.error("Multi-module analysis could not establish the appPath based on the specified path. Please review the specified -d path.");
                Main.exit(StatusCode.ERROR.getValue());
            }
            logger.info("The multi-module analysis setup file was created successfully.");
            Main.exit(StatusCode.SUCCESS.getValue());
        }

        // Scan folders and create a project per folder
        if (projectPerSubFolder) {
            if (this.config.getSender().isEnableImpactAnalysis()) {
                logger.warn("Could not executing VIA impact analysis with the 'projectPerFolder' flag");
                return projects;
            }
            Map<String, Set<String>> appPathsToDependencyDirs = new HashMap<>();
            Set<String> setDirs = new HashSet<>(1);

            for (String directory : dependencyDirs) {
                setDirs.add(directory);
                appPathsToDependencyDirs.put(FSAConfiguration.DEFAULT_KEY, setDirs);

                ProjectsDetails projectsDetails = getProjects(Collections.singletonList(directory), appPathsToDependencyDirs);
                String projectName = new File(directory).getName();
                addSingleProjectToProjects(projectsDetails, projectName, projects);

                // return on the first project that fails
                if (!projectsDetails.getStatusCode().equals(StatusCode.SUCCESS)) {
                    // return status code if there is a failure
                    return new ProjectsDetails(new ArrayList<>(), projects.getStatusCode(), projects.getDetails());
                }
                appPathsToDependencyDirs.clear();
                setDirs.clear();
            }
            if (CollectionUtils.isEmpty(projects.getProjects())) {
                logger.warn("projectPerFolder = true, No sub-folders were found in project folder, scanning main project folder");
                projectPerSubFolder = false;
            } else {
                return projects;
            }
        }
        // Scan folders and create one project for all folders together
        if (!projectPerSubFolder) { // This 'if' is always true now, but keep it maybe we will do other checks in the future...
            projects = getProjects(dependencyDirs, config.getAppPathsToDependencyDirs());
            if (!projects.getProjects().isEmpty()) {
                AgentProjectInfo projectInfo = projects.getProjects().stream().findFirst().get();
                if (projectInfo.getCoordinates() == null) {
                    // use token or name + version
                    String projectToken = config.getRequest().getProjectToken();
                    if (StringUtils.isNotBlank(projectToken)) {
                        projectInfo.setProjectToken(projectToken);
                    } else {
                        String projectName = config.getRequest().getProjectName();
                        String projectVersion = config.getRequest().getProjectVersion();
                        projectInfo.setCoordinates(new Coordinates(null, projectName, projectVersion));
                    }
                }
            }
            return projects;
        }

        // todo: check for duplicates projects
        return projects;
    }

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


Question:
// Initialized checks if the barrier has been initialized
// and has a master key set.

func (b *AESGCMBarrier) Initialized(ctx context.Context) (bool, error) {
	// Read the keyring file
	keys, err := b.backend.List(ctx, keyringPrefix)
	if err != nil {
		return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err)
	}
	if strutil.StrListContains(keys, "keyring") {
		return true, nil
	}

	// Fallback, check for the old sentinel file
	out, err := b.backend.Get(ctx, barrierInitPath)
	if err != nil {
		return false, errwrap.Wrapf("failed to check for initialization: {{err}}", err)
	}
	return out != nil, nil
}

def auth_traps_enabled(name, status=True):
    '''

    '''
    ret = {'name': name,
           'changes': {},
           'comment': six.text_type(),
           'result': None}

    vname = 'EnableAuthenticationTraps'
    current_status = __salt__['win_snmp.get_auth_traps_enabled']()

    if status == current_status:
        ret['comment'] = '{0} already contains the provided value.'.format(vname)
        ret['result'] = True
    elif __opts__['test']:
        ret['comment'] = '{0} will be changed.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
    else:
        ret['comment'] = 'Set {0} to contain the provided value.'.format(vname)
        ret['changes'] = {'old': current_status,
                          'new': status}
        ret['result'] = __salt__['win_snmp.set_auth_traps_enabled'](status=status)

    return ret

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


Question:
Run the migrations.

@return void

public function up()
    {
        $schema = app()->make('db')->connection()->getSchemaBuilder();

        $schema->create(config('vi-kon.auth.table.users'), function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->string('remember_token')
                  ->nullable(true)
                  ->default(null);
            $table->string('home')
                  ->nullable(true)
                  ->default(null);
            $table->string('namespace')
                  ->default('');
            $table->boolean('blocked')
                  ->default(false);
            $table->boolean('static')
                  ->default(false);
            $table->boolean('hidden')
                  ->default(false);
            $table->timestamps();

            $table->unique(['username', 'namespace']);
        });
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


Question:
<p>
The IP ranges. Not applicable for stale security group rules.
</p>

@param ipRanges
The IP ranges. Not applicable for stale security group rules.

public void setIpRanges(java.util.Collection<String> ipRanges) {
        if (ipRanges == null) {
            this.ipRanges = null;
            return;
        }

        this.ipRanges = new com.amazonaws.internal.SdkInternalList<String>(ipRanges);
    }

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

        predicate.call(collection, value)
      end
    end

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


Question:
Writes the content of the specified C{s} into this buffer.

        @param s: Raw bytes

def write(self, s, size=None):

        self._buffer.write(s)
        self._len_changed = True

public Metadata readNextMetadata() throws IOException {
        Metadata metadata = null;

        boolean isLast = (bitStream.readRawUInt(Metadata.STREAM_METADATA_IS_LAST_LEN) != 0);
        int type = bitStream.readRawUInt(Metadata.STREAM_METADATA_TYPE_LEN);
        int length = bitStream.readRawUInt(Metadata.STREAM_METADATA_LENGTH_LEN);

        if (type == Metadata.METADATA_TYPE_STREAMINFO) {
        	metadata = streamInfo = new StreamInfo(bitStream, length, isLast);
            pcmProcessors.processStreamInfo((StreamInfo)metadata);
        } else if (type == Metadata.METADATA_TYPE_SEEKTABLE) {
        	metadata = seekTable = new SeekTable(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_APPLICATION) {
            metadata = new Application(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_PADDING) {
            metadata = new Padding(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_VORBIS_COMMENT) {
            metadata = vorbisComment = new VorbisComment(bitStream, length, isLast);
        } else if (type == Metadata.METADATA_TYPE_CUESHEET) {
	    metadata = new CueSheet(bitStream, length, isLast);
	} else if (type == Metadata.METADATA_TYPE_PICTURE) {
	    metadata = new Picture(bitStream, length, isLast);
        } else {
            metadata = new Unknown(bitStream, length, isLast);
        }
        frameListeners.processMetadata(metadata);
        //if (isLast) state = DECODER_SEARCH_FOR_FRAME_SYNC;
        return metadata;
    }

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


Question:
@param $transactionId
@param $type

@return bool
@throws \Doctrine\ORM\NonUniqueResultException

public function isDonateAlreadyAdded($transactionId, $type)
    {
        if (!$transactionId) {
            return false;
        }

        $query = $this->createQueryBuilder('p')
            ->select('p')
            ->where('p.transactionId = :transactionId')
            ->setParameter('transactionId', $transactionId)
            ->andWhere('p.type = :type')
            ->setParameter('type', $type)
            ->andWhere('p.success = :success')
            ->setParameter('success', Entity::STATUS_SUCCESS)
            ->setMaxResults(1)
            ->getQuery();

        return (bool)$query->getOneOrNullResult($query::HYDRATE_SIMPLEOBJECT);
    }

public function changeAction(ChangeCollection $changes)
    {
        try {
            $count = $changes->count();
            $changes->apply();

            $success = new Info();
            $success->setMessage(sprintf('%d change(s) successfully applied.', $count));

            $this->feedbackCollection->add($success);
            $this->persistenceManager->persistAll();
        } catch (\Exception $e) {
            $error = new Error();
            $error->setMessage($e->getMessage());

            $this->feedbackCollection->add($error);
        }

        $this->view->assign('value', $this->feedbackCollection);
    }

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


Question:
Verifies that a webelement previously found {@code isEnabled}

@param index
@param isEnabled

@Then("^the element on index '(\\d+?)' (IS|IS NOT) enabled$")
    public void assertSeleniumIsEnabled(Integer index, Boolean isEnabled) {
        assertThat(this.commonspec, commonspec.getPreviousWebElements()).as("There are less found elements than required")
                .hasAtLeast(index);
        assertThat(this.commonspec, commonspec.getPreviousWebElements().getPreviousWebElements().get(index).isEnabled())
                .as("Unexpected element enabled property").isEqualTo(isEnabled);
    }

def _wrapper_enabled?
        return false unless request.has_content_type?

        ref = request.content_mime_type.ref
        _wrapper_formats.include?(ref) && _wrapper_key && !request.parameters.key?(_wrapper_key)
      end

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


Question:
// Refresh performs a Refresh on the proper resource type.
//
// Refresh on the Resource won't be called if the state represents a
// non-created resource (ID is blank).
//
// An error is returned if the resource isn't registered.

func (m *Map) Refresh(
	info *terraform.InstanceInfo,
	s *terraform.InstanceState,
	meta interface{}) (*terraform.InstanceState, error) {
	// If the resource isn't created, don't refresh.
	if s.ID == "" {
		return s, nil
	}

	r, ok := m.Mapping[info.Type]
	if !ok {
		return nil, fmt.Errorf("Unknown resource type: %s", info.Type)
	}

	return r.Refresh(s, meta)
}

public function redirectLocation(Request $request)
    {
        if ($request->query->has('id')) {
            $location = $this->locationService->loadLocation($request->query->get('id'));
        } elseif ($request->query->has('remoteId')) {
            $location = $this->locationService->loadLocationByRemoteId($request->query->get('remoteId'));
        } elseif ($request->query->has('urlAlias')) {
            $urlAlias = $this->urlAliasService->lookup($request->query->get('urlAlias'));
            $location = $this->locationService->loadLocation($urlAlias->destination);
        } else {
            throw new BadRequestException("At least one of 'id', 'remoteId' or 'urlAlias' parameters is required.");
        }

        return new Values\TemporaryRedirect(
            $this->router->generate(
                'ezpublish_rest_loadLocation',
                array(
                    'locationPath' => trim($location->pathString, '/'),
                )
            )
        );
    }

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


Question:
Add a row.

@param array    $data  The row data.

@param null|int $rowId The id for the row.

@return FakeResult

public function addRow($data, $rowId = null)
    {
        if (($rowId === null) && isset($data['id'])) {
            $rowId = $data['id'];
        }

        if ($rowId === null) {
            $rowId = count($this->rows);
        }

        $this->rows[$rowId] = $data;

        return $this;
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question:
Add a ChildDeclaration to this mapping

 @param [Symbol] name
 @param [Hash] opts accepts options; expected options: :class

 @return [ChildDeclaration]

def add_child(name, opts = {}, &block)
      delete_property(name)
      properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block)
    end

func parseK8sPodSpec(in string) (*caas.PodSpec, error) {
	// Do the common fields.
	var spec caas.PodSpec
	if err := yaml.Unmarshal([]byte(in), &spec); err != nil {
		return nil, errors.Trace(err)
	}

	// Do the k8s pod attributes.
	var pod k8sPod
	decoder := k8syaml.NewYAMLOrJSONDecoder(strings.NewReader(in), len(in))
	if err := decoder.Decode(&pod); err != nil {
		return nil, errors.Trace(err)
	}
	if pod.K8sPodSpec != nil {
		spec.ProviderPod = pod.K8sPodSpec
	}

	// Do the k8s containers.
	var containers k8sContainers
	decoder = k8syaml.NewYAMLOrJSONDecoder(strings.NewReader(in), len(in))
	if err := decoder.Decode(&containers); err != nil {
		return nil, errors.Trace(err)
	}

	if len(containers.Containers) == 0 {
		return nil, errors.New("require at least one container spec")
	}
	quoteBoolStrings(containers.Containers)
	quoteBoolStrings(containers.InitContainers)

	// Compose the result.
	spec.Containers = make([]caas.ContainerSpec, len(containers.Containers))
	for i, c := range containers.Containers {
		if err := c.Validate(); err != nil {
			return nil, errors.Trace(err)
		}
		spec.Containers[i] = containerFromK8sSpec(c)
	}
	spec.InitContainers = make([]caas.ContainerSpec, len(containers.InitContainers))
	for i, c := range containers.InitContainers {
		if err := c.Validate(); err != nil {
			return nil, errors.Trace(err)
		}
		spec.InitContainers[i] = containerFromK8sSpec(c)
	}
	spec.CustomResourceDefinitions = containers.CustomResourceDefinitions
	return &spec, nil
}

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


Question: // SetPeriod sets the Period field's value.

func (s *GetRelationalDatabaseMetricDataInput) SetPeriod(v int64) *GetRelationalDatabaseMetricDataInput {
	s.Period = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: Write the SERIESTEXT chart BIFF record.

def store_seriestext(str, encoding)  # :nodoc:
    ruby_19 { str = convert_to_ascii_if_ascii(str) }

    record   = 0x100D          # Record identifier.
    length   = 0x0000          # Number of bytes to follow.
    id       = 0x0000          # Text id.
    # str                      # Text.
    # encoding                 # String encoding.
    cch      = str.bytesize      # String length.

    encoding ||= 0

    # Character length is num of chars not num of bytes
    cch /= 2 if encoding != 0

    # Change the UTF-16 name from BE to LE
    str = str.unpack('v*').pack('n*') if encoding != 0

    length = 4 + str.bytesize

    header = [record, length].pack('vv')
    data  = [id].pack('v')
    data += [cch].pack('C')
    data += [encoding].pack('C')

    append(header, data, str)
  end

def dump_stats(self, fdump, close=True):

        if self.tracker:
            self.tracker.stop_periodic_snapshots()

        if isinstance(fdump, type('')):
            fdump = open(fdump, 'wb')
        pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        pickle.dump(self.snapshots, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        if close:
            fdump.close()

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


Question:
Retrieves the configured templates from TypoScript.

@param integer $pageId
@param string $templateKey
@return array

protected function getAvailableTemplateFromTypoScriptConfiguration($pageId, $templateKey)
    {
        $configuration = $this->getConfigurationFromPageId($pageId);
        return $configuration->getAvailableTemplatesByFileKey($templateKey);
    }

public function GetActiveSettingAsHiddenInputField()
    {
        $sInput = '';
        if (false !== $this->GetActiveStartValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_START_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveStartValue()).'" />';
        }
        if (false !== $this->GetActiveEndValue()) {
            $sInput .= '<input type="hidden" name="'.TGlobal::OutHTML(
                $this->GetURLInputName().'['.self::URL_PARAMETER_FILTER_END_VALUE.']'
            ).'" value="'.TGlobal::OutHTML($this->GetActiveEndValue()).'" />';
        }

        return $sInput;
    }

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


Question: // ParseAddresses implements NetworkProtocol.ParseAddresses.

func (*protocol) ParseAddresses(v buffer.View) (src, dst tcpip.Address) {
	h := header.IPv4(v)
	return h.SourceAddress(), h.DestinationAddress()
}

func (t *IPsTable) fetch(c context.Context) error {
	db := database.Get(c)
	rows, err := db.QueryContext(c, `
		SELECT id, ipv4, vlan_id
		FROM ips
	`)
	if err != nil {
		return errors.Annotate(err, "failed to select IP addresses").Err()
	}
	defer rows.Close()
	for rows.Next() {
		ip := &IP{}
		if err := rows.Scan(&ip.Id, &ip.IPv4, &ip.VLANId); err != nil {
			return errors.Annotate(err, "failed to scan IP address").Err()
		}
		t.current = append(t.current, ip)
	}
	return nil
}

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


Question: Invokes a subscription with the required parameters and acts as an adapter for the different asynchronous mechanisms behavior. i.e. node-style callbacks and promises.

function subscriptionInvoker (subscription, data, topic) {
    var result;

    if (subscription.fn.length === 3) {
      return new Promise(function promiseResolver (fulfill, reject) {
        subscription.fn.call(
          subscription.context, data, topic, function callback (err, succ) {
            return err ? reject(err) : fulfill(succ);
          }
        );
      });
    }

    try {
      result = subscription.fn.call(subscription.context, data, topic);
    } catch (e) {
      return Promise.reject(e);
    }

    if (result && typeof result.then === 'function') {
      return result;
    }

    return Promise.resolve(result);
  }

func DefaultDial(connectionTimeout time.Duration) func(network, addr string) (net.Conn, error) {
	return func(network, addr string) (net.Conn, error) {
		conn, err := net.DialTimeout(network, addr, connectionTimeout)
		if err != nil {
			return nil, err
		}

		// Heartbeating hasn't started yet, don't stall forever on a dead server.
		// A deadline is set for TLS and AMQP handshaking. After AMQP is established,
		// the deadline is cleared in openComplete.
		if err := conn.SetDeadline(time.Now().Add(connectionTimeout)); err != nil {
			return nil, err
		}

		return conn, nil
	}
}

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


Question:
Create MySQL Metadata DAO instance

@return MySQLMetaDataDAO

public static function getInstance(DriverConfig $config)
    {
        $pdoDriver = PdoDriverFactory::getInstance();

        return new MySQLMetaDataDAO(
            $pdoDriver->getConnection($config),
            $config
        );
    }

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

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


Question:
Set excludes data.

@param array $excludes

@return $this

protected function excludes($excludes)
    {
        $excludes = \is_array($excludes) ? $excludes : \func_get_args();

        $this->excludes = $excludes;

        return $this;
    }

func shouldIncludeNode(eCtx *executionContext, directives []*ast.Directive) bool {
	var (
		skipAST, includeAST *ast.Directive
		argValues           map[string]interface{}
	)
	for _, directive := range directives {
		if directive == nil || directive.Name == nil {
			continue
		}
		switch directive.Name.Value {
		case SkipDirective.Name:
			skipAST = directive
		case IncludeDirective.Name:
			includeAST = directive
		}
	}
	// precedence: skipAST > includeAST
	if skipAST != nil {
		argValues = getArgumentValues(SkipDirective.Args, skipAST.Arguments, eCtx.VariableValues)
		if skipIf, ok := argValues["if"].(bool); ok && skipIf {
			return false // excluded selectionSet's fields
		}
	}
	if includeAST != nil {
		argValues = getArgumentValues(IncludeDirective.Args, includeAST.Arguments, eCtx.VariableValues)
		if includeIf, ok := argValues["if"].(bool); ok && !includeIf {
			return false // excluded selectionSet's fields
		}
	}
	return true
}

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


Question: // InstanceInspect returns an instance.

func (d *driver) InstanceInspect(
	ctx types.Context,
	opts types.Store) (*types.Instance, error) {

	iid := context.MustInstanceID(ctx)
	return &types.Instance{
		Name:         iid.ID,
		InstanceID:   iid,
		ProviderName: iid.Driver,
	}, nil
}

def inspect
      string  = String.new
      string << "#<#{self.class.name}"
      string << " chunks=#{@chunks.inspect}"
      string << " size=#{size.inspect}"
      string << " encoding=#{encoding.inspect}"
      string << " data=#{data.inspect}"
      string << " on_close=#{@on_close.inspect}"
      string << " rewindable=#{@rewindable.inspect}"
      string << " (closed)" if closed?
      string << ">"
    end

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


Question: Represents a singular REST name

def rest_name(cls):

        if cls.__name__ == "NURESTRootObject" or cls.__name__ == "NURESTObject":
            return "Not Implemented"

        if cls.__rest_name__ is None:
            raise NotImplementedError('%s has no defined name. Implement rest_name property first.' % cls)

        return cls.__rest_name__

func (mr *MockRestClientInterfaceMockRecorder) APIVersion() *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "APIVersion", reflect.TypeOf((*MockRestClientInterface)(nil).APIVersion))
}

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


Question:
Connect to the remote socket.

once fail or exception, it do the cleanup itself.

@Override
    synchronized public boolean connect(InetSocketAddress addr){
        long now = System.currentTimeMillis();
        if(isStarted){
            return true;
        }
        isStarted = true;

        String host = addr.getHostName();
        int port = addr.getPort();

        serverURI = URI.create("ws://" + host + ":" + port + "/ws/service/");

        if(LOGGER.isTraceEnabled()){
            LOGGER.trace("WebSocket connect to timeOut=" + connectTimeOut + " - " + serverURI.toString());
        }

        client = new WebSocketClient();

        doConnect();

        synchronized(sessionLock){
            long to = connectTimeOut - (System.currentTimeMillis() - now);
            while(! connected && to > 0){

                try {
                    sessionLock.wait(to);
                } catch (InterruptedException e) {
                    // do nothing.
                }
                to = connectTimeOut - (System.currentTimeMillis() - now);
            }
        }
        return true;
    }

public final void write(Collection<? extends Client> clients) {
        if (clients.isEmpty()) {
            throw new IllegalArgumentException("You must send this packet to at least one client!");
        }

        clients.forEach(this::write);
    }

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


Question: // ReadV1 implements ChatServiceHandler.ReadV1.

func (c *chatServiceHandler) ReadV1(ctx context.Context, opts readOptionsV1) Reply {
	var rlimits []chat1.RateLimit
	client, err := GetChatLocalClient(c.G())
	if err != nil {
		return c.errReply(err)
	}

	conv, rlimits, err := c.findConversation(ctx, opts.Channel)
	if err != nil {
		return c.errReply(err)
	}

	arg := chat1.GetThreadLocalArg{
		ConversationID: conv.Info.Id,
		Pagination:     opts.Pagination,
		Query: &chat1.GetThreadQuery{
			MarkAsRead: !opts.Peek,
		},
		IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_CLI,
	}
	threadView, err := client.GetThreadLocal(ctx, arg)
	if err != nil {
		return c.errReply(err)
	}
	rlimits = append(rlimits, threadView.RateLimits...)

	// Check to see if this was fetched offline and we should fail
	if opts.FailOffline && threadView.Offline {
		return c.errReply(chat.OfflineError{})
	}

	// This could be lower than the truth if any messages were
	// posted between the last two gregor rpcs.
	readMsgID := conv.ReaderInfo.ReadMsgid

	selfUID := c.G().Env.GetUID()
	if selfUID.IsNil() {
		c.G().Log.Warning("Could not get self UID for api")
	}

	messages, err := c.formatMessages(ctx, threadView.Thread.Messages, conv, selfUID, readMsgID, opts.UnreadOnly)
	if err != nil {
		return c.errReply(err)
	}

	thread := Thread{
		Offline:          threadView.Offline,
		IdentifyFailures: threadView.IdentifyFailures,
		Pagination:       threadView.Thread.Pagination,
		Messages:         messages,
	}

	thread.RateLimits.RateLimits = c.aggRateLimits(rlimits)
	return Reply{Result: thread}
}

public function write($message, $level = null)
    {
        if ($this->isSilent()) {
            return;
        }

        if ($level && ($this->verbosity < $level)) {
            return;
        }

        $message = $this->filter->filter($message);
        $this->adapter->write($message);
    }

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


Question:
Clean the parameter URLs:
- if the parameter is a string make it an array
- remove the trailing slashes if found

@param string|array urls
@return array the array of cleaned URLs

public function cleanParameterUrls($urls)
    {
        if (!is_array($urls)) {
            $urls = array($urls);
        }

        $urls = array_filter($urls);
        $urls = array_map('urldecode', $urls);

        foreach ($urls as &$url) {
            $url = $this->removeTrailingSlash($url);
            $scheme = parse_url($url, PHP_URL_SCHEME);
            if (empty($scheme)
                && strpos($url, '://') === false
            ) {
                $url = 'http://' . $url;
            }
            $url = trim($url);
            $url = Common::sanitizeInputValue($url);
        }

        $urls = array_unique($urls);
        return $urls;
    }

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:
Sets the given comma separated paths as the list of inputs
for the map-reduce job.

@param conf Configuration of the job
@param commaSeparatedPaths Comma separated paths to be set as
the list of inputs for the map-reduce job.

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

synchronized void start(Properties properties) throws Throwable {
        String serverMode = CanalController.getProperty(properties, CanalConstants.CANAL_SERVER_MODE);
        if (serverMode.equalsIgnoreCase("kafka")) {
            canalMQProducer = new CanalKafkaProducer();
        } else if (serverMode.equalsIgnoreCase("rocketmq")) {
            canalMQProducer = new CanalRocketMQProducer();
        }

        if (canalMQProducer != null) {
            // disable netty
            System.setProperty(CanalConstants.CANAL_WITHOUT_NETTY, "true");
            String autoScan = CanalController.getProperty(properties, CanalConstants.CANAL_AUTO_SCAN);
            // 设置为raw避免ByteString->Entry的二次解析
            System.setProperty("canal.instance.memory.rawEntry", "false");
            if ("true".equals(autoScan)) {
                String rootDir = CanalController.getProperty(properties, CanalConstants.CANAL_CONF_DIR);
                if (StringUtils.isEmpty(rootDir)) {
                    rootDir = "../conf";
                }
                File rootdir = new File(rootDir);
                if (rootdir.exists()) {
                    File[] instanceDirs = rootdir.listFiles(new FileFilter() {

                        public boolean accept(File pathname) {
                            String filename = pathname.getName();
                            return pathname.isDirectory() && !"spring".equalsIgnoreCase(filename) &&
                                    !"metrics".equalsIgnoreCase(filename);
                        }
                    });
                    if (instanceDirs != null && instanceDirs.length > 0) {
                        List<String> instances = Lists.transform(Arrays.asList(instanceDirs),
                            new Function<File, String>() {

                                @Override
                                public String apply(File instanceDir) {
                                    return instanceDir.getName();
                                }
                            });
                        System.setProperty(CanalConstants.CANAL_DESTINATIONS, Joiner.on(",").join(instances));
                    }
                }
            } else {
                String destinations = CanalController.getProperty(properties, CanalConstants.CANAL_DESTINATIONS);
                System.setProperty(CanalConstants.CANAL_DESTINATIONS, destinations);
            }
        }

        logger.info("## start the canal server.");
        controller = new CanalController(properties);
        controller.start();
        logger.info("## the canal server is running now ......");
        shutdownThread = new Thread() {

            public void run() {
                try {
                    logger.info("## stop the canal server");
                    controller.stop();
                    CanalLauncher.running = false;
                } catch (Throwable e) {
                    logger.warn("##something goes wrong when stopping canal Server:", e);
                } finally {
                    logger.info("## canal server is down.");
                }
            }

        };
        Runtime.getRuntime().addShutdownHook(shutdownThread);

        if (canalMQProducer != null) {
            canalMQStarter = new CanalMQStarter(canalMQProducer);
            MQProperties mqProperties = buildMQProperties(properties);
            canalMQStarter.start(mqProperties);
            controller.setCanalMQStarter(canalMQStarter);
        }
    }

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


Question:
generate sentences

@param sentenceCount number of sentences
@param supplemental  if true add additional word to each word
@return sentence string

public static String sentences(int sentenceCount, boolean supplemental) {
        List<String> sentenceList = new ArrayList<String>();
        for (int i = 0; i < sentenceCount; i++) {
            sentenceList.add(sentence(3, supplemental, 6));
        }

        String sentenceString = StringUtils.join(sentenceList, " ");
        return sentenceString;

    }

def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
                       config: TextProcessingConfig) -> Iterator[str]:
    # only called if docx loaded

    if in_order:
        for thing in docx_docx_iter_block_items(doc):
            if isinstance(thing, docx.text.paragraph.Paragraph):
                yield docx_process_simple_text(thing.text, config.width)
            elif isinstance(thing, docx.table.Table):
                yield docx_process_table(thing, config)
    else:
        for paragraph in doc.paragraphs:
            yield docx_process_simple_text(paragraph.text, config.width)
        for table in doc.tables:
            yield docx_process_table(table, config)

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


Question: Create a new Seneca instance. * _initial_options_ `o` → instance options

function make_seneca(initial_options) {
  initial_options = initial_options || {}

  // Create a private context.
  var private$ = make_private()
  private$.error = error

  // Create a new root Seneca instance.
  var root$ = new Seneca()

  // Expose private data to plugins.
  root$.private$ = private$

  // Resolve initial options.
  private$.optioner = Optioner(module, option_defaults, initial_options)
  var opts = { $: private$.optioner.get() }

  // Setup event handlers, if defined
  ;['log', 'act_in', 'act_out', 'act_err', 'ready', 'close'].forEach(function(
    event_name
  ) {
    if ('function' === typeof opts.$.events[event_name]) {
      root$.on(event_name, opts.$.events[event_name])
    }
  })

  // Create internal tools.
  private$.actnid = Nid({ length: opts.$.idlen })
  private$.didnid = Nid({ length: opts.$.didlen })

  var next_action_id = Common.autoincr()

  // These need to come from options as required during construction.
  opts.$.internal.actrouter = opts.$.internal.actrouter || Patrun({ gex: true })
  opts.$.internal.subrouter = opts.$.internal.subrouter || Patrun({ gex: true })

  var callpoint = make_callpoint(opts.$.debug.callpoint)

  // Define public member variables.
  root$.start_time = Date.now()
  root$.context = {}
  root$.version = Package.version

  // TODO: rename in 4.x as "args" terminology is legacy
  root$.fixedargs = {}

  root$.flags = {
    closed: false
  }

  Object.defineProperty(root$, 'root', { value: root$ })

  private$.history = Common.history(opts.$.history)

  // Seneca methods. Official API.
  root$.has = API.has // True if the given pattern has an action.
  root$.find = API.find // Find the action definition for a pattern.
  root$.list = API.list // List the patterns added to this instance.
  root$.status = API.status // Get the status if this instance.
  root$.reply = API.reply // Reply to a submitted message.
  root$.sub = API.sub // Subscribe to messages.
  root$.list_plugins = API.list_plugins // List the registered plugins.
  root$.find_plugin = API.find_plugin // Find the plugin definition.
  root$.has_plugin = API.has_plugin // True if the plugin is registered.
  root$.ignore_plugin = API.ignore_plugin // Ignore plugin and don't register it.
  root$.listen = API.listen(callpoint) // Listen for inbound messages.
  root$.client = API.client(callpoint) // Send outbound messages.
  root$.gate = API.gate // Create a delegate that executes actions in sequence.
  root$.ungate = API.ungate // Execute actions in parallel.
  root$.translate = API.translate // Translate message to new pattern.
  root$.ping = API.ping // Generate ping response.
  root$.use = API.use // Define and load a plugin.
  root$.test = API.test // Set test mode.
  root$.quiet = API.quiet // Convenience method to set logging level to `warn+`.
  root$.export = API.export // Export plain objects from a plugin.
  root$.depends = API.depends // Check for plugin dependencies.
  root$.delegate = API.delegate // Create an action-specific Seneca instance.
  root$.prior = API.prior // Call the previous action definition for message pattern.
  root$.inward = API.inward // Add a modifier function for messages inward
  root$.outward = API.outward // Add a modifier function for responses outward
  root$.error = API.error // Set global error handler, or generate Seneca Error
  root$.fail = opts.$.legacy.fail ? Legacy.make_legacy_fail(opts.$) : API.fail // Throw a Seneca error

  root$.add = api_add // Add a pattern an associated action.
  root$.act = api_act // Submit a message and trigger the associated action.

  root$.ready = api_ready // Callback when plugins initialized.
  root$.close = api_close // Close and shutdown plugins.
  root$.options = api_options // Get and set options.
  root$.decorate = api_decorate // Decorate seneca object with functions

  // Non-API methods.
  root$.register = Plugins.register(opts, callpoint)

  root$.wrap = api_wrap
  root$.seneca = api_seneca
  root$.fix = api_fix

  // DEPRECATE IN 4.x
  root$.findact = root$.find
  root$.plugins = API.list_plugins
  root$.findplugin = API.find_plugin
  root$.hasplugin = API.has_plugin
  root$.hasact = Legacy.hasact
  root$.act_if = Legacy.act_if
  root$.findpins = Legacy.findpins
  root$.pinact = Legacy.findpins
  root$.next_act = Legacy.next_act

  // Identifier generator.
  root$.idgen = Nid({ length: opts.$.idlen })
  opts.$.tag = opts.$.tag || option_defaults.tag
  opts.$.tag = opts.$.tag === 'undefined' ? option_defaults.tag : opts.$.tag

  // Create a unique identifer for this instance.
  root$.id =
    opts.$.id$ ||
    root$.idgen() +
      '/' +
      root$.start_time +
      '/' +
      process.pid +
      '/' +
      root$.version +
      '/' +
      opts.$.tag

  // The instance tag, useful for grouping instances.
  root$.tag = opts.$.tag

  if (opts.$.debug.short_logs || opts.$.log.short) {
    opts.$.idlen = 2
    root$.idgen = Nid({ length: opts.$.idlen })
    root$.id = root$.idgen() + '/' + opts.$.tag
  }

  root$.fullname = 'Seneca/' + root$.id

  root$.die = Common.makedie(root$, {
    type: 'sys',
    plugin: 'seneca',
    tag: root$.version,
    id: root$.id,
    callpoint: callpoint
  })

  root$.util = seneca_util

  private$.exports = { options: opts.$ }
  private$.decorations = {}

  // Configure logging
  private$.logger = load_logger(root$, opts.$.internal.logger)
  root$.make_log = make_log
  root$.log = make_log(root$, make_default_log_modifier(root$))

  // Error events are fatal, unless you're undead.  These are not the
  // same as action errors, these are unexpected internal issues.
  root$.on('error', root$.die)

  private$.ge = GateExecutor({
    timeout: opts.$.timeout
  })
    .clear(action_queue_clear)
    .start()

  // TODO: this should be a plugin
  // setup status log
  if (opts.$.status.interval > 0 && opts.$.status.running) {
    private$.stats = private$.stats || {}
    private$.status_interval = setInterval(function status() {
      root$.log.info({
        kind: 'status',
        alive: Date.now() - private$.stats.start,
        act: private$.stats.act
      })
    }, opts.$.status.interval)
  }

  if (opts.$.stats) {
    private$.timestats = new Stats.NamedStats(
      opts.$.stats.size,
      opts.$.stats.interval
    )

    if (opts.$.stats.running) {
      setInterval(function stats() {
        private$.timestats.calculate()
      }, opts.$.stats.interval)
    }
  }

  // private$.plugins = {}
  private$.plugin_order = { byname: [], byref: [] }
  private$.use = UsePlugin({
    prefix: ['seneca-', '@seneca/'],
    module: opts.$.internal.module || module,
    msgprefix: false,
    builtin: '',
    merge_defaults: false
  })

  private$.actrouter = opts.$.internal.actrouter
  private$.subrouter = opts.$.internal.subrouter

  root$.toString = api_toString

  // TODO: provide an api to add these
  private$.action_modifiers = [
    function add_rules_from_validate_annotation(actdef) {
      actdef.rules = Object.assign(
        actdef.rules,
        _.clone(actdef.func.validate || {})
      )
    }
  ]

  private$.sub = { handler: null, tracers: [] }

  private$.ready_list = []

  private$.inward = Ordu({ name: 'inward' })
    .add(Inward.msg_modify)
    .add(Inward.closed)
    .add(Inward.act_cache)
    .add(Inward.act_default)
    .add(Inward.act_not_found)
    .add(Inward.act_stats)
    .add(Inward.validate_msg)
    .add(Inward.warnings)
    .add(Inward.msg_meta)
    .add(Inward.limit_msg)
    .add(Inward.prepare_delegate)
    .add(Inward.announce)

  private$.outward = Ordu({ name: 'outward' })
    .add(Outward.make_error)
    .add(Outward.act_stats)
    .add(Outward.act_cache)
    .add(Outward.res_object)
    .add(Outward.res_entity)
    .add(Outward.msg_meta)
    .add(Outward.trace)
    .add(Outward.announce)
    .add(Outward.act_error)

  if (opts.$.test) {
    root$.test('string' === typeof opts.$.test ? opts.$.test : 'print')
  }

  // See [`seneca.add`](#seneca.add)
  function api_add() {
    var self = this
    var args = Common.parsePattern(self, arguments, 'action:f? actdef:o?')

    var raw_pattern = args.pattern
    var pattern = self.util.clean(raw_pattern)

    var action =
      args.action ||
      function default_action(msg, done, meta) {
        done.call(this, null, meta.dflt || null)
      }

    var actdef = args.actdef || {}

    actdef.raw = _.cloneDeep(raw_pattern)
    actdef.plugin_name = actdef.plugin_name || 'root$'
    actdef.plugin_fullname =
      actdef.plugin_fullname ||
      actdef.plugin_name +
        ((actdef.plugin_tag === '-'
        ? void 0
        : actdef.plugin_tag)
          ? '$' + actdef.plugin_tag
          : '')

    actdef.plugin = {
      name: actdef.plugin_name,
      tag: actdef.plugin_tag,
      fullname: actdef.plugin_fullname
    }

    var add_callpoint = callpoint()
    if (add_callpoint) {
      actdef.callpoint = add_callpoint
    }

    actdef.sub = !!raw_pattern.sub$
    actdef.client = !!raw_pattern.client$

    // Deprecate a pattern by providing a string message using deprecate$ key.
    actdef.deprecate = raw_pattern.deprecate$

    actdef.fixed = Jsonic(raw_pattern.fixed$ || {})
    actdef.custom = Jsonic(raw_pattern.custom$ || {})

    var strict_add =
      raw_pattern.strict$ && raw_pattern.strict$.add !== null
        ? !!raw_pattern.strict$.add
        : !!opts.$.strict.add

    var addroute = true

    if (opts.$.legacy.actdef) {
      actdef.args = _.clone(pattern)
    }

    actdef.id = action.name + '_' + next_action_id()
    actdef.name = action.name
    actdef.func = action

    // Canonical string form of the action pattern.
    actdef.pattern = Common.pattern(pattern)

    // Canonical object form of the action pattern.
    actdef.msgcanon = Jsonic(actdef.pattern)

    var priordef = self.find(pattern)

    if (priordef && strict_add && priordef.pattern !== actdef.pattern) {
      // only exact action patterns are overridden
      // use .wrap for pin-based patterns
      priordef = null
    }

    if (priordef) {
      // Clients needs special handling so that the catchall
      // pattern does not submit all patterns into the handle
      if (
        _.isFunction(priordef.handle) &&
        ((priordef.client && actdef.client) ||
          (!priordef.client && !actdef.client))
      ) {
        priordef.handle(args.pattern, action)
        addroute = false
      } else {
        actdef.priordef = priordef
      }
      actdef.priorpath = priordef.id + ';' + priordef.priorpath
    } else {
      actdef.priorpath = ''
    }

    if (action && actdef && _.isFunction(action.handle)) {
      actdef.handle = action.handle
    }

    private$.stats.actmap[actdef.pattern] =
      private$.stats.actmap[actdef.pattern] || make_action_stats(actdef)

    var pattern_rules = {}
    _.each(pattern, function(v, k) {
      if (_.isObject(v)) {
        pattern_rules[k] = _.clone(v)
        delete pattern[k]
      }
    })
    actdef.rules = pattern_rules

    if (addroute) {
      self.log.debug({
        kind: 'add',
        case: actdef.sub ? 'SUB' : 'ADD',
        id: actdef.id,
        pattern: actdef.pattern,
        name: action.name,
        callpoint: callpoint
      })

      private$.actrouter.add(pattern, actdef)
    }

    private$.actdef[actdef.id] = actdef

    deferred_modify_action(self, actdef)

    return self
  }

  function make_action_stats(actdef) {
    return {
      id: actdef.id,
      plugin: {
        full: actdef.plugin_fullname,
        name: actdef.plugin_name,
        tag: actdef.plugin_tag
      },
      prior: actdef.priorpath,
      calls: 0,
      done: 0,
      fails: 0,
      time: {}
    }
  }

  // NOTE: use setImmediate so that action annotations (such as .validate)
  // can be defined after call to seneca.add (for nicer plugin code order).
  function deferred_modify_action(seneca, actdef) {
    setImmediate(function() {
      _.each(seneca.private$.action_modifiers, function(actmod) {
        actmod.call(seneca, actdef)
      })
    })
  }

  // Perform an action. The properties of the first argument are matched against
  // known patterns, and the most specific one wins.
  function api_act() {
    var argsarr = new Array(arguments.length)
    for (var l = 0; l < argsarr.length; ++l) {
      argsarr[l] = arguments[l]
    }

    var self = this
    var spec = Common.build_message(self, argsarr, 'reply:f?', self.fixedargs)
    var msg = spec.msg
    var reply = spec.reply

    if (opts.$.debug.act_caller || opts.$.test) {
      msg.caller$ =
        '\n    Action call arguments and location: ' +
        (new Error(Util.inspect(msg).replace(/\n/g, '')).stack + '\n')
          .replace(/Error: /, '')
          .replace(/.*\/gate-executor\.js:.*\n/g, '')
          .replace(/.*\/seneca\.js:.*\n/g, '')
          .replace(/.*\/seneca\/lib\/.*\.js:.*\n/g, '')
    }

    do_act(self, msg, reply)
    return self
  }

  function api_wrap(pin, meta, wrapper) {
    var pinthis = this

    wrapper = _.isFunction(meta) ? meta : wrapper
    meta = _.isFunction(meta) ? {} : meta

    pin = _.isArray(pin) ? pin : [pin]
    _.each(pin, function(p) {
      _.each(pinthis.list(p), function(actpattern) {
        pinthis.add(actpattern, meta, wrapper)
      })
    })

    return this
  }

  private$.handle_close = function() {
    root$.close(function(err) {
      if (err) {
        Print.err(err)
      }

      opts.$.system.exit(err ? (err.exit === null ? 1 : err.exit) : 0)
    })
  }

  // close seneca instance
  // sets public seneca.closed property
  function api_close(done) {
    var seneca = this

    var safe_done = _.once(function(err) {
      if (_.isFunction(done)) {
        return done.call(seneca, err)
      }
    })

    // don't try to close twice
    if (seneca.flags.closed) {
      return safe_done()
    }

    seneca.ready(do_close)
    var close_timeout = setTimeout(do_close, opts.$.close_delay)

    function do_close() {
      clearTimeout(close_timeout)

      if (seneca.flags.closed) {
        return safe_done()
      }

      // TODO: remove in 4.x
      seneca.closed = true

      seneca.flags.closed = true

      // cleanup process event listeners
      _.each(opts.$.system.close_signals, function(active, signal) {
        if (active) {
          process.removeListener(signal, private$.handle_close)
        }
      })

      seneca.log.debug({
        kind: 'close',
        notice: 'start',
        callpoint: callpoint()
      })

      seneca.act('role:seneca,cmd:close,closing$:true', function(err) {
        seneca.log.debug(errlog(err, { kind: 'close', notice: 'end' }))

        seneca.removeAllListeners('act-in')
        seneca.removeAllListeners('act-out')
        seneca.removeAllListeners('act-err')
        seneca.removeAllListeners('pin')
        seneca.removeAllListeners('after-pin')
        seneca.removeAllListeners('ready')

        seneca.private$.history.close()

        if (seneca.private$.status_interval) {
          clearInterval(seneca.private$.status_interval)
        }

        return safe_done(err)
      })
    }

    return seneca
  }

  // useful when defining services!
  // note: has EventEmitter.once semantics
  // if using .on('ready',fn) it will be be called for each ready event
  function api_ready(ready) {
    var self = this

    if ('function' === typeof ready) {
      setImmediate(function register_ready() {
        if (root$.private$.ge.isclear()) {
          execute_ready(ready.bind(self))
        } else {
          root$.private$.ready_list.push(ready.bind(self))
        }
      })
    }

    return self
  }

  // Return self. Mostly useful as a check that this is a Seneca instance.
  function api_seneca() {
    return this
  }

  // Describe this instance using the form: Seneca/VERSION/ID
  function api_toString() {
    return this.fullname
  }

  function do_act(instance, origmsg, origreply) {
    var timedout = false
    var actmsg = intern.make_actmsg(origmsg)
    var meta = new intern.Meta(instance, opts, origmsg, origreply)

    if (meta.gate) {
      instance = instance.delegate()
      instance.private$.ge = instance.private$.ge.gate()
    }

    var actctxt = {
      seneca: instance,
      origmsg: origmsg,
      reply: origreply || _.noop,
      options: instance.options(),
      callpoint: callpoint()
    }

    var execspec = {
      dn: meta.id,
      fn: function act_fn(done) {
        try {
          intern.execute_action(
            instance,
            opts,
            actctxt,
            actmsg,
            meta,
            function action_reply(err, out, reply_meta) {
              if (!timedout) {
                intern.handle_reply(meta, actctxt, actmsg, err, out, reply_meta)
              }
              done()
            }
          )
        } catch (e) {
          var ex = Util.isError(e) ? e : new Error(Util.inspect(e))
          intern.handle_reply(meta, actctxt, actmsg, ex)
          done()
        }
      },
      ontm: function act_tm() {
        timedout = true
        intern.handle_reply(meta, actctxt, actmsg, new Error('[TIMEOUT]'))
      },
      tm: meta.timeout
    }

    instance.private$.ge.add(execspec)
  }

  function api_fix(patargs, msgargs, custom) {
    var self = this

    // var defargs = Common.parsePattern(self, arguments)
    patargs = Jsonic(patargs || {})

    var fix_delegate = self.delegate(patargs)

    fix_delegate.add = function fix_add() {
      var args = Common.parsePattern(this, arguments, 'rest:.*', patargs)
      var addargs = [args.pattern]
        .concat({
          fixed$: Object.assign({}, msgargs, args.pattern.fixed$),
          custom$: Object.assign({}, custom, args.pattern.custom$)
        })
        .concat(args.rest)
      return self.add.apply(this, addargs)
    }

    return fix_delegate
  }

  function api_options(options, chain) {
    var self = this

    if (options != null) {
      self.log.debug({
        kind: 'options',
        case: 'SET',
        options: options,
        callpoint: callpoint()
      })
    }

    opts.$ = private$.exports.options =
      options == null ? private$.optioner.get() : private$.optioner.set(options)

    if (opts.$.legacy.logging) {
      if (options && options.log && _.isArray(options.log.map)) {
        for (var i = 0; i < options.log.map.length; ++i) {
          self.logroute(options.log.map[i])
        }
      }
    }

    // TODO: in 4.x, when given options, it should chain
    // Allow chaining with seneca.options({...}, true)
    // see https://github.com/rjrodger/seneca/issues/80
    return chain ? self : opts.$
  }

  // Inspired by https://github.com/hapijs/hapi/blob/master/lib/plugin.js decorate
  // TODO: convert to seneca errors
  function api_decorate() {
    var args = Norma('property:s value:.', arguments)

    var property = args.property
    Assert(property[0] !== '_', 'property cannot start with _')
    Assert(
      private$.decorations[property] === undefined,
      'seneca is already decorated with the property: ' + property
    )
    Assert(
      root$[property] === undefined,
      'cannot override a core seneca property: ' + property
    )

    root$[property] = private$.decorations[property] = args.value
  }

  Actions(root$)

  if (!opts.$.legacy.transport) {
    opts.$.legacy.error = false

    // TODO: move to static options in Seneca 4.x
    opts.$.transport = root$.util.deepextend(
      {
        port: 62345,
        host: '127.0.0.1',
        path: '/act',
        protocol: 'http'
      },
      opts.$.transport
    )

    Transport(root$)
  }

  Print(root$, opts.$.debug.argv || process.argv)

  _.each(opts.$.system.close_signals, function(active, signal) {
    if (active) {
      process.once(signal, private$.handle_close)
    }
  })

  function load_logger(instance, log_plugin) {
    log_plugin = log_plugin || require('./lib/logging')

    return log_plugin.preload.call(instance).extend.logger
  }

  // NOTE: this could be called from an arbitrary GateExecutor task,
  // if the task queue is emptied.
  function action_queue_clear() {
    root$.emit('ready')
    execute_ready(root$.private$.ready_list.shift())

    if (root$.private$.ge.isclear()) {
      while (0 < root$.private$.ready_list.length) {
        execute_ready(root$.private$.ready_list.shift())
      }
    }
  }

  function execute_ready(ready_func) {
    if (null == ready_func) return

    try {
      ready_func()
    } catch (ready_err) {
      var err = error(ready_err, 'ready_failed', { message: ready_err.message })

      if (opts.$.test) {
        if (opts.$.errhandler) {
          opts.$.errhandler.call(root$, err)
        } else throw err
      } else {
        root$.die(err)
      }
    }
  }

  return root$
}

def repl_init(self, config):
        """"""
        self.update_server_map(config)
        # init_server - server which can init replica set
        init_server = [member['host'] for member in config['members']
                       if not (member.get('arbiterOnly', False)
                               or member.get('priority', 1) == 0)][0]

        servers = [member['host'] for member in config['members']]
        if not self.wait_while_reachable(servers):
            logger.error("all servers must be reachable")
            self.cleanup()
            return False
        try:
            result = self.connection(init_server).admin.command("replSetInitiate", config)
            logger.debug("replica init result: {result}".format(**locals()))
        except pymongo.errors.PyMongoError:
            raise
        if int(result.get('ok', 0)) == 1:
            # Wait while members come up
            return self.waiting_member_state()
        else:
            self.cleanup()
            return False

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


Question:
Delete an entity identified by its type and unique attributes.
@param  typeName - entity type to be deleted
@param  servletRequest - request containing unique attributes/values
@return EntityMutationResponse

@DELETE
    @Consumes(Servlets.JSON_MEDIA_TYPE)
    @Produces(Servlets.JSON_MEDIA_TYPE)
    @Path("/uniqueAttribute/type/{typeName}")
    public EntityMutationResponse deleteByUniqueAttribute(@PathParam("typeName") String typeName,
                                                          @Context HttpServletRequest servletRequest) throws AtlasBaseException {
        AtlasPerfTracer perf = null;

        try {
            Map<String, Object> attributes = getAttributes(servletRequest);

            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityREST.deleteByUniqueAttribute(" + typeName + "," + attributes + ")");
            }

            AtlasEntityType entityType = ensureEntityType(typeName);

            return entitiesStore.deleteByUniqueAttributes(entityType, attributes);
        } finally {
            AtlasPerfTracer.log(perf);
        }
    }

private static HttpResponse sendRequest(org.dasein.cloud.digitalocean.DigitalOcean provider, RESTMethod method, String token, String strUrl, DigitalOceanAction action) throws CloudException, InternalException {
        HttpRequestBase req = null;
        if (method == RESTMethod.GET) {
            req = new HttpGet(strUrl);
        } else if (method == RESTMethod.POST) {
            req = new HttpPost(strUrl);
        } else if (method == RESTMethod.PUT) {
            req = new HttpPut(strUrl);
        } else if (method == RESTMethod.DELETE) {
            req = new HttpDelete(strUrl);
        } else if (method == RESTMethod.HEAD) {
            req = new HttpHead(strUrl);
        }

        try {
            req.setHeader("Authorization", "Bearer " + token);
            req.setHeader("Accept", "application/json");
            req.setHeader("Content-Type", "application/json;charset=UTF-8");

            StringEntity requestEntity = null;
            if (req instanceof HttpEntityEnclosingRequestBase && action != null) {
                JSONObject jsonToPost = action.getParameters();
                if (jsonToPost != null) {
                    requestEntity = new StringEntity(
                            jsonToPost.toString(),
                            ContentType.APPLICATION_JSON);
                    ((HttpEntityEnclosingRequestBase) req).setEntity(requestEntity);
                }
            }

            HttpClient httpClient = provider.getClient();

            if (wire.isDebugEnabled()) {
                wire.debug("");
                wire.debug("--------------------------------------------------------------------------------------");
            }

            if (wire.isDebugEnabled()) {
                wire.debug(req.getRequestLine().toString());
                for (Header header : req.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");

                if (requestEntity != null) {
                    try {
                        wire.debug(EntityUtils.toString(requestEntity));
                        wire.debug("");
                    } catch (IOException ignore) {
                    }
                }
            }

            HttpResponse response = null;
            int retryCount = 0;

            while (retryCount < 6) {
                response = httpClient.execute(req);

                if (wire.isDebugEnabled()) {
                    wire.debug(response.getStatusLine().toString());
                }

                if (method == RESTMethod.DELETE) {
                    if ((response.getStatusLine().getStatusCode() == 204)) {
                        break;
                    } else {
                        retryCount++;
                        Thread.sleep(5000);
                    }
                } else {
                    break;
                }
            }
            if (method == RESTMethod.DELETE && (response.getStatusLine().getStatusCode() != 204)) {
                //Error occurred
                throw new CloudException("Delete method returned unexpected code, despite retrying.");
            }
            return response;
        } catch (JSONException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (InterruptedException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (ClientProtocolException e) {
            throw new CloudException("Problem sending request.", e);
        } catch (IOException e) {
            throw new CloudException("Problem sending request.", e);
        } finally {
            try {
//                req.releaseConnection();
            } catch (Exception e) {
            }

        }
    }

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


Question: // Source creates the JSON data.

func (o *FuzzyCompletionSuggesterOptions) Source() (interface{}, error) {
	out := make(map[string]interface{})

	if o.editDistance != nil {
		out["fuzziness"] = o.editDistance
	}
	if o.transpositions != nil {
		out["transpositions"] = *o.transpositions
	}
	if o.minLength != nil {
		out["min_length"] = *o.minLength
	}
	if o.prefixLength != nil {
		out["prefix_length"] = *o.prefixLength
	}
	if o.unicodeAware != nil {
		out["unicode_aware"] = *o.unicodeAware
	}
	if o.maxDeterminizedStates != nil {
		out["max_determinized_states"] = *o.maxDeterminizedStates
	}

	return out, nil
}

public ConfigurationSourcesModuleBuilder addSource(ConfigurationSource configurationSource) {
    if (configurationSource == null) {
      throw new NullPointerException("configurationSource: null");
    }
    configurationSources.add(configurationSource);
    return this;
  }

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


Question:
The account's Internal auto reply message. Setting the value will change the auto reply message of the
         account, automatically setting the status to enabled (but not altering the schedule).

def auto_reply_message(self):

        if self._auto_reply is None:
            r = requests.get('https://outlook.office.com/api/v2.0/me/MailboxSettings/AutomaticRepliesSetting',
                             headers=self._headers)
            check_response(r)
            self._auto_reply = r.json().get('InternalReplyMessage')

        return self._auto_reply

public function propFind(PropFind $propFind, INode $node)
    {
        if ($node instanceof DAVACL\IPrincipal) {
            $caldavPlugin = $this->server->getPlugin('caldav');
            $principalUrl = $node->getPrincipalUrl();

            // schedule-outbox-URL property
            $propFind->handle('{'.self::NS_CALDAV.'}schedule-outbox-URL', function () use ($principalUrl, $caldavPlugin) {
                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
                if (!$calendarHomePath) {
                    return null;
                }
                $outboxPath = $calendarHomePath.'/outbox/';

                return new LocalHref($outboxPath);
            });
            // schedule-inbox-URL property
            $propFind->handle('{'.self::NS_CALDAV.'}schedule-inbox-URL', function () use ($principalUrl, $caldavPlugin) {
                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);
                if (!$calendarHomePath) {
                    return null;
                }
                $inboxPath = $calendarHomePath.'/inbox/';

                return new LocalHref($inboxPath);
            });

            $propFind->handle('{'.self::NS_CALDAV.'}schedule-default-calendar-URL', function () use ($principalUrl, $caldavPlugin) {
                // We don't support customizing this property yet, so in the
                // meantime we just grab the first calendar in the home-set.
                $calendarHomePath = $caldavPlugin->getCalendarHomeForPrincipal($principalUrl);

                if (!$calendarHomePath) {
                    return null;
                }

                $sccs = '{'.self::NS_CALDAV.'}supported-calendar-component-set';

                $result = $this->server->getPropertiesForPath($calendarHomePath, [
                    '{DAV:}resourcetype',
                    '{DAV:}share-access',
                    $sccs,
                ], 1);

                foreach ($result as $child) {
                    if (!isset($child[200]['{DAV:}resourcetype']) || !$child[200]['{DAV:}resourcetype']->is('{'.self::NS_CALDAV.'}calendar')) {
                        // Node is either not a calendar
                        continue;
                    }
                    if (isset($child[200]['{DAV:}share-access'])) {
                        $shareAccess = $child[200]['{DAV:}share-access']->getValue();
                        if (Sharing\Plugin::ACCESS_NOTSHARED !== $shareAccess && Sharing\Plugin::ACCESS_SHAREDOWNER !== $shareAccess) {
                            // Node is a shared node, not owned by the relevant
                            // user.
                            continue;
                        }
                    }
                    if (!isset($child[200][$sccs]) || in_array('VEVENT', $child[200][$sccs]->getValue())) {
                        // Either there is no supported-calendar-component-set
                        // (which is fine) or we found one that supports VEVENT.
                        return new LocalHref($child['href']);
                    }
                }
            });

            // The server currently reports every principal to be of type
            // 'INDIVIDUAL'
            $propFind->handle('{'.self::NS_CALDAV.'}calendar-user-type', function () {
                return 'INDIVIDUAL';
            });
        }

        // Mapping the old property to the new property.
        $propFind->handle('{http://calendarserver.org/ns/}calendar-availability', function () use ($propFind, $node) {
            // In case it wasn't clear, the only difference is that we map the
            // old property to a different namespace.
            $availProp = '{'.self::NS_CALDAV.'}calendar-availability';
            $subPropFind = new PropFind(
                 $propFind->getPath(),
                 [$availProp]
             );

            $this->server->getPropertiesByNode(
                 $subPropFind,
                 $node
             );

            $propFind->set(
                 '{http://calendarserver.org/ns/}calendar-availability',
                 $subPropFind->get($availProp),
                 $subPropFind->getStatus($availProp)
             );
        });
    }

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


Question: Remove runlist from the storage.

def runlist_remove(name, **kwargs):

    ctx = Context(**kwargs)
    ctx.execute_action('runlist:remove', **{
        'storage': ctx.repo.create_secure_service('storage'),
        'name': name,
    })

@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
	{
		switch (featureID)
		{
			case SarlPackage.SARL_ACTION__FIRED_EVENTS:
				return ((InternalEList<?>)getFiredEvents()).basicRemove(otherEnd, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

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


Question:
Append the html-code to start a html mail message to the given buffer.<p>

@param buffer The StringBuffer to add the html code to.

protected void appendHtmlHeader(StringBuffer buffer) {

        if (m_configuredHeader != null) {
            buffer.append(m_configuredHeader);
        } else {
            buffer.append("<html>\r\n");
            buffer.append("  <head>\r\n");
            buffer.append("    <style type=\"text/css\">\r\n");
            buffer.append(
                "      body { font-family: Verdana, Arial, Helvetica, sans-serif; background-color:white; }\r\n");
            buffer.append("      a { color:#b31b43; text-decoration:none; font-weight: bold; }\r\n");
            buffer.append("      a:hover { color:#b31b43; text-decoration:underline; font-weight: bold; }\r\n");
            buffer.append("      div.publish_link { margin: 20px 0; }\r\n");
            buffer.append("      table { white-space: nowrap; font-size: small; }\r\n");
            buffer.append("      tr.trow1 { background-color: #cdc0b0; }\r\n");
            buffer.append("      tr.trow2 { background-color: #eedfcc; }\r\n");
            buffer.append("      tr.trow3 { background-color: #ffefdb; }\r\n");
            buffer.append(
                "      th.rescol { border-width: 1px 0 2px 1px; border-style: solid; border-color: #222222; padding: 5px; }\r\n");
            buffer.append(
                "      th.titlecol { border-width: 1px 1px 2px 1px; border-style: solid; border-color: #222222; padding: 5px; }\r\n");
            buffer.append(
                "      td.rescol { border-width: 0 0 1px 1px; border-style: solid; border-color: #222222; padding: 5px; }\r\n");
            buffer.append(
                "      td.titlecol { border-width: 0 1px 1px 1px; border-style: solid; border-color: #222222; padding: 5px; }\r\n");
            buffer.append("    </style>\r\n");
            buffer.append("  </head>\r\n");
            buffer.append("  <body>\r\n");
        }
    }

def add_listener(type, &block)
      case type
      when :status
        @webclient.setStatusHandler(self)
      when :alert
        @webclient.setAlertHandler(self)
      when :attachment
        @webclient.setAttachmentHandler(self)
      when :web_window_event
        @webclient.addWebWindowListener(self)
      when :html_parser
        @webclient.setHTMLParserListener(self)
      when :incorrectness
        @webclient.setIncorrectnessListener(self)
      when :confirm
        @webclient.setConfirmHandler(self)
      when :prompt
        @webclient.setPromptHandler(self)
      else
        raise ArgumentError, "unknown listener type #{type.inspect}"
      end

      @procs[type] << block
    end

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


Question:
Sets the behavior for one or all attributes to use when traversing the
        tree using a query vector and it encounters a branch that does not
        exist.

def set_missing_value_policy(self, policy, target_attr_name=None):

        assert policy in MISSING_VALUE_POLICIES, \
            "Unknown policy: %s" % (policy,)
        for attr_name in self.data.attribute_names:
            if target_attr_name is not None and target_attr_name != attr_name:
                continue
            self.missing_value_policy[attr_name] = policy

def commit_to(self, db: BaseDB) -> None:

        self.logger.debug2('persist storage root to data store')
        if self._trie_nodes_batch is None:
            raise ValidationError(
                "It is invalid to commit an account's storage if it has no pending changes. "
                "Always check storage_lookup.has_changed_root before attempting to commit."
            )
        self._trie_nodes_batch.commit_to(db, apply_deletes=False)
        self._clear_changed_root()

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


Question:
Makes sure that a btrfs subvolume is removed.

    name
        Name of the subvolume to remove

    device
        Device where to remove the subvolume

    commit
        Wait until the transaction is over

def subvolume_deleted(name, device, commit=False, __dest=None):
    '''

    '''
    ret = {
        'name': name,
        'result': False,
        'changes': {},
        'comment': [],
    }

    path = os.path.join(__dest, name)

    exists = __salt__['btrfs.subvolume_exists'](path)
    if not exists:
        ret['comment'].append('Subvolume {} already missing'.format(name))

    if __opts__['test']:
        ret['result'] = None
        if exists:
            ret['comment'].append('Subvolume {} will be removed'.format(name))
        return ret

    # If commit is set, we wait until all is over
    commit = 'after' if commit else None

    if not exists:
        try:
            __salt__['btrfs.subvolume_delete'](path, commit=commit)
        except CommandExecutionError:
            ret['comment'].append('Error removing subvolume {}'.format(name))
            return ret

        ret['changes'][name] = 'Removed subvolume {}'.format(name)

    ret['result'] = True
    return ret

def commit(self, frame):

        if not frame.transaction:
            raise ProtocolError("Missing transaction for COMMIT command.")

        if not frame.transaction in self.engine.transactions:
            raise ProtocolError("Invalid transaction: %s" % frame.transaction)

        for tframe in self.engine.transactions[frame.transaction]:
            del tframe.headers['transaction']
            self.process_frame(tframe)

        self.engine.queue_manager.clear_transaction_frames(
            self.engine.connection, frame.transaction)
        del self.engine.transactions[frame.transaction]

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


Question: Register a phone.

def register_phone_view(request):
    """"""
    if request.method == "POST":
        form = PhoneRegistrationForm(request.POST)
        logger.debug(form)
        if form.is_valid():
            obj = form.save()
            obj.user = request.user
            obj.save()
            messages.success(request, "Successfully added phone.")
            return redirect("itemreg")
        else:
            messages.error(request, "Error adding phone.")
    else:
        form = PhoneRegistrationForm()
    return render(request, "itemreg/register_form.html", {"form": form, "action": "add", "type": "phone", "form_route": "itemreg_phone"})

public static Registry run(String type, String test) {
    Registry registry = createRegistry(type);
    TESTS.get(test).accept(registry);
    return registry;
  }

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


Question:
// permanodeMatchesAttrVals checks that the values in vals - all of them, if c.ValueAll is set -
// match the values for c.Attr.
// vals are the current permanode values of c.Attr.

func (c *PermanodeConstraint) permanodeMatchesAttrVals(ctx context.Context, s *search, vals []string) (bool, error) {
	if c.NumValue != nil && !c.NumValue.intMatches(int64(len(vals))) {
		return false, nil
	}
	if c.hasValueConstraint() {
		nmatch := 0
		for _, val := range vals {
			match, err := c.permanodeMatchesAttrVal(ctx, s, val)
			if err != nil {
				return false, err
			}
			if match {
				nmatch++
			}
		}
		if nmatch == 0 {
			return false, nil
		}
		if c.ValueAll {
			return nmatch == len(vals), nil
		}
	}
	return true, nil
}

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:
Perform this action on the section state.
@param state The section state.

void perform(SectionState state) {
    state.addChildMode(getModeUsage(), null);
    state.addAttributeValidationModeUsage(getModeUsage());
  }

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

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


Question: Sets a value for a room config

def __set_config_value(self, key, value):
        """"""

        self.check_owner()
        params = {"room": self.room_id, "config": to_json({key: value})}
        resp = self.conn.make_api_call("setRoomConfig", params)
        if "error" in resp:
            raise RuntimeError(f"{resp['error'].get('message') or resp['error']}")
        return resp

func (env *Environment) Register(key, defaultValue string, params map[string]string, t reflect.Type) error {
	env.fields[camelToSnake(key)] = defaultValue
	return nil
}

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


Question: // SetInstanceId sets the InstanceId field's value.

func (s *ListSecurityProfilesInput) SetInstanceId(v string) *ListSecurityProfilesInput {
	s.InstanceId = &v
	return s
}

public KeyArea setupKey(int iKeyArea)
    {
        KeyArea keyArea = null;
        if (iKeyArea == 0)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, ID_KEY);
            keyArea.addKeyField(ID, DBConstants.ASCENDING);
        }
        if (iKeyArea == 1)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, KEY_KEY);
            keyArea.addKeyField(KEY, DBConstants.ASCENDING);
        }
        if (keyArea == null)
            keyArea = super.setupKey(iKeyArea);
        return keyArea;
    }

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


Question: Accepts negative length.

function(length, opt) {

            var index = this.segmentIndexAtLength(length, opt);
            if (!index) return null;

            return this.getSegment(index);
        }

public static boolean isNonCharacter(int ch)
    {
        if ((ch & NON_CHARACTER_SUFFIX_MIN_3_0_) ==
                                            NON_CHARACTER_SUFFIX_MIN_3_0_) {
            return true;
        }

        return ch >= NON_CHARACTER_MIN_3_1_ && ch <=  NON_CHARACTER_MAX_3_1_;
    }

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


Question:
Checks if is initialized.

@param <V> the value type
@param metadata the metadata
@param value the value
@return true, if is initialized

private static <V> boolean isInitialized(Metadata metadata, V value) {
        if (metadata.valueType.getJavaType() == WireFormat.JavaType.MESSAGE) {
            return value != null;
        }
        return true;
    }

private void init(ResourceLoader resourceLoader) throws IOException {
    if (config == null && configs == null) {
      if (resourceLoader == null) {
        return;
      } else if (configFileArgument == null && configArgument == null && analyzerArgument==null) {
        throw new IOException("no configuration");
      } else {
        if (configFileArgument != null) {
          try {
            config = MtasConfiguration.readConfiguration(
                resourceLoader.openResource(configFileArgument));
          } catch (IOException e) {
            throw new IOException(
                "Problem loading configuration from " + configFileArgument, e);
          }
        }
        if (configArgument != null) {
          try {
            configs = MtasConfiguration.readMtasTokenizerConfigurations(
                resourceLoader, configArgument);
          } catch (IOException e) {
            throw new IOException(
                "Problem loading configurations from " + configArgument, e);
          }
        }
        if (analyzerArgument != null) {
          configs = null;
          config = new MtasConfiguration();
          MtasConfiguration subConfig = new MtasConfiguration();
          subConfig.name = "parser";
          subConfig.attributes.put("name", analyzerArgument);
          subConfig.attributes.put(ARGUMENT_PARSER_ARGS, analyzerArgumentParserArgs);
          config.children.add(subConfig);
        }
      }
    }
  }

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


Question:
Setter for customer.

@param pCustomer reference

public final void setCustomer(final DebtorCreditor pCustomer) {
    this.customer = pCustomer;
    if (this.itsId == null) {
      this.itsId = new CustomerGoodsSeenId();
    }
    this.itsId.setCustomer(this.customer);
  }

def send_comment_email(email, package_owner, package_name, commenter):
    """"""
    link = '{CATALOG_URL}/package/{owner}/{pkg}/comments'.format(
        CATALOG_URL=CATALOG_URL, owner=package_owner, pkg=package_name)
    subject = "New comment on {package_owner}/{package_name}".format(
        package_owner=package_owner, package_name=package_name)
    html = render_template('comment_email.html', commenter=commenter, link=link)
    body = render_template('comment_email.txt', commenter=commenter, link=link)
    send_email(recipients=[email], sender=DEFAULT_SENDER, subject=subject,
               html=html, body=body)

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


Question:
Decides whether the client has received tap messages or will receive more
messages in the future.

@return true if the client has tap responses or expects to have responses
in the future. False otherwise.

public boolean hasMoreMessages() {
    if (!rqueue.isEmpty()) {
      return true;
    } else {
      synchronized (omap) {
        Iterator<TapStream> itr = omap.keySet().iterator();
        while (itr.hasNext()) {
          TapStream ts = itr.next();
          if (ts.isCompleted() || ts.isCancelled() || ts.hasErrored()) {
            omap.get(ts).shutdown();
            omap.remove(ts);
          }
        }
        if (omap.size() > 0) {
          return true;
        }
      }
    }
    return false;
  }

func (t token) Check(attempt int, trapdoorKey interface{}) error {

	// This validation, which could be done at Token creation time, is deferred
	// until this point for historical reasons. In particular, this code was
	// extracted from a *leadership* implementation which has a LeadershipCheck
	// method returning a token; if it returned an error as well it would seem
	// to imply that the method implemented a check itself, rather than a check
	// factory.
	//
	// Fixing that would be great but seems out of scope.
	if err := t.secretary.CheckLease(t.leaseKey); err != nil {
		return errors.Annotatef(err, "cannot check lease %q", t.leaseKey.Lease)
	}
	if err := t.secretary.CheckHolder(t.holderName); err != nil {
		return errors.Annotatef(err, "cannot check holder %q", t.holderName)
	}
	return check{
		leaseKey:    t.leaseKey,
		holderName:  t.holderName,
		attempt:     attempt,
		trapdoorKey: trapdoorKey,
		response:    make(chan error),
		stop:        t.stop,
	}.invoke(t.checks)
}

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