Question: This method checks whether a given customer meets a given set of requirements.

def customerMeetsRequirement(self, customer, danceRole=None, registration=None):
        '''

        '''

        cust_reqs = self.customerrequirement_set.filter(customer=customer,met=True)
        if customer:
            cust_priors = customer.eventregistration_set.filter(event__series__isnull=False)
        else:
            cust_priors = EventRegistration.objects.none()

        # If there's an explicit object stating that this customer meets the requirement, then we're done.
        if self.roleEnforced and danceRole and cust_reqs.filter(role=danceRole).exists():
            return True
        elif not self.roleEnforced and cust_reqs.exists():
            return True
        elif self.roleEnforced and not danceRole:
            return False

        # Go through each item for this requirement and see if the customer meets that item
        for item in self.requirementitem_set.all():
            filter_dict = {}
            if item.requiredLevel:
                filter_dict['event__series__classDescription__danceTypeLevel'] = item.requiredLevel
            if item.requiredClass:
                filter_dict['event__series__classDescription'] = item.requiredClass
            if self.roleEnforced:
                filter_dict['role'] = danceRole

            current_matches = 0
            overlap_matches = 0
            nonconcurrent_filter = {'event__endTime__lte': timezone.now()}

            if registration:

                if isinstance(registration,Registration):
                    current_matches = registration.eventregistration_set.filter(**filter_dict).count()
                elif isinstance(registration,TemporaryRegistration):
                    current_matches = registration.temporaryeventregistration_set.filter(**filter_dict).count()

                nonconcurrent_filter = {'event__endTime__lte': registration.firstSeriesStartTime}
                overlap_matches = cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                    event__startTime__lte=registration.lastSeriesEndTime,
                ).count()

            priors_matches = cust_priors.filter(**filter_dict).filter(**nonconcurrent_filter).count()

            # The number of matches depends on the concurrency rule for this item
            if item.concurrentRule == item.ConcurrencyRule.prohibited:
                matches = priors_matches
            elif item.concurrentRule == item.ConcurrencyRule.allowOneOverlapClass:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(1)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowTwoOverlapClasses:
                matches = priors_matches + \
                    cust_priors.filter(**filter_dict).exclude(**nonconcurrent_filter).filter(
                        event__startTime__lte=registration.getTimeOfClassesRemaining(2)
                    ).count()
            elif item.concurrentRule == item.ConcurrencyRule.allowed:
                matches = priors_matches + overlap_matches + \
                    (current_matches if isinstance(registration,TemporaryRegistration) else 0)
            elif item.concurrentRule == item.ConcurrencyRule.required:
                matches = overlap_matches + current_matches

            if matches >= item.quantity:
                # If this is an 'or' or a 'not' requirement, then we are done
                if self.booleanRule == self.BooleanChoice.booleanOr:
                    return True
                if self.booleanRule == self.BooleanChoice.booleanNot:
                    return False
            else:
                # If this is an 'and' requirement and we didn't meet, then we are done
                if self.booleanRule == self.BooleanChoice.booleanAnd:
                    return False

        # If we got this far, then either all 'and' requirements were met, or all 'or' and 'not' requirements were not met
        if self.booleanRule == self.BooleanChoice.booleanOr or self.requirementitem_set.count() == 0:
            return False
        return True

def provide_attr(attr)
      list_item_attr_value = list_item.public_send(attr)

      # Provide user supplied attr
      return list_item_attr_value if list_item_attr_value.present?

      # Provide object supplied attr
      return object_data[attr] if object_available?

      # Provide error - Object is linked but has been deleted
      return 'Object Unavailable' if list_item.object? && !object_available?

      # Provide empty string - no attr supplied and no object linked
      ''
    end

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


Question: // MarshalText encodes the address as hex.

func (a UnprefixedAddress) MarshalText() ([]byte, error) {
	return []byte(hex.EncodeToString(a[:])), nil
}

func (m *multiaddr) String() string {
	s, err := bytesToString(m.bytes)
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
	}
	return s
}

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


Question:
get a single entry by the coordinate location [blockStart, innerStart]

    .. warning:: creates a new instance of a BAMFile object when maybe the one we had would have worked

def fetch_by_coord(self,coord):

    #print coord
    #print self.path
    #b2 = BAMFile(self.path,blockStart=coord[0],innerStart=coord[1],index_obj=self.index,reference=self._reference)
    b2 = BAMFile(self.path,BAMFile.Options(blockStart=coord[0],innerStart=coord[1],reference=self.reference))
    #for bam in b2: print type(bam)
    #print 'hi'
    bam = b2.read_entry()
    b2.close()
    b2 = None
    return bam

def _load_file(self, log_file, message_name_filter_list):

        if isinstance(log_file, str):
            self._file_handle = open(log_file, "rb")
        else:
            self._file_handle = log_file

        # parse the whole file
        self._read_file_header()
        self._last_timestamp = self._start_timestamp
        self._read_file_definitions()

        if self.has_data_appended and len(self._appended_offsets) > 0:
            if self._debug:
                print('This file has data appended')
            for offset in self._appended_offsets:
                self._read_file_data(message_name_filter_list, read_until=offset)
                self._file_handle.seek(offset)

        # read the whole file, or the rest if data appended
        self._read_file_data(message_name_filter_list)

        self._file_handle.close()
        del self._file_handle

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


Question: Exponential smoothing of values

def _smooth(values: List[float], beta: float) -> List[float]:

    avg_value = 0.
    smoothed = []
    for i, value in enumerate(values):
        avg_value = beta * avg_value + (1 - beta) * value
        smoothed.append(avg_value / (1 - beta ** (i + 1)))
    return smoothed

public static <T extends Number> WindowOver<T> varSamp(Expression<T> expr) {
        return new WindowOver<T>(expr.getType(), SQLOps.VARSAMP, expr);
    }

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


Question: // GetMaps returns maps for the given keys.

func (c *MemoryStore) GetMaps(keys []string) (map[string]map[string]interface{}, error) {
	values := make(map[string]map[string]interface{}, len(keys))
	for _, v := range keys {
		value, _ := c.GetMap(v)
		if value != nil {
			values[v] = value
		}
	}

	return values, nil
}

func (y EngineYard) Get(k string) (Engine, bool) {
	e, ok := y[k]
	return e, ok
}

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


Question:
Validates to list of given values to (case-sensitive) match

@param name The field to check
@param values A list of given values to check against

public void expectMatch(String name, List<String> values) {
        expectMatch(name, messages.get(Validation.MATCH_VALUES_KEY.name(), name), values);
    }

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

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


Question:
Converts a file name into a Writer taking in account the output charset. Returns null if the
file name is null.

@GwtIncompatible("Unnecessary")
  private Writer fileNameToLegacyOutputWriter(String fileName) throws IOException {
    if (fileName == null) {
      return null;
    }
    if (isInTestMode()) {
      return new StringWriter();
    }

    return streamToLegacyOutputWriter(filenameToOutputStream(fileName));
  }

@Nonnull
	public static LCharToFltFunction charToFltFunctionFrom(Consumer<LCharToFltFunctionBuilder> buildingFunction) {
		LCharToFltFunctionBuilder builder = new LCharToFltFunctionBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

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


Question:
Apply the action by putting the VM
into the sleeping state on its destination node in a given model

@param m the model to alter
@return {@code true} iff the VM is now sleeping on the destination node

@Override
    public boolean applyAction(Model m) {
        Mapping map = m.getMapping();
        return map.isRunning(vm) &&
                map.getVMLocation(vm).equals(src) &&
                map.addSleepingVM(vm, dst);
    }

def x_build_targets_target( self, node ):
        '''

        '''
        target_node = node
        name = self.get_child_data(target_node,tag='name',strip=True)
        path = self.get_child_data(target_node,tag='path',strip=True)
        jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
        #~ Map for jam targets to virtual targets.
        self.target[jam_target] = {
            'name' : name,
            'path' : path
            }
        #~ Create the ancestry.
        dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
        while dep_node:
            child = self.get_data(dep_node,strip=True)
            child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
            self.parent[child_jam_target] = jam_target
            dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
        return None

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


Question:
Returns a Trustlines object for this account.
 @return [Trustlines]
 @raise [RippleRestError] if RippleRest server returns an error
 @raise [ProtocolError] if protocol is wrong or network is down

def trustlines
      data = RippleRest
        .get("v1/accounts/#{@address}/trustlines")["trustlines"]
        .map(&Trustline.method(:new))
      obj = Trustlines.new data
      obj.account = self
      obj
    end

func WithClients(
	transportType testutils.TransportType,
	keyValueYARPCServer examplepb.KeyValueYARPCServer,
	sinkYARPCServer examplepb.SinkYARPCServer,
	fooYARPCServer examplepb.FooYARPCServer,
	logger *zap.Logger,
	f func(*Clients) error,
) error {
	var procedures []transport.Procedure
	if keyValueYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildKeyValueYARPCProcedures(keyValueYARPCServer)...)
	}
	if sinkYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildSinkYARPCProcedures(sinkYARPCServer)...)
	}
	if fooYARPCServer != nil {
		procedures = append(procedures, examplepb.BuildFooYARPCProcedures(fooYARPCServer)...)
	}
	return testutils.WithClientInfo(
		"example",
		procedures,
		transportType,
		logger,
		func(clientInfo *testutils.ClientInfo) error {
			return f(
				&Clients{
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig),
					examplepb.NewSinkYARPCClient(clientInfo.ClientConfig),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig),
					examplepb.NewKeyValueYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewSinkYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewFooYARPCClient(clientInfo.ClientConfig, protobuf.UseJSON),
					examplepb.NewKeyValueClient(clientInfo.GRPCClientConn),
					examplepb.NewSinkClient(clientInfo.GRPCClientConn),
					examplepb.NewFooClient(clientInfo.GRPCClientConn),
					clientInfo.ContextWrapper,
				},
			)
		},
	)
}

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


Question:
Handle context

@param Context $context
@return Context

@throws AccessDeniedException
@throws NotFoundException
@throws NotImplementedException

public function proceed(Context $context)
    {
        $context = $this->route($context);
        $context = $this->resolve($context);
        $context = $this->guard($context);
        $context = $this->execute($context);
        $context = $this->render($context);

        return $context;
    }

public T authentication(String username, String password, boolean allowAnyHost) {
        if (StringUtils.isNotBlank(username)) {
            if (defaultHost == null || StringUtils.isBlank(defaultHost.getHostName())) {
                throw new IllegalStateException("Cannot configure authentication when host is not set.");
            }
            AuthScope authscope = allowAnyHost ?
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
                    new AuthScope(defaultHost.getHostName(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));
        }
        return self();
    }

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


Question: From Arrays.binarySearch (Comparator). Check with org.roaringbitmap.Util.unsignedBinarySearch

private static int unsignedBinarySearch(int[] a, int fromIndex, int toIndex, int key,
      Comparator<? super Integer> c) {
    int low = fromIndex;
    int high = toIndex - 1;

    while (low <= high) {
      int mid = (low + high) >>> 1;
      int midVal = a[mid];
      int cmp = c.compare(midVal, key);
      if (cmp < 0) {
        low = mid + 1;
      } else if (cmp > 0) {
        high = mid - 1;
      } else {
        return mid; // key found
      }
    }
    return -(low + 1); // key not found.
  }

func ubiquitousChains(chains [][]*x509.Certificate) [][]*x509.Certificate {
	// Filter out chains with highest cross platform ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.ComparePlatformUbiquity)
	// Prefer that all intermediates are SHA-2 certs if the leaf is a SHA-2 cert, in order to improve ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareSHA2Homogeneity)
	// Filter shortest chains
	chains = ubiquity.Filter(chains, ubiquity.CompareChainLength)
	// Filter chains with highest signature hash ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareChainHashUbiquity)
	// Filter chains with highest keyAlgo ubiquity.
	chains = ubiquity.Filter(chains, ubiquity.CompareChainKeyAlgoUbiquity)
	// Filter chains with intermediates that last longer.
	chains = ubiquity.Filter(chains, ubiquity.CompareExpiryUbiquity)
	// Use the optimal strategy as final tie breaker.
	return optimalChains(chains)
}

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


Question:
Save Calendar Entity

@param mixed[] $calendar data to be saved
@param mixed[] $options in case any extras required for conditions

@return mixed[] $response containing the state of save operation

public function saveCalendarEntity(array $calendar = [], array $options = []): array
    {
        $response = [
            'errors' => [],
            'status' => false,
            'entity' => null,
        ];

        $query = $this->find()
            ->where($options['conditions']);

        $query->execute();

        if (!$query->count()) {
            $entity = $this->newEntity();
            $entity = $this->patchEntity($entity, $calendar);
        } else {
            /** @var \Cake\Datasource\EntityInterface $calEntity */
            $calEntity = $query->firstOrFail();
            $entity = $this->patchEntity($calEntity, $calendar);
        }

        $saved = $this->save($entity);

        if ($saved) {
            $response['status'] = true;
            $response['entity'] = $saved;
        } else {
            $response['errors'] = $entity->getErrors();
        }

        return $response;
    }

public static FedoraEvent from(final Event event) {
        requireNonNull(event);
        try {
            @SuppressWarnings("unchecked")
            final Map<String, String> info = new HashMap<>(event.getInfo());

            final String userdata = event.getUserData();
            try {
                if (userdata != null && !userdata.isEmpty()) {
                    final JsonNode json = MAPPER.readTree(userdata);
                    if (json.has(BASE_URL)) {
                        String url = json.get(BASE_URL).asText();
                        while (url.endsWith("/")) {
                            url = url.substring(0, url.length() - 1);
                        }
                        info.put(BASE_URL, url);
                    }
                    if (json.has(USER_AGENT)) {
                        info.put(USER_AGENT, json.get(USER_AGENT).asText());
                    }
                } else {
                    LOGGER.debug("Event UserData is empty!");
                }
            } catch (final IOException ex) {
                LOGGER.warn("Error extracting user data: " + userdata, ex.getMessage());
            }

            final Set<String> resourceTypes = getResourceTypes(event).collect(toSet());

            return new FedoraEventImpl(valueOf(event.getType()), cleanPath(event), resourceTypes,
                    event.getUserID(), FedoraSessionUserUtil.getUserURI(event.getUserID()), ofEpochMilli(event
                            .getDate()), info);

        } catch (final RepositoryException ex) {
            throw new RepositoryRuntimeException("Error converting JCR Event to FedoraEvent", ex);
        }
    }

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


Question: // PushFront inserts the element e at the front of list l.

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

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

	l.head = e
}

protected function ol(array $items, string $marker = '<yellow>%s</yellow>.', int $writer = Output::STANDARD): void
	{
		(new OrderedList($this->output))->draw($items, $marker, $writer);
	}

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


Question:
value:'scName.tbAliasName' value:table
@param table
@param appendAlias

private void addRoutedTableIntoContext(TableWrapper table, ShardRouteConfig routeConfig, boolean appendAlias) {
        FrameContext frameContext = this.getStack().peek();
        String scName = table.getSchemaName();
        String tbName = table.getName();
        String tbAliasName = tbName;
        if (table.getAlias() != null && table.getAlias().getName() != null) {
            tbAliasName = table.getAlias().getName();
        } else {
            if (appendAlias) {
                table.setAlias(new Alias(tbName, true));
            }
        }
        String sdKey = DDRStringUtils.toLowerCase(routeConfig.getSdKey());// sdKey可以为null,当为null时需要通过context路由
        if (scName != null) {
            StringBuilder sb = new StringBuilder();
            sb.append(DDRStringUtils.toLowerCase(scName));
            sb.append('.');
            sb.append(DDRStringUtils.toLowerCase(tbAliasName));
            sb.append('.');
            sb.append(sdKey);
            String key = sb.toString();
            putIntoContext(frameContext, key, table);
            putIntoContext(frameContext, key.substring(scName.length() + 1), table);
            putIntoContext(frameContext, key.substring(scName.length() + 2 + tbAliasName.length()), table);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(DDRStringUtils.toLowerCase(tbAliasName));
            sb.append('.');
            sb.append(sdKey);
            String key = sb.toString();
            putIntoContext(frameContext, key, table);
            putIntoContext(frameContext, key.substring(tbAliasName.length() + 1), table);
        }
    }

public function parseColumnList(&$original_sql, $in_string, $offset_in_original_sql, $warn_empty_aliases)
    {

        $tmpsql = $original_sql;
        $rolling_new_alias_offset = $offset_in_original_sql;
        $collist = $this->tokeniseColumns($in_string);
        foreach ($collist as $k => $colitem) {
            $auto_gen_alias = false;
            if (!$this->parseColumn($k + 1, trim($colitem), $auto_gen_alias, $warn_empty_aliases)) {
                return false;
            }

            $rolling_new_alias_offset += strlen($colitem);
            if ($auto_gen_alias) {
                $tmpsql = substr($tmpsql, 0, $rolling_new_alias_offset) .
                " $auto_gen_alias" . substr($tmpsql, $rolling_new_alias_offset);
                $rolling_new_alias_offset += strlen($auto_gen_alias) + 1;
            }
            $rolling_new_alias_offset += 1;
        }

        $original_sql = $tmpsql;

        return true;
    }

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


Question:
See, http://www.postgresql.org/docs/8.4/interactive/catalog-pg-constraint.html
@return bool. Populate the static variables $this->references $this->isReferencedBy

private function loadReferences()
    {

        // References defined in pg_catalog
        $sql = new Raw('SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false');
        $sql = new Raw( <<<SQL
-- Based on. http://code.google.com/p/pgutils/ but very heavily modified
-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.
WITH "vRelationDescendants" as (
    SELECT
        c.oid,
        c.relname,
        (
            WITH RECURSIVE
            q( oid ) AS
            (
                SELECT
                    crd.oid
                FROM
                    pg_class crd
                WHERE
                    crd.oid = c.oid

                UNION ALL

                SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent
            )
            SELECT oid FROM q WHERE oid = c.oid
        ) as childoid
    FROM
        pg_class c
    INNER JOIN
        pg_namespace n ON n.oid = c.relnamespace
    ORDER BY
        n.nspname, c.relname
), "vAttributeReferences"  as (
    SELECT
        fkr.oid <> fkrd.oid AS "isInheritedSource",
        pkr.oid <> pkrd.oid AS "isInheritedTarget",
        ( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as "isInherited",

        fkn.nspname AS fk_namespace,
        fkr.relname AS fk_relation,
        fkr.oid AS fk_oid,
        fka.attname AS fk_column,
        fka.attnum as "fk_attnum",

        -- initByData
        fkr.oid::text || '.' || fka.attnum::text AS fk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum
            )
        ) AS fk_indexed,
        pkn.nspname AS pk_namespace,
        pkr.relname AS pk_relation,
        pkr.oid AS pk_oid,
        pka.attname AS pk_column,
        pka.attnum as "pk_attnum",

        -- initByData
        pkr.oid::text || '.' || pka.attnum::text AS pk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = pkr.oid AND
                    pg_index.indkey[0] = pka.attnum
            )
        ) AS pk_indexed,
        c.confupdtype::text || c.confdeltype::text AS ud,
        cn.nspname AS c_namespace,
        c.conname AS c_name
    FROM (
        (
            (
                (
                    (
                        (
                            (
                                pg_constraint c
                                    JOIN
                                pg_namespace cn ON cn.oid = c.connamespace
                            )
                            INNER JOIN
                                "vRelationDescendants" as fkrd ON c.conrelid = fkrd.oid
                            INNER JOIN
                                pg_class fkr ON fkr.oid = fkrd.childoid
                        )
                        JOIN
                            pg_namespace fkn ON fkn.oid = fkr.relnamespace
                    )
                    JOIN
                        pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)
                )
                INNER JOIN
                    "vRelationDescendants" as pkrd ON c.confrelid = pkrd.oid
                INNER JOIN
                    pg_class pkr ON pkr.oid = pkrd.childoid
            )
            JOIN
                pg_namespace pkn ON pkn.oid = pkr.relnamespace
        )
        JOIN
            pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)
    )
    WHERE
        c.contype = 'f'::"char" AND
        fkn.nspname = ANY( current_schemas(false) ) AND
        pkn.nspname = ANY( current_schemas(false) )
)
SELECT * FROM "vAttributeReferences" WHERE "isInherited" = false
SQL
        );

        $relationships = $this->db->query($sql);

        foreach( $relationships as $relationship ) {

            $fk = $this->pgAttributes->findOneByKey($relationship['fk_key']);
            $pk = $this->pgAttributes->findOneByKey($relationship['pk_key']);

            if( !$fk or !$pk ) {
                d_pr( $relationship );
                die();
            }

            $fk->addReference($pk);

        }

        // look for normality defined relationships
        $profiler = new Profiler( __FUNCTION__ );
        $profiler->log();

        foreach( $this->pgClasses as $relation ) {

            $tags = $relation->getTags();

            if( isset( $tags['references'] ) ) {

                foreach( $tags['references'] as $reference ) {

                    $reference = array_map( 'trim', explode( '=', $reference) );
                    $reference[1] = explode( '.', $reference[1] );

                    $fk = $relation->getAttributeByName($reference[0]);

                    // referencing
                    $pkTable = $this->pgClasses->findOneByName($reference[1][0]);
                    $pk = $pkTable->getAttributeByName($reference[1][1]);

                    $fk->addReference($pk);

                }

            }

        }

//        echo $profiler->log()->output();

    }

public function ref() : array
    {
        try {
            $ref = $this->gaussianElimination();
        } catch (RuntimeException $e) {
            $ref = $this->rowReductionMethod();
        }

        return $ref;
    }

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


Question:
@param ProductInterface $product
@param float $priceValue
@param float $minimumQuantity
@param null|int $currencyId

@throws ProductDependencyNotFoundException

@return ProductPrice

public function createNewProductPriceForCurrency(
        ProductInterface $product,
        $priceValue,
        $minimumQuantity = 0.0,
        $currencyId = null
    ) {
        // Fetch currency.
        if (!$currencyId) {
            $currency = $this->currencyRepository->findByCode($this->defaultCurrency);
        } else {
            $currency = $this->currencyRepository->find($currencyId);
        }

        if (!$currency) {
            throw new ProductDependencyNotFoundException($this->currencyRepository->getClassName(), $currencyId);
        }

        $productPrice = new ProductPrice();
        $productPrice->setMinimumQuantity($minimumQuantity);
        $productPrice->setPrice($priceValue);
        $productPrice->setProduct($product);
        $productPrice->setCurrency($currency);
        $product->addPrice($productPrice);

        return $productPrice;
    }

public static Message read(DataInputStream is) throws IOException {
        final Field start = Field.read(is);
        if (!(start instanceof NumberField)) {
            throw new IOException("Did not find number field reading start of message; got: " + start);
        }
        if (start.getSize() != 4) {
            throw new IOException("Number field to start message must be of size 4, got: " + start);
        }
        if (((NumberField) start).getValue() != MESSAGE_START.getValue()) {
            throw new IOException("Number field had wrong value to start message. Expected: " + MESSAGE_START +
            ", got: " + start);
        }

        final Field transaction = Field.read(is);
        if (!(transaction instanceof NumberField)) {
            throw new IOException("Did not find number field reading transaction ID of message; got: " + transaction);
        }
        if (transaction.getSize() != 4) {
            throw new IOException("Transaction number field of message must be of size 4, got: " + transaction);
        }

        final Field type = Field.read(is);
        if (!(type instanceof NumberField)) {
            throw new IOException("Did not find number field reading type of message; got: " + type);
        }
        if (type.getSize() != 2) {
            throw new IOException("Type field of message must be of size 2, got: " + type);
        }

        final Field argCountField = Field.read(is);
        if (!(argCountField instanceof NumberField)) {
            throw new IOException("Did not find number field reading argument count of message; got: " + argCountField);
        }
        if (argCountField.getSize() != 1) {
            throw new IOException("Argument count field of message must be of size 1, got: " + argCountField);
        }
        final int argCount = (int)((NumberField)argCountField).getValue();
        if (argCount < 0 || argCount > 12) {
            throw new IOException("Illegal argument count while reading message; must be between 0 and 12, got: " +
            argCount);
        }

        final Field argTypes = Field.read(is);
        if (!(argTypes instanceof BinaryField)) {
            throw new IOException("Did not find binary field reading argument types of message, got: " + argTypes);
        }
        byte[] argTags = new byte[12];
        ((BinaryField)argTypes).getValue().get(argTags);

        Field[] arguments = new Field[argCount];
        Field lastArg = null;
        for (int i = 0; i < argCount; i++) {
            if (argTags[i] == 3 && (lastArg instanceof NumberField) &&
                    ((NumberField) lastArg).getValue() == 0) {
                arguments [i] = new BinaryField(new byte[0]);  // Do not attempt to read a zero-length binary field
            } else {
                arguments[i] = Field.read(is);
            }
            lastArg = arguments[i];
            if (lastArg.getArgumentTag() != argTags[i]) {
                throw new IOException("Found argument of wrong type reading message. Expected tag: " + argTags[i] +
                " and got: " + arguments[i].getArgumentTag());
            }
        }
        Message result = new Message((NumberField)transaction, (NumberField)type, arguments);
        logger.debug("Received> {}", result);
        return result;
    }

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


Question: // Stop safely shuts down the ChanStatusManager.

func (m *ChanStatusManager) Stop() error {
	if !atomic.CompareAndSwapUint32(&m.stopped, 0, 1) {
		return nil
	}

	close(m.quit)
	m.wg.Wait()

	return nil
}

public void afterCompletion(int status) {
		switch (status) {
			case Status.STATUS_COMMITTED:
				txContext.run();
				break;
			default:
		}
		TransactionContextThreadLocal.setTransactionContext(null);
	}

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


Question: Marshall the given parameter object.

public void marshall(ListTagsForResourceRequest listTagsForResourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(listTagsForResourceRequest.getResourceId(), RESOURCEID_BINDING);
            protocolMarshaller.marshall(listTagsForResourceRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(listTagsForResourceRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question: saves a characters data to file

def save_to_file(self, fname):

        with open(fname, 'w') as f:
            f.write(str(self))

@Override
    public void putCharacter(char c) throws IOException {
        if(TerminalTextUtils.isPrintableCharacter(c)) {
            writeToTerminal(translateCharacter(c));
        }
    }

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


Question: Remove the given entries from the textual representation.

def delete_entries(self, entries):

        self.lines = trim([
            line for line in self.lines
            if not isinstance(line, Entry) or line not in entries
        ])

@Override
    public String tagKey(String key) {
        return KEY_CLEANUP_PATTERN.matcher(delegate.tagKey(key)).replaceAll("_");
    }

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


Question: FIXME: Refactor!

public Appender parse( String pattern ) throws IllegalArgumentException
	{
		List<Appender> appenders = new ArrayList<Appender>();
		int prev = 0;
		int pos = 0;
		while ((pos = pattern.indexOf(VAR_START, pos)) >= 0)
		{
			// Add text between beginning/end of last variable
			if ( pos > prev )
			{
				appenders.add(new TextAppender(pattern.substring(prev, pos)));
			}

			// Move to real variable name beginning
			pos += VAR_START_LEN;

			// Next close bracket (not necessarily the variable end bracket if
			// there is a default value with nested variables
			int endVariable = pattern.indexOf(VAR_CLOSE, pos);
			if ( endVariable < 0 )
			{
				throw new IllegalArgumentException(format(
						"Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''", pattern,
						VAR_CLOSE, pos - VAR_START_LEN, pattern.substring(pos - VAR_START_LEN)));
			}

			// Try to skip eventual internal variable here
			int nextVariable = pattern.indexOf(VAR_START, pos);
			// Just used to throw exception with more accurate message
			int lastEndVariable = endVariable;
			boolean hasNested = false;
			while (nextVariable >= 0 && nextVariable < endVariable)
			{
				hasNested = true;
				endVariable = pattern.indexOf(VAR_CLOSE, endVariable + VAR_CLOSE_LEN);
				// Something is badly closed
				if ( endVariable < 0 )
				{
					throw new IllegalArgumentException(format(
							"Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''",
							pattern, VAR_CLOSE, nextVariable, pattern.substring(nextVariable, lastEndVariable)));
				}
				nextVariable = pattern.indexOf(VAR_START, nextVariable + VAR_START_LEN);
				lastEndVariable = endVariable;
			}
			// The chunk to process
			final String rawKey = pattern.substring(pos - VAR_START_LEN, endVariable + VAR_CLOSE_LEN);
			// Key without variable start and end symbols
			final String key = pattern.substring(pos, endVariable);

			int pipeIndex = key.indexOf(PIPE_SEPARATOR);

			boolean hasKeyVariables = false;
			boolean hasDefault = false;
			boolean hasDefaultVariables = false;

			// There is a pipe
			if ( pipeIndex >= 0 )
			{
				// No nested property detected, simple default part
				if ( !hasNested )
				{
					hasDefault = true;
					hasDefaultVariables = false;
				}
				// There is a pipe and nested variable,
				// determine if pipe is for the current variable or a nested key
				// variable
				else
				{
					int nextStartKeyVariable = key.indexOf(VAR_START);
					hasKeyVariables = pipeIndex > nextStartKeyVariable;
					if ( hasKeyVariables )
					{
						// ff${fdf}|${f}
						int nextEndKeyVariable = key.indexOf(VAR_CLOSE, nextStartKeyVariable + VAR_START_LEN);
						pipeIndex = key.indexOf(PIPE_SEPARATOR, nextEndKeyVariable + VAR_CLOSE_LEN);
						while (pipeIndex >= 0 && pipeIndex > nextStartKeyVariable)
						{
							pipeIndex = key.indexOf(PIPE_SEPARATOR, nextEndKeyVariable + VAR_CLOSE_LEN);
							nextStartKeyVariable = key.indexOf(VAR_START, nextStartKeyVariable + VAR_START_LEN);
							// No more nested variable
							if ( nextStartKeyVariable < 0 )
							{
								break;
							}
							nextEndKeyVariable = key.indexOf(VAR_CLOSE, nextEndKeyVariable + VAR_CLOSE_LEN);
							if ( nextEndKeyVariable < 0 )
							{
								throw new IllegalArgumentException(
										format("Syntax error in property value ''{0}'', missing close bracket ''{1}'' for variable beginning at col {2}: ''{3}''",
												pattern, VAR_CLOSE, nextStartKeyVariable, key.substring(nextStartKeyVariable)));
							}
						}
					}

					// nested variables are only for key, current variable does
					// not have a default value
					if ( pipeIndex >= 0 )
					{
						hasDefault = true;
						hasDefaultVariables = key.indexOf(VAR_START, pipeIndex) >= 0;
					}

				}
			}
			// No pipe, there is key variables if nested elements have been
			// detected
			else
			{
				hasKeyVariables = hasNested;
			}

			// Construct variable appenders
			String keyPart = null;
			String defaultPart = null;
			if ( hasDefault )
			{
				keyPart = key.substring(0, pipeIndex).trim();
				defaultPart = key.substring(pipeIndex + PIPE_SEPARATOR_LEN).trim();
			} else
			{
				keyPart = key.trim();
			}
			// Choose TextAppender when relevant to avoid unecessary parsing when it's clearly not needed
			appenders.add(new KeyAppender(this, rawKey, hasKeyVariables ? parse(keyPart) : new TextAppender(keyPart), !hasDefault ? null
					: (hasDefaultVariables ? parse(defaultPart) : new TextAppender(defaultPart))));

			prev = endVariable + VAR_CLOSE_LEN;
			pos = prev;
		}

		if ( prev < pattern.length() )
		{
			appenders.add(new TextAppender(pattern.substring(prev)));
		}

		return appenders.size() == 1 ? appenders.get(0) : new MixinAppender(pattern, appenders);
	}

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

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


Question: // Watch returns a watch.Interface that watches the requested controllerRevisions.

func (c *FakeControllerRevisions) Watch(opts v1.ListOptions) (watch.Interface, error) {
	return c.Fake.
		InvokesWatch(testing.NewWatchAction(controllerrevisionsResource, c.ns, opts))

}

public function setAllowReview($allowReview)
    {
        if (is_bool($allowReview)) {
            $this->allowReview = $allowReview;
        } else {
            $msg = "AllowReview must be a boolean, '" . gettype($allowReview) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question: Attach particular SOAP headers to the request depending on the method call made

def _setHeaders(self, call = None, **kwargs):
    '''

    '''
    # All calls, including utility calls, set the session header
    headers = {'SessionHeader': self._sessionHeader}

    if 'debug_categories' in kwargs:
      #ERROR, WARN, INFO, DEBUG, FINE, FINER, FINEST
      #Db, Workflow, Validation, Callout, Apex Code, Apex Profiling, All
      debug_categories = kwargs['debug_categories']

      headers['DebuggingHeader'] = {
        'categories' : debug_categories
      }

      # headers['DebuggingHeader'] = {
      #   'categories' : {
      #     'category' : kwargs['debug_category'],
      #     'level'    : kwargs['debug_level']
      #   }
      # }

    if call in ('convertLead',
                'create',
                'merge',
                'process',
                'undelete',
                'update',
                'upsert'):
      if self._allowFieldTruncationHeader is not None:
        headers['AllowFieldTruncationHeader'] = self._allowFieldTruncationHeader

    if call in ('create',
                'merge',
                'update',
                'upsert'):
      if self._assignmentRuleHeader is not None:
        headers['AssignmentRuleHeader'] = self._assignmentRuleHeader

    # CallOptions will only ever be set by the SforcePartnerClient
    if self._callOptions is not None:
      if call in ('create',
                  'merge',
                  'queryAll',
                  'query',
                  'queryMore',
                  'retrieve',
                  'search',
                  'update',
                  'upsert',
                  'convertLead',
                  'login',
                  'delete',
                  'describeGlobal',
                  'describeLayout',
                  'describeTabs',
                  'describeSObject',
                  'describeSObjects',
                  'getDeleted',
                  'getUpdated',
                  'process',
                  'undelete',
                  'getServerTimestamp',
                  'getUserInfo',
                  'setPassword',
                  'resetPassword'):
        headers['CallOptions'] = self._callOptions

    if call in ('create',
                'delete',
                'resetPassword',
                'update',
                'upsert'):
      if self._emailHeader is not None:
        headers['EmailHeader'] = self._emailHeader

    if call in ('describeSObject',
                'describeSObjects'):
      if self._localeOptions is not None:
        headers['LocaleOptions'] = self._localeOptions

    if call == 'login':
      if self._loginScopeHeader is not None:
        headers['LoginScopeHeader'] = self._loginScopeHeader

    if call in ('create',
                'merge',
                'query',
                'retrieve',
                'update',
                'upsert'):
      if self._mruHeader is not None:
        headers['MruHeader'] = self._mruHeader

    if call in ('convertLead',
                'create',
                'delete',
                'describeGlobal',
                'describeLayout',
                'describeSObject',
                'describeSObjects',
                'describeTabs',
                'merge',
                'process',
                'query',
                'retrieve',
                'search',
                'undelete',
                'update',
                'upsert'):
      if self._packageVersionHeader is not None:
        headers['PackageVersionHeader'] = self._packageVersionHeader

    if call in ('query',
                'queryAll',
                'queryMore',
                'retrieve'):
      if self._queryOptions is not None:
        headers['QueryOptions'] = self._queryOptions

    if call == 'delete':
      if self._userTerritoryDeleteHeader is not None:
        headers['UserTerritoryDeleteHeader'] = self._userTerritoryDeleteHeader

    #print '\n\n>>>>>>>>>>>>>>>> setting header '
    #print headers

    self._sforce.set_options(soapheaders = headers)

public function setName($name) : self
    {
        if ($this->getMethod() != 'GET') {
            $this->setCsrf(true);
        }

        return $this->addAttribute('name', $name);
    }

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


Question: Return the response to a standard dt impulse.

def response(self):
        """"""
        values = []
        sum_values = 0.
        ma_coefs = self.ma_coefs
        ar_coefs = self.ar_coefs
        ma_order = self.ma_order
        for idx in range(len(self.ma.delays)):
            value = 0.
            if idx < ma_order:
                value += ma_coefs[idx]
            for jdx, ar_coef in enumerate(ar_coefs):
                zdx = idx-jdx-1
                if zdx >= 0:
                    value += ar_coef*values[zdx]
            values.append(value)
            sum_values += value
        return numpy.array(values)

public void setMean(double newMean) {
		double oldMean = mean;
		mean = newMean;
		boolean oldMeanESet = meanESet;
		meanESet = true;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.NORMAL_DISTRIBUTION_TYPE__MEAN, oldMean, mean, !oldMeanESet));
	}

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


Question:
fire a HTMLEvent

@param  {Element} element which element to fire a event on
@param  {string}  type    type of event
@param  {object}  extra   extra data for the event object

function fireEvent(element, type, extra) {
  var event = doc.createEvent('HTMLEvents')
  event.initEvent(type, true, true)

  if (typeof extra === 'object') {
    for (var p in extra) {
      event[p] = extra[p]
    }
  }

  /**
   * A flag to distinguish with other events with the same name generated
   * by another library in the same page.
   */
  event._for = 'weex'

  element.dispatchEvent(event)
}

function onParsingComplete ()
  {
    // Validate defaultParam's value.
    $def = isset($this->props->defaultParam) ? $this->props->defaultParam : null;
    if (!empty($def)) {
      if (!$this->props->defines ($def))
        throw new ComponentException($this,
          "Invalid value for defaultParam on <{$this->getTagName()}>; parameter $def does not exist");

      // Move children to default parameter.
      if ($this->hasChildren ()) {
        $type = $this->props->getTypeOf ($def);
        if ($type != type::content && $type != type::metadata)
          throw new ComponentException($this, sprintf (
            "The macro's default parameter $def can't hold content because its type is %s.",
            type::getNameOf ($type)));

        $param = new Metadata($this->context, ucfirst ($def), $type);
        $this->props->set ($def, $param);
        $param->attachTo ($this);
        $param->setChildren ($this->getChildren ());
      }
    }
    elseif ($this->hasChildren ())
      throw new ComponentException ($this,
        'You may not specify content for this tag because it has no default property');
  }

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


Question:
Change the property on the given node.

@param NodeData $node
@return void

public function execute(NodeData $node)
    {
        $currentPropertyValue = $node->getProperty($this->propertyName);
        $newValueWithReplacedCurrentValue = str_replace($this->currentValuePlaceholder, $currentPropertyValue, $this->newValue);
        $newValueWithReplacedSearch = str_replace($this->search, $this->replace, $newValueWithReplacedCurrentValue);
        $node->setProperty($this->propertyName, $newValueWithReplacedSearch);
    }

function(xmlElement) {
    this.arguments_ = [];
    for (var i = 0, childNode; childNode = xmlElement.childNodes[i]; i++) {
      if (childNode.nodeName.toLowerCase() == 'arg') {
        this.arguments_.push(childNode.getAttribute('name'));
      }
    }
    this.updateParams_();
    Blockly.Procedures.mutateCallers(this);

    // Show or hide the statement input.
    this.setStatements_(xmlElement.getAttribute('statements') !== 'false');
  }

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


Question: sends header with 200 OK status

public function sendOkStatus() {
    $Config = GiroCheckout_SDK_Config::getInstance();

    if ($Config->getConfig('DEBUG_MODE')) {
      GiroCheckout_SDK_Debug_helper::getInstance()->logNotificationOutput('sendOkStatus');
    }

    header('HTTP/1.1 200 OK');
  }

function (req, res) {
        return function (err) {
            if (err) {
                res.writeHead(500);
                res.end(err.toString());
            } else {
                res.writeHead(404);
                res.end();
            }
        };
    }

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


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

func (s *Policy) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Policy"}
	if s.ExcludeResourceTags == nil {
		invalidParams.Add(request.NewErrParamRequired("ExcludeResourceTags"))
	}
	if s.PolicyId != nil && len(*s.PolicyId) < 36 {
		invalidParams.Add(request.NewErrParamMinLen("PolicyId", 36))
	}
	if s.PolicyName == nil {
		invalidParams.Add(request.NewErrParamRequired("PolicyName"))
	}
	if s.PolicyName != nil && len(*s.PolicyName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("PolicyName", 1))
	}
	if s.PolicyUpdateToken != nil && len(*s.PolicyUpdateToken) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("PolicyUpdateToken", 1))
	}
	if s.RemediationEnabled == nil {
		invalidParams.Add(request.NewErrParamRequired("RemediationEnabled"))
	}
	if s.ResourceType == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceType"))
	}
	if s.ResourceType != nil && len(*s.ResourceType) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ResourceType", 1))
	}
	if s.SecurityServicePolicyData == nil {
		invalidParams.Add(request.NewErrParamRequired("SecurityServicePolicyData"))
	}
	if s.ResourceTags != nil {
		for i, v := range s.ResourceTags {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ResourceTags", i), err.(request.ErrInvalidParams))
			}
		}
	}
	if s.SecurityServicePolicyData != nil {
		if err := s.SecurityServicePolicyData.Validate(); err != nil {
			invalidParams.AddNested("SecurityServicePolicyData", err.(request.ErrInvalidParams))
		}
	}

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

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

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

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


Question:
Open a new File
@since 22.06.2006

public void doOpenFile(File[] files)
	{
	    if (files!=null)
	    {
	    	if (files.length==1)
	    	{
	    		File f = files[0];
		    	if (f.isFile())
		    	{
			    	String modFileName = f.getAbsolutePath();
			    	int i = modFileName.lastIndexOf(File.separatorChar);
			    	searchPath = modFileName.substring(0, i);
		    		loadMultimediaOrPlayListFile(Helpers.createURLfromFile(f));
		    	}
		    	else
		    	if (f.isDirectory())
		    	{
			    	searchPath = f.getAbsolutePath();
		    	}
	    	}
	    	else
	    	{
	    		playlistRecieved(null, PlayList.createNewListWithFiles(files, false, false), null);
	    	}
	    }
	}

public function setPublicationDate($publicationDate)
    {
        self::writeFullTag(
            $publicationDate,
            'publication_date',
            true,
            'video:publication_date',
            $this->validator,
            'validatePublicationDate',
            $this->exception,
            'Provided publication date value is not a valid.'
        );

        return $this;
    }

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


Question: // NewMockApplication creates a new mock instance

func NewMockApplication(ctrl *gomock.Controller) *MockApplication {
	mock := &MockApplication{ctrl: ctrl}
	mock.recorder = &MockApplicationMockRecorder{mock}
	return mock
}

func (t Term) Sample(args ...interface{}) Term {
	return constructMethodTerm(t, "Sample", p.Term_SAMPLE, args, map[string]interface{}{})
}

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


Question:
Returns Text Value.
@access		public
@return		string

public function setValue( $value, $cdata = FALSE )
	{
		if( !is_string( $value ) && $value !== NULL )
			throw new InvalidArgumentException( 'Value must be a string or NULL' );

		$value	= preg_replace( "/(.*)<!\[CDATA\[(.*)\]\]>(.*)/iU", "\\1\\2\\3", $value );
		if( $cdata || preg_match( '/&|</', $value ) )												//  string is known or detected to be CDATA
		{
			$dom	= dom_import_simplexml( $this );												//  import node in DOM
			$cdata	= $dom->ownerDocument->createCDATASection( $value );							//  create a new CDATA section
			$dom->nodeValue	= "";																	//  clear node content
			$dom->appendChild( $cdata );															//  add CDATA section
		}
		else 																						//  normal node content
		{
			dom_import_simplexml( $this )->nodeValue	= $value;									//  set node content
		}
	}

def GetModuleText(heading, name, showprivate=False):
        """"""
        und = '='*len(heading)
        if showprivate:
            opts = ':private-members:'
        else:
            opts = ''
        return r'''

%s
%s

.. automodule:: %s
    %s

''' % (heading, und, name, opts)

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


Question:
Restore all fields from value stored in session except if they.
@param fields Fields to restore from session.
@param actionBean ActionBean.
@param context ActionBeanContext.
@throws IllegalAccessException Cannot get access to some fields.

protected void restoreFields(Collection<Field> fields, ActionBean actionBean, ActionBeanContext context) throws IllegalAccessException {
        HttpSession session = context.getRequest().getSession(false);
        if (session != null) {
	        Set<String> parameters = this.getParameters(context.getRequest());
	        for (Field field : fields) {
	            if (!field.isAccessible()) {
	                field.setAccessible(true);
	            }
	            if (!parameters.contains(field.getName())) {
	                // Replace value.
	                Object value = session.getAttribute(getFieldKey(field, actionBean.getClass()));
	                // If value is null and field is primitive, don't set value.
	                if (!(value == null && field.getType().isPrimitive())) {
	                    field.set(actionBean, value);
	                }
	            }
	        }
        }
    }

public void encodeData(AsnOutputStream asnOs) throws MAPException {
        if (this.callSessionUnrelated == null) {
            throw new MAPException(
                    "Error while encoding LCSPrivacyCheck the mandatory parameter callSessionUnrelated is not defined");
        }

        try {
            asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_CALL_SESSION_UNRELATED, this.callSessionUnrelated.getAction());
        } catch (IOException e) {
            throw new MAPException("IOException when encoding parameter LCSPrivacyCheck.callSessionUnrelated", e);
        } catch (AsnException e) {
            throw new MAPException("AsnException when encoding parameter LCSPrivacyCheck.callSessionUnrelated", e);
        }

        if (this.callSessionRelated != null) {
            try {
                asnOs.writeInteger(Tag.CLASS_CONTEXT_SPECIFIC, _TAG_CALL_SESSION_RELATED, this.callSessionRelated.getAction());
            } catch (IOException e) {
                throw new MAPException("IOException when encoding parameter LCSPrivacyCheck.callSessionRelated", e);
            } catch (AsnException e) {
                throw new MAPException("AsnException when encoding parameter LCSPrivacyCheck.callSessionRelated", e);
            }
        }
    }

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


Question:
Awaits for an operation to be completed.

@param service
the media contract
@param operationId
the operation id to wait for.
@return the final state of the operation. If operationId is null, returns OperationState.Succeeded.
@throws ServiceException

public static OperationState await(MediaContract service, String operationId) throws ServiceException {
        if (operationId == null) {
            return OperationState.Succeeded;
        }
        OperationInfo opinfo;
        do {
            opinfo = service.get(Operation.get(operationId));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // intentionally do nothing
            }
        } while (opinfo.getState().equals(OperationState.InProgress));
        return opinfo.getState();
    }

func (c *baselistMachinesCommand) Run(ctx *cmd.Context) error {
	apiclient, err := newAPIClientForMachines(c)
	if err != nil {
		return errors.Trace(err)
	}
	defer apiclient.Close()

	fullStatus, err := apiclient.Status(nil)
	if err != nil {
		if fullStatus == nil {
			// Status call completely failed, there is nothing to report
			return err
		}
		// Display any error, but continue to print status if some was returned
		fmt.Fprintf(ctx.Stderr, "%v\n", err)
	} else if fullStatus == nil {
		return errors.Errorf("unable to obtain the current status")
	}

	formatter := status.NewStatusFormatter(fullStatus, c.isoTime)
	formatted := formatter.MachineFormat(c.machineIds)
	return c.out.Write(ctx, formatted)
}

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


Question:
Prints a parameterized type declaration:

<pre>
T<X>
</pre>

private void printParameterizedType(ParameterizedType parameterizedType)
    throws IOException
  {
    Type rawType = parameterizedType.getRawType();

    if (rawType instanceof Class<?>)
      printClass((Class<?>) rawType);
    else
      printType(rawType);

    print("<");

    Type[] typeParameters = parameterizedType.getActualTypeArguments();

    for (int i = 0; i < typeParameters.length; i++) {
      if (i != 0) {
        print(", ");
      }

      printType(typeParameters[i]);
    }

    print(">");
  }

private void exportInternalAPI(ClassLoader cl) {
        String[] packages = {
            "com.sun.tools.doclets",
            "com.sun.tools.doclets.standard",
            "com.sun.tools.doclets.internal.toolkit",
            "com.sun.tools.doclets.internal.toolkit.taglets",
            "com.sun.tools.doclets.internal.toolkit.builders",
            "com.sun.tools.doclets.internal.toolkit.util",
            "com.sun.tools.doclets.internal.toolkit.util.links",
            "com.sun.tools.doclets.formats.html",
            "com.sun.tools.doclets.formats.html.markup"
        };

        try {
            Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
            Object thisModule = getModuleMethod.invoke(getClass());

            Class<?> moduleClass = Class.forName("java.lang.Module");
            Method addExportsMethod = moduleClass.getDeclaredMethod("addExports", String.class, moduleClass);

            Method getUnnamedModuleMethod = ClassLoader.class.getDeclaredMethod("getUnnamedModule");
            Object target = getUnnamedModuleMethod.invoke(cl);

            for (String pack : packages) {
                addExportsMethod.invoke(thisModule, pack, target);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

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


Question:
// EncodeWithoutSignature returns the url-encoded value of the Token
// before signing has occured (typically for use by external signers).

func (t *Token) EncodeWithoutSignature() string {
	t.header = t.Header.encode()
	t.claim = t.ClaimSet.encode()
	return fmt.Sprintf("%s.%s", t.header, t.claim)
}

func ConvertPrivateKeyToPKCS8(key data.PrivateKey, role data.RoleName, gun data.GUN, passphrase string) ([]byte, error) {
	var (
		err       error
		der       []byte
		blockType = "PRIVATE KEY"
	)

	if passphrase == "" {
		der, err = ConvertTUFKeyToPKCS8(key, nil)
	} else {
		blockType = "ENCRYPTED PRIVATE KEY"
		der, err = ConvertTUFKeyToPKCS8(key, []byte(passphrase))
	}
	if err != nil {
		return nil, fmt.Errorf("unable to convert to PKCS8 key")
	}

	headers := make(map[string]string)
	if role != "" {
		headers["role"] = role.String()
	}

	if gun != "" {
		headers["gun"] = gun.String()
	}

	return pem.EncodeToMemory(&pem.Block{Bytes: der, Type: blockType, Headers: headers}), nil
}

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


Question:
TODO

@param $db DatabaseManager
@param $excepted
@param bool $drop
@return array

public function getStructureDifferences($db, $excepted, $drop = false)
    {
        if (isset($excepted['table'])) {
            $excepted = array($excepted['table'] => $excepted);
        }
        $actions = array();
        foreach ($excepted as $table => $value) {
            $current = $this->getCurrentStructure($db, $table);
            if (count($current) > 0) {
                $dbTable = array_shift($current);
                if ($this->getHash($value) != $this->getHash($dbTable)) {

//                    if(strtolower($value['engine']) != strtolower($dbTable['engine'])) {
//                        $actions[] = array(
//                            'sql' => $this->getChangeEngine($table, $value['engine']),
//                            'action' => 'change_engine'
//                        );
//                    }

                    $subject1 = array($value['fields']);
                    $subject2 = array($dbTable['fields']);

                    foreach ($subject1 as $index => $test1) {
                        $test2 = $subject2[$index];
                        // Search for add and changes
                        foreach ($test1 as $key => $item) {
                            if (isset($test2[$key])) {
                                $item2 = $test2[$key];
                                // possible changes
                                if ($this->getHash($item) !== $this->getHash($item2)) {
                                    $actions[] = array(
                                        'sql' => $this->getAlterChange($table, $item),
                                        'action' => 'alter_field'
                                    );
                                }
                            } else {
                                // create the new instance
                                $actions[] = array('sql' => $this->getAlterAdd($table, $item), 'action' => 'add_field');
                            }
                        }
                        //Search for deletion
                        foreach ($test2 as $key => $item) {
                            if (!isset($test1[$key]) && $drop) {
                                $actions[] = array(
                                    'sql' => $this->getAlterDrop($table, $item, $key),
                                    'action' => 'drop_field'
                                );
                            }
                        }
                    }

                    $test1 = $value['keys'];
                    $test2 = $dbTable['keys'];
                    foreach ($test1 as $key => $item) {
                        if (!$this->haveKey($item, $test2)) {
                            $actions[] = array('sql' => $this->getAddKey($table, $item), 'action' => 'add_key');
                        }
                    }
                    //Search for deletion
                    foreach ($test2 as $key => $item) {
                        if (!$this->haveKey($item, $test1)) {
                            $actions[] = array(
                                'sql' => $this->getDropKey($table, $item),
                                'action' => 'drop_key'
                            );
                        }
                    }

                    $test1 = $value['unique'];
                    $test2 = $dbTable['unique'];
                    foreach ($test1 as $key => $item) {
                        if (!$this->haveUnique($item, $test2)) {
                            $actions[] = array('sql' => $this->getAddKey($table, $item), 'action' => 'add_unique');
                        }
                    }
                    //Search for deletion
                    foreach ($test2 as $key => $item) {
                        if (!$this->haveKey($item, $test1)) {
                            $actions[] = array(
                                'sql' => $this->getDropKey($table, $item),
                                'action' => 'drop_unique'
                            );
                        }
                    }

                }
            } else {
                //                if(!$value instanceof \stdClass) die_stack_trace();
                $actions[] = array('sql' => $this->getCreateTable($value), 'action' => 'create_table');
            }
        }
        if ($current) {
            foreach ($current as $table => $value) {
                if (!isset($excepted[$table]) && $drop) {
                    $actions[] = array('sql' => $this->getDropTable($value), 'action' => 'drop_table');
                }
            }
        }
        return $actions;
    }

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

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


Question: Splits the specified {@link String} with the specified delimiter..

public AsciiString[] split(char delim) {
        final List<AsciiString> res = InternalThreadLocalMap.get().arrayList();

        int start = 0;
        final int length = length();
        for (int i = start; i < length; i++) {
            if (charAt(i) == delim) {
                if (start == i) {
                    res.add(EMPTY_STRING);
                } else {
                    res.add(new AsciiString(value, start + arrayOffset(), i - start, false));
                }
                start = i + 1;
            }
        }

        if (start == 0) { // If no delimiter was found in the value
            res.add(this);
        } else {
            if (start != length) {
                // Add the last element if it's not empty.
                res.add(new AsciiString(value, start + arrayOffset(), length - start, false));
            } else {
                // Truncate trailing empty elements.
                for (int i = res.size() - 1; i >= 0; i--) {
                    if (res.get(i).isEmpty()) {
                        res.remove(i);
                    } else {
                        break;
                    }
                }
            }
        }

        return res.toArray(new AsciiString[0]);
    }

public function build(array $items, $currentUri)
    {
        foreach ($items as $item) {
            if ($item->isDivider()) {
                continue;
            }

            $this->buildItem($item, $currentUri);
        }

        return $items;
    }

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


Question: // Float32 gets float32 data

func (c *secureCookies) Float32(key string) (float32, error) {
	ck, err := c.req.Cookie(key)
	if err != nil {
		return 0, err
	}
	s := parseSecureCookie(c.secret, ck.Value)
	v, err := strconv.ParseFloat(s, 32)
	return float32(v), err
}

func (r *Reader) ReadUint() uint64 {
	tag := r.readByte()
	decoder := uintDecoders[tag]
	if decoder == nil {
		castError(tag, "uint64")
	}
	return decoder(r)
}

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


Question:
Receives a list of VTIMEZONE blocks.

    Parses them and adds them to calendar._timezones.

def timezone(calendar, vtimezones):

    for vtimezone in vtimezones:
        remove_x(vtimezone)  # Remove non standard lines from the block
        fake_file = StringIO()
        fake_file.write(str(vtimezone))  # Represent the block as a string
        fake_file.seek(0)
        timezones = tzical(fake_file)  # tzical does not like strings
        # timezones is a tzical object and could contain multiple timezones
        for key in timezones.keys():
            calendar._timezones[key] = timezones.get(key)

def zone_schedules_backup(self, filename):
        """"""
        _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...",
                     self.systemId, self.location.name)

        schedules = {}

        if self.hotwater:
            _LOGGER.info("Retrieving DHW schedule: %s...",
                         self.hotwater.zoneId)

            schedule = self.hotwater.schedule()
            schedules[self.hotwater.zoneId] = {
                'name': 'Domestic Hot Water',
                'schedule': schedule}

        for zone in self._zones:
            zone_id = zone.zoneId
            name = zone.name

            _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name)

            schedule = zone.schedule()
            schedules[zone_id] = {'name': name, 'schedule': schedule}

        schedule_db = json.dumps(schedules, indent=4)

        _LOGGER.info("Writing to backup file: %s...", filename)
        with open(filename, 'w') as file_output:
            file_output.write(schedule_db)

        _LOGGER.info("Backup completed.")

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


Question: // List runs the list action.

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

func (t *TabletTracker) TabletsInUse() string {
	t.mu.Lock()
	defer t.mu.Unlock()

	var aliases []string
	for alias := range t.usedTablets {
		aliases = append(aliases, alias)
	}
	sort.Strings(aliases)
	return strings.Join(aliases, " ")
}

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


Question: // WithPayload adds the payload to the patch endpoint Id labels update failed response

func (o *PatchEndpointIDLabelsUpdateFailed) WithPayload(payload models.Error) *PatchEndpointIDLabelsUpdateFailed {
	o.Payload = payload
	return o
}

def changepassword(self, event):
        """"""

        old = event.data['old']
        new = event.data['new']
        uuid = event.user.uuid

        # TODO: Write email to notify user of password change

        user = objectmodels['user'].find_one({'uuid': uuid})
        if std_hash(old, self.salt) == user.passhash:
            user.passhash = std_hash(new, self.salt)
            user.save()

            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': True
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('Successfully changed password for user', uuid)
        else:
            packet = {
                'component': 'hfos.enrol.enrolmanager',
                'action': 'changepassword',
                'data': False
            }
            self.fireEvent(send(event.client.uuid, packet))
            self.log('User tried to change password without supplying old one', lvl=warn)

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


Question: Returns main image for given model

def get_main_for(self, model):
        '''

        '''
        try:
            return self.for_model(model).get(is_main=True)
        except models.ObjectDoesNotExist:
            return None

public function outputImage($path, array $params = [], $skipValidation = false)
    {
        $this->validateRequest($path, $params, $skipValidation);

        $this->getLeagueGlideServer()->outputImage($path, $params);
    }

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


Question:
You can modify the container here before it is dumped to PHP code.

@param ContainerBuilder $container

public function process(ContainerBuilder $container)
    {
        if (!$container->has($this->getCollectorServiceName())) {
            return;
        }

        $definition = $container->findDefinition(
            $this->getCollectorServiceName()
        );

        $taggedServices = $container->findTaggedServiceIds(
            $this->getTagName()
        );
        foreach ($taggedServices as $id => $tags) {
            $definition->addMethodCall(
                $this->getCollectorMethodName(),
                [new Reference($id)]
            );
        }
    }

protected function _buildAndExecuteProxyResponse()
    {
        if($this->_responseModifier)
        {
          $data = call_user_func_array($this->_responseModifier, array(&$this->_responseBody, &$this->_responseHeaders));
        }

        $this->_generateProxyResponseHeaders();

        $this->_output($this->_responseBody);
    }

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


Question:
Modifies the "msgCount" belief

@param int - the number to add or remove

private void modifyBeliefCount(int count){
        introspector.setBeliefValue(getLocalName(), Definitions.RECEIVED_MESSAGE_COUNT, getBeliefCount()+count, null);
    }

public function updateRuleData(Rule $rule): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_rule_data')
            ->set('enabled', ':enabled')
            ->set('priority', ':priority')
            ->where(
                $query->expr()->eq('rule_id', ':rule_id')
            )
            ->setParameter('rule_id', $rule->id, Type::INTEGER)
            ->setParameter('enabled', $rule->enabled, Type::BOOLEAN)
            ->setParameter('priority', $rule->priority, Type::INTEGER);

        $query->execute();
    }

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


Question:
Writes the experimental setup to a JSON file

        Parameters
        ----------
        filename : str
            Absolute path where to write the JSON file

def to_json(self, filename):

        with open(filename, 'w') as fp:
            json.dump(dict(stimuli=self.stimuli, inhibitors=self.inhibitors, readouts=self.readouts), fp)

public JsonObject export() {
        JsonObject result = JsonObject.create();
        injectParams(result);

        JsonObject queryJson = JsonObject.create();
        queryPart.injectParamsAndBoost(queryJson);
        return result.put("query", queryJson);
    }

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


Question:
Check if the supplied result is different from the most recently stored
SSL record available.

@param  string  $domain
@param  array  $result
@return void

protected function checkForSslRecordChanges($domain, $result)
    {
        if (! $ssl_history = History::where('meta', $domain)->first()) {
            return;
        }

        if ($ssl_history->record['valid'] !== $result['certificates']['information'][0]['valid_now']) {
            if (! $result['certificates']['information'][0]['valid_now']) {
                $this->eye->status()->setSick('ssl_'.$domain);
                return $this->eye->notifier()->alert(new Invalid(['domain' => $domain]));
            }
        }

        if ($ssl_history->record['revoked'] !== $result['certificates']['information'][0]['revoked']) {
            if ($result['certificates']['information'][0]['revoked']) {
                $this->eye->status()->setSick('ssl_'.$domain);
                return $this->eye->notifier()->alert(new Revoked(['domain' => $domain]));
            }
        }

        if ($ssl_history->record['expires_soon'] !== $result['certificates']['information'][0]['expires_soon']) {
            if ($result['certificates']['information'][0]['expires_soon']) {
                $this->eye->status()->setSick('ssl_'.$domain);
                return $this->eye->notifier()->alert(new Expiring(['domain' => $domain,
                                                                   'valid_to' => $result['certificates']['information'][0]['valid_to']]));
            }
        }

        if ($ssl_history->record['grade'] !== $result['results']['grade']) {
            return $this->eye->notifier()->alert(new GradeChange(['domain' => $domain,
                                                                  'old_grade' => $ssl_history->record['grade'],
                                                                  'new_grade' => $result['results']['grade']]));
        }

        $this->eye->status()->setHealthy('ssl_'.$domain);
    }

def web_modification_time(local_url)
      resp = nil
      Net::HTTP.start(local_url.host, 80) do |http|
        resp = http.head(local_url.path)
      end
      resp['Last-Modified'].nil? ? Time.at(0) : Time.parse(resp['Last-Modified'])
    end

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


Question:
Repositions the low-level layer to read from the specified index.

@param reqIndex
Index to position the file pointer to.

protected synchronized void navigateToIndex(int reqIndex)
			throws IOException {
		// determine if navigation is necessary
		if (reqIndex != index) {
			// ensure that the requested index is valid
			if (reqIndex < 0 || reqIndex >= size) {
				throw new IndexOutOfBoundsException();
			}
			// navigate to requested index in file
			if (reqIndex > index) {
				// forward navigation
				skipForward(reqIndex - index);
			} else {
				// backward navigation
				int backSkips = index - reqIndex;
				if (backSkips < (index / 2)) {
					// check if current index is beyond valid list
					if (index == size) {
						// reset current position to last element in
						// set and adjust index and skip counter.
						index = (size - 1);
						position = lastInsertPosition;
						backSkips = index - reqIndex;
					}
					// move in backward direction
					skipBackward(backSkips);
				} else {
					// it is faster to reset position to the beginning
					// of the file and move forward from there to the
					// requested index
					resetPosition();
					skipForward(reqIndex);
				}
			}
		}
		if (reqIndex != index) {
			throw new IOException("Navigation fault! (required: " + reqIndex
					+ ", yielded: " + index + ")");
		}
	}

public function ensureIndex(array $keys, array $options = array())
    {
        $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
        $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
        $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;

        return $this->riakCollection->ensureIndex($keys, $options);
    }

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


Question: ............................................................ helpers:

function atKey(list, index) {
        if (!isArray(list.value))
            return;

        // see docs/impl-notes.md#at-1
        list = (!isArray(list.value[0].value) &&
            (list.type === "Expression"))
                ? [list] : list.value;

        var pair, type, key;
        for (var i = 0; i < list.length; i++) {
            pair = list[i];
            // return empty thing if value is missing but key matches:
            if (!isArray(pair) &&
                (Node.compare(index, pair) === 0))
                    return new Node();

            type = pair.type;
            pair = pair.value;
            key  = pair[0];
            if (Node.compare(index, key) === 0)
                return (pair.length < 2) ? pair[1]
                    : newLessList(pair.slice(1), type);
        }
    }

public static Pattern catalysisPrecedes(Blacklist blacklist)
	{
		Pattern p = new Pattern(SequenceEntityReference.class, "first ER");
		p.add(linkedER(true), "first ER", "first generic ER");
		p.add(erToPE(), "first generic ER", "first simple controller PE");
		p.add(linkToComplex(), "first simple controller PE", "first controller PE");
		p.add(peToControl(), "first controller PE", "first Control");
		p.add(controlToConv(), "first Control", "first Conversion");
		p.add(new Participant(RelType.OUTPUT, blacklist, true), "first Control", "first Conversion", "linker PE");
		p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "first Conversion", "linker PE");
		p.add(type(SmallMolecule.class), "linker PE");
		p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "linker PE", "second Conversion");
		p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "second Conversion", "linker PE");
		p.add(equal(false), "first Conversion", "second Conversion");

		// make sure that conversions are not replicates or reverse of each other
		// and also outward facing sides of reactions contain at least one non ubique
		p.add(new ConstraintAdapter(3, blacklist)
		{
			@Override
			public boolean satisfies(Match match, int... ind)
			{
				Conversion cnv1 = (Conversion) match.get(ind[0]);
				Conversion cnv2 = (Conversion) match.get(ind[1]);
				SmallMolecule linker = (SmallMolecule) match.get(ind[2]);

				Set<PhysicalEntity> input1 = cnv1.getLeft().contains(linker) ? cnv1.getRight() : cnv1.getLeft();
				Set<PhysicalEntity> input2 = cnv2.getLeft().contains(linker) ? cnv2.getLeft() : cnv2.getRight();
				Set<PhysicalEntity> output1 = cnv1.getLeft().contains(linker) ? cnv1.getLeft() : cnv1.getRight();
				Set<PhysicalEntity> output2 = cnv2.getLeft().contains(linker) ? cnv2.getRight() : cnv2.getLeft();

				if (input1.equals(input2) && output1.equals(output2)) return false;
				if (input1.equals(output2) && output1.equals(input2)) return false;

				if (blacklist != null)
				{
					Set<PhysicalEntity> set = new HashSet<PhysicalEntity>(input1);
					set = blacklist.getNonUbiques(set, RelType.INPUT);
					set.removeAll(output2);
					if (set.isEmpty())
					{
						set.addAll(output2);
						set = blacklist.getNonUbiques(set, RelType.OUTPUT);
						set.removeAll(input1);

						if (set.isEmpty()) return false;
					}
				}
				return true;
			}
		}, "first Conversion", "second Conversion", "linker PE");

		p.add(new RelatedControl(RelType.INPUT, blacklist), "linker PE", "second Conversion", "second Control");
		p.add(controllerPE(), "second Control", "second controller PE");
		p.add(new NOT(compToER()), "second controller PE", "first ER");
		p.add(linkToSpecific(), "second controller PE", "second simple controller PE");
		p.add(type(SequenceEntity.class), "second simple controller PE");
		p.add(peToER(), "second simple controller PE", "second generic ER");
		p.add(linkedER(false), "second generic ER", "second ER");
		p.add(equal(false), "first ER", "second ER");
		return p;
	}

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


Question:
Loads the Error Prone version.

<p>This depends on the Maven build, and will always return {@code Optional.absent()} with other
build systems.

public static Optional<String> loadVersionFromPom() {
    try (InputStream stream = ErrorProneVersion.class.getResourceAsStream(PROPERTIES_RESOURCE)) {
      if (stream == null) {
        return Optional.absent();
      }
      Properties mavenProperties = new Properties();
      mavenProperties.load(stream);
      return Optional.of(mavenProperties.getProperty("version"));
    } catch (IOException expected) {
      return Optional.absent();
    }
  }

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question: Form the union of two closures

public List<Type> union(List<Type> cl1, List<Type> cl2) {
        if (cl1.isEmpty()) {
            return cl2;
        } else if (cl2.isEmpty()) {
            return cl1;
        } else if (cl1.head.tsym == cl2.head.tsym) {
            return union(cl1.tail, cl2.tail).prepend(cl1.head);
        } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
            return union(cl1.tail, cl2).prepend(cl1.head);
        } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
            return union(cl1, cl2.tail).prepend(cl2.head);
        } else {
            // unrelated types
            return union(cl1.tail, cl2).prepend(cl1.head);
        }
    }

def setClosable(self, state):

        self._closable = state
        if state:
            self._closeButton.show()
        else:
            self._closeButton.hide()

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


Question:
Run the given command (with shell=False) and return the output as a
    string.

    Strips the output of enclosing whitespace.

    If the return code is non-zero, throw GitInvocationError.

def call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
         on_error='ignore', returncode=False):

    # start external command process
    p = subprocess.Popen(command, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    # get outputs
    out, _ = p.communicate()

    # throw exception if process failed
    if p.returncode != 0 and on_error == 'raise':
        raise GitInvocationError('Failed to run "%s"' % " ".join(command))

    if returncode:
        return out.strip(), p.returncode
    else:
        return out.strip()

def build(check, sdist):
    """"""
    if check in get_valid_checks():
        check_dir = os.path.join(get_root(), check)
    else:
        check_dir = resolve_path(check)
        if not dir_exists(check_dir):
            abort('`{}` is not an Agent-based Integration or Python package'.format(check))

        check = basepath(check_dir)

    echo_waiting('Building `{}`...'.format(check))

    dist_dir = os.path.join(check_dir, 'dist')
    remove_path(dist_dir)

    result = build_package(check_dir, sdist)
    if result.code != 0:
        abort(result.stdout, result.code)

    echo_info('Build done, artifact(s) in: {}'.format(dist_dir))
    echo_success('Success!')

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


Question:
Return an iterator that starts and the current index and increments
        by the given step.

def iterate(self, index, step, n_cols=70):

        while True:
            if step < 0 and index < 0:
                # Hack to prevent displaying a submission's post if iterating
                # comments in the negative direction
                break
            try:
                yield self.get(index, n_cols=n_cols)
            except IndexError:
                break
            index += step

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

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

	l.head = e
}

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


Question:
Create a {@link RemoteRepository} from a String url

@param url String
@return {@link RemoteRepository}
@throws MalformedURLException exceptions

public static RemoteRepository remoteRepositoryFromUrl(String url) throws MalformedURLException {
        URL parsedUrl = new URL(url);

        StringBuffer id = new StringBuffer(parsedUrl.getHost());
        String path = parsedUrl.getPath();
        if (path.length() > 0) {
            path = path.replaceFirst("/", "").replaceAll("/", "-").replaceAll(":", "-");
            id.append("-");
            id.append(path);
        }

        if (parsedUrl.getPort() > -1) {
            id.append("-");
            id.append(parsedUrl.getPort());
        }

        return new RemoteRepository(id.toString(), "default", url);
    }

def add_reference(self, subj: Node, val: str) -> None:

        match = FHIR_RESOURCE_RE.match(val)
        ref_uri_str = res_type = None
        if match:
            ref_uri_str = val if match.group(FHIR_RE_BASE) else (self._base_uri + urllib.parse.quote(val))
            res_type = match.group(FHIR_RE_RESOURCE)
        elif '://' in val:
            ref_uri_str = val
            res_type = "Resource"
        elif self._base_uri and not val.startswith('#') and not val.startswith('/'):
            ref_uri_str = self._base_uri + urllib.parse.quote(val)
            res_type = val.split('/', 1)[0] if '/' in val else "Resource"
        if ref_uri_str:
            ref_uri = URIRef(ref_uri_str)
            self.add(subj, FHIR.link, ref_uri)
            self.add(ref_uri, RDF.type, FHIR[res_type])

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


Question: // ExtractCities efficiently from a user's message.

func ExtractCities(db *sqlx.DB, in *dt.Msg) ([]dt.City, error) {
	// Interface type is used to expand the args in db.Select below.
	// Although we're only storing strings, []string{} doesn't work.
	var args []interface{}

	// Look for "at", "in", "on" prepositions to signal that locations
	// follow, skipping everything before
	var start int
	for i := range in.Stems {
		switch in.Stems[i] {
		case "at", "in", "on":
			start = i
			break
		}
	}

	// Prepare sentence for iteration
	tmp := regexNonWords.ReplaceAllString(in.Sentence, "")
	words := strings.Fields(strings.Title(tmp))

	// Iterate through words and bigrams to assemble a DB query
	for i := start; i < len(words); i++ {
		args = append(args, words[i])
	}
	bgs := bigrams(words, start)
	for i := 0; i < len(bgs); i++ {
		args = append(args, bgs[i])
	}

	cities := []dt.City{}
	q := `SELECT name, countrycode FROM cities
	      WHERE countrycode='US' AND name IN (?)
	      ORDER BY LENGTH(name) DESC`
	query, arguments, err := sqlx.In(q, args)
	query = db.Rebind(query)
	rows, err := db.Query(query, arguments...)
	if err != nil {
		return nil, err
	}
	defer func() {
		if err = rows.Close(); err != nil {
			log.Info("failed to close db rows.", err)
		}
	}()
	for rows.Next() {
		city := dt.City{}
		if err = rows.Scan(&city.Name, &city.CountryCode); err != nil {
			return nil, err
		}
		cities = append(cities, city)
	}
	if err = rows.Err(); err != nil {
		return nil, err
	}
	if len(cities) == 0 {
		return nil, ErrNotFound
	}
	return cities, nil
}

private static void contextWord(String[] words, int index, int distance, String word, Map<String, List<ContextWord>> map){
        String _word = null;
        if(index > -1 && index < words.length){
            _word = words[index];
        }
        if(_word != null && Utils.isChineseCharAndLengthAtLeastTwo(_word)){
            addToMap(map, word, _word, distance);
        }
    }

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


Question: // Refresh retrieves and parses API data from Coinbase.

func (coinbase *CoinbaseExchange) Refresh() {
	coinbase.LogRequest()
	response := new(CoinbaseResponse)
	err := coinbase.fetch(coinbase.requests.price, response)
	if err != nil {
		coinbase.fail("Fetch", err)
		return
	}

	indices := make(FiatIndices)
	for code, floatStr := range response.Data.Rates {
		price, err := strconv.ParseFloat(floatStr, 64)
		if err != nil {
			coinbase.fail(fmt.Sprintf("Failed to parse float for index %s. Given %s", code, floatStr), err)
			continue
		}
		indices[code] = price
	}
	coinbase.UpdateIndices(indices)
}

def store_pulse_jobs(pulse_job, exchange, routing_key):

    newrelic.agent.add_custom_parameter("exchange", exchange)
    newrelic.agent.add_custom_parameter("routing_key", routing_key)

    JobLoader().process_job(pulse_job)

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


Question:
Add or update a bunch of contact titles.

@param \Symfony\Component\HttpFoundation\Request $request

@return \Symfony\Component\HttpFoundation\Response

public function cpatchAction(Request $request)
    {
        try {
            $data = [];

            $i = 0;
            while ($item = $request->get($i)) {
                if (!isset($item['title'])) {
                    throw new RestException(
                        'There is no title-name for the given title'
                    );
                }

                $data[] = $this->addAndUpdateTitles($item);
                ++$i;
            }

            $this->getDoctrine()->getManager()->flush();
            $view = $this->view($data, 200);
        } catch (EntityNotFoundException $enfe) {
            $view = $this->view($enfe->toArray(), 404);
        } catch (RestException $exc) {
            $view = $this->view($exc->toArray(), 400);
        }

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

func (s *GetIntegrationResponseInput) SetHttpMethod(v string) *GetIntegrationResponseInput {
	s.HttpMethod = &v
	return s
}

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