Question:
Calculate the VA file position given the existing borders.

@param id Object ID
@param dv Data vector
@return Vector approximation

public VectorApproximation calculateApproximation(DBID id, V dv) {
    int[] approximation = new int[dv.getDimensionality()];
    for(int d = 0; d < splitPositions.length; d++) {
      final double val = dv.doubleValue(d);
      final int lastBorderIndex = splitPositions[d].length - 1;

      // Value is below data grid
      if(val < splitPositions[d][0]) {
        approximation[d] = 0;
        if(id != null) {
          LOG.warning("Vector outside of VAFile grid!");
        }
      } // Value is above data grid
      else if(val > splitPositions[d][lastBorderIndex]) {
        approximation[d] = lastBorderIndex - 1;
        if(id != null) {
          LOG.warning("Vector outside of VAFile grid!");
        }
      } // normal case
      else {
        // Search grid position
        int pos = Arrays.binarySearch(splitPositions[d], val);
        pos = (pos >= 0) ? pos : ((-pos) - 2);
        approximation[d] = pos;
      }
    }
    return new VectorApproximation(id, approximation);
  }

public void setUVs(float u, float v, float U, float V)
	{
		this.u = u;
		this.v = v;
		this.U = U;
		this.V = V;
	}

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


Question: o:object, p:pattern

function match( o, p, strict ) {

        var o_type = get_type( o ),
            p_type = get_type( p );

        if ( strict ) {

            // In strict mode, objects must have the same type
            if ( o_type !== p_type ) { return false; }

            switch( o_type ) {

                case 'array':
                    return match_arrays( o, p, true );

                case 'boolean':
                    return o === p;

                case 'nan':
                case 'null':
                case 'undefined':
                    return true;

                case 'function':
                case 'number':
                case 'regexp':
                case 'string':
                    return o.toString() === p.toString();

                case 'object':
                    return match_objects( o, p, true );

            }

        } else {

            switch( p_type ) {

                case 'array':
                    return o_type === 'array'
                                ? match_arrays( o, p, false )
                                : false;

                case 'boolean':
                case 'number':
                case 'string':
                    return p == o;

                case 'function':
                    return !!p( o );

                case 'nan':
                    return isNaN( o );

                case 'null':
                case 'undefined':
                    return o_type === p_type;

                case 'object':
                    return o_type === 'object'
                                ? match_objects( o, p, false )
                                : false;

                case 'regexp':
                    return o_type === 'string' && p.test( o );

            }

        }

    }

def extract(obj, pointer, bypass_ref=False):

    return Pointer(pointer).extract(obj, bypass_ref)

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


Question: Return a list of all accounts matching tax_type.

def find_all_by_tax_type(tax_type)
        raise AccountsListNotLoadedError unless loaded?
        @accounts.inject([]) do | list, account |
          list << account if account.tax_type == tax_type
          list
        end
      end

def kmer_lca(seqs_path: 'path to (optionally gzipped) fasta/fastq input',
             fastq: 'input is fastq; disable autodetection' = False,
             progress: 'show progress bar (sent to stderr)' = False):
    '''

    '''
    conf = tictax.config()
    records = tictax.parse_seqs(seqs_path, fastq)
    print('Classifying sequences…', file=sys.stderr)
    asyncio.get_event_loop().run_until_complete(tictax.oc_classify(records,
                                                                   conf['one_codex_api_key'],
                                                                   progress,
                                                                   True))
    print('✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌 ✓📌', file=sys.stderr)

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


Question:
/*
(non-Javadoc)

@see org.jboss.shrinkwrap.api.container.ClassContainer#deleteClass(java.lang.Class)

@Override
    public T deleteClass(Class<?> clazz) throws IllegalArgumentException {
        Validate.notNull(clazz, "Class must be specified");

        return deleteClasses(clazz);
    }

def wrap_java_property(property)
      pd = property.property_descriptor
      if pd.property_type == Java::JavaLang::String.java_class then
        wrap_java_string_property(property)
      elsif pd.property_type == Java::JavaUtil::Date.java_class then
        wrap_java_date_property(property)
      end
    end

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


Question: // SetJumboFrameCapable sets the JumboFrameCapable field's value.

func (s *Interconnect) SetJumboFrameCapable(v bool) *Interconnect {
	s.JumboFrameCapable = &v
	return s
}

public int getJcrType( PropertyType propertyType ) {
        switch (propertyType) {
            case BOOLEAN:
                return javax.jcr.PropertyType.BOOLEAN;
            case DATETIME:
                return javax.jcr.PropertyType.DATE;
            case DECIMAL:
                return javax.jcr.PropertyType.DECIMAL;
            case HTML:
                return javax.jcr.PropertyType.STRING;
            case INTEGER:
                return javax.jcr.PropertyType.LONG;
            case URI:
                return javax.jcr.PropertyType.URI;
            case ID:
                return javax.jcr.PropertyType.STRING;
            default:
                return javax.jcr.PropertyType.UNDEFINED;
        }
    }

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


Question:
Returns field structure with field resolvers added.
Note that to declare a field resolver for a particular field,
create a resolve<Name>Field() method to your subclass.

@return array

public function getFields()
    {
        $fields = $this->fields();
        $allFields = [];

        foreach ($fields as $name => $field) {
            $resolver = $this->getFieldResolver($name, $field);
            if ($resolver) {
                $field['resolve'] = $resolver;
            }
            $allFields[$name] = $field;
        }

        return $allFields;
    }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
Expires entries or reschedules into the proper bucket if still active.

@param index the wheel being operated on
@param previousTicks the previous number of ticks
@param currentTicks the current number of ticks

void expire(int index, long previousTicks, long currentTicks) {
    Node<K, V>[] timerWheel = wheel[index];

    int start, end;
    if ((currentTicks - previousTicks) >= timerWheel.length) {
      end = timerWheel.length;
      start = 0;
    } else {
      long mask = SPANS[index] - 1;
      start = (int) (previousTicks & mask);
      end = 1 + (int) (currentTicks & mask);
    }

    int mask = timerWheel.length - 1;
    for (int i = start; i < end; i++) {
      Node<K, V> sentinel = timerWheel[(i & mask)];
      Node<K, V> prev = sentinel.getPreviousInVariableOrder();
      Node<K, V> node = sentinel.getNextInVariableOrder();
      sentinel.setPreviousInVariableOrder(sentinel);
      sentinel.setNextInVariableOrder(sentinel);

      while (node != sentinel) {
        Node<K, V> next = node.getNextInVariableOrder();
        node.setPreviousInVariableOrder(null);
        node.setNextInVariableOrder(null);

        try {
          if (((node.getVariableTime() - nanos) > 0)
              || !cache.evictEntry(node, RemovalCause.EXPIRED, nanos)) {
            Node<K, V> newSentinel = findBucket(node.getVariableTime());
            link(newSentinel, node);
          }
          node = next;
        } catch (Throwable t) {
          node.setPreviousInVariableOrder(sentinel.getPreviousInVariableOrder());
          node.setNextInVariableOrder(next);
          sentinel.getPreviousInVariableOrder().setNextInVariableOrder(node);
          sentinel.setPreviousInVariableOrder(prev);
          throw t;
        }
      }
    }
  }

public function setScatterSerieTicks($ID, $Width = 0)
    {
        if (isset($this->Data["ScatterSeries"][$ID])) {
            $this->Data["ScatterSeries"][$ID]["Ticks"] = $Width;
        }
    }

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


Question:
Format the array of URL parameters.

@param  mixed|array  $parameters
@return array

public function formatParameters($parameters)
    {
        $parameters = Arr::wrap($parameters);

        foreach ($parameters as $key => $parameter) {
            if ($parameter instanceof UrlRoutable) {
                $parameters[$key] = $parameter->getRouteKey();
            }
        }

        return $parameters;
    }

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

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

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


Question: // ServiceInspectWithRaw returns the service information and the raw data.

func (cli *Client) ServiceInspectWithRaw(ctx context.Context, serviceID string) (swarm.Service, []byte, error) {
	serverResp, err := cli.get(ctx, "/services/"+serviceID, nil, nil)
	if err != nil {
		if serverResp.statusCode == http.StatusNotFound {
			return swarm.Service{}, nil, serviceNotFoundError{serviceID}
		}
		return swarm.Service{}, nil, err
	}
	defer ensureReaderClosed(serverResp)

	body, err := ioutil.ReadAll(serverResp.body)
	if err != nil {
		return swarm.Service{}, nil, err
	}

	var response swarm.Service
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&response)
	return response, body, err
}

def analyze_traceback(tb, inspection_level=None, limit=None):

    info = []
    tb_level = tb
    extracted_tb = traceback.extract_tb(tb, limit=limit)
    for ii, (filepath, line, module, code) in enumerate(extracted_tb):
        func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)

        d = {"File": filepath,
             "Error Line Number": line,
             "Module": module,
             "Error Line": code,
             "Module Line Number": func_lineno,
             "Custom Inspection": {},
             "Source Code": ''}
        if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
            # Perform advanced inspection on the last `inspection_level` tracebacks.
            d['Source Code'] = ''.join(func_source)
            d['Local Variables'] = get_local_references(tb_level)
            d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
        tb_level = getattr(tb_level, 'tb_next', None)
        info.append(d)

    return info

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


Question: /*Line 77 - 'AtomErrors.js'

function (e) {
/*Line 78 - 'AtomErrors.js' */                if (this.refreshing)
/*Line 79 - 'AtomErrors.js' */                    return;
/*Line 80 - 'AtomErrors.js' */                this.refreshing = true;
/*Line 81 - 'AtomErrors.js' */                try {
/*Line 82 - 'AtomErrors.js' */                    e = e || this.value;
/*Line 83 - 'AtomErrors.js' */                    var ac = e.atomControl;
/*Line 84 - 'AtomErrors.js' */                    if (ac) {
/*Line 85 - 'AtomErrors.js' */                        AtomBinder.refreshValue(ac, "errors");
/*Line 86 - 'AtomErrors.js' */                    }
/*Line 87 - 'AtomErrors.js' */                } finally {
/*Line 88 - 'AtomErrors.js' */                    this.refreshing = false;
/*Line 89 - 'AtomErrors.js' */                }
/*Line 90 - 'AtomErrors.js' */                var p = e._logicalParent || e.parentNode;
/*Line 91 - 'AtomErrors.js' */                if (p) {
/*Line 92 - 'AtomErrors.js' */                    this.refresh(p);
/*Line 93 - 'AtomErrors.js' */                }
/*Line 94 - 'AtomErrors.js' */            }

public static function run(App $app, ?Config $config = null): void
    {
        \ini_set('display_errors', '0');
        \ini_set('html_errors', '0');

        $k1 = new static($config);
        $k1->runApp($app);
    }

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


Question: primaryKeyColumns

function findColumns (pgColumns, schemaName, tableName) {
  return pgColumns
    .filter(o => o.table_schema === schemaName && o.table_name === tableName)
    .reduce((columns, col) => {
      const columnInfo = {
        columnDefault: col.column_default,
        isNullable: col.is_nullable,
        dataType: col.data_type,
        characterMaximumLength: col.character_maximum_length,
        numericScale: col.numeric_scale,
        comment: col.column_comment
      }
      if (columnInfo.dataType === 'ARRAY') {
        columnInfo.array = true
        columnInfo.dataType = col.array_element_type.slice(1)
      } else {
        columnInfo.array = false
      }
      columns[col.column_name] = columnInfo
      return columns
    },
    {}
    )
}

def pprint(sequence, keys=None):

    if len(sequence) > 0:
        columns = calculate_columns(sequence)
        row_format = calculate_row_format(columns, keys)
        header = row_format % dict([(key, key.title()) for key in columns])
        separator = row_format % dict([(key, '-' * columns[key]) for key in columns])

        print(separator)
        print(header)
        print(separator)

        for row in sequence:
            print(row_format % row)

        print(separator)

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


Question: // lineFromConsole reads a line from stdin

func lineFromConsole() (string, error) {
	bytes, _, err := bufio.NewReader(os.Stdin).ReadLine()
	return string(bytes), err
}

protected function getTitle()
    {
        $console = $this->console;

        $title = sprintf(
            "%s\n%s\n%s\n",
            str_repeat(
                '-',
                $console->getWidth()
            ),
            "Humus PHPUnit Module for Zend Framework 2\n"
            . "Author: Sascha-Oliver Prolic",
            str_repeat(
                '-',
                $console->getWidth()
            )
        );

        return $console->colorize($title, ColorInterface::RED);
    }

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


Question: Save the load for a given job id

def save_load(jid, load, minions=None):
    '''

    '''
    conn, mdb = _get_conn(ret=None)
    to_save = _safe_copy(load)

    if PYMONGO_VERSION > _LooseVersion('2.3'):
        #using .copy() to ensure original data for load is unchanged
        mdb.jobs.insert_one(to_save)
    else:
        mdb.jobs.insert(to_save)

@Override
  public void onSave(Result<Void> result)
  {
    StubContainerAmp container = _container;

    if (container != null) {
      container.onSave(result);
    }
    else {
      onSaveChild(result);
    }
  }

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


Question:
Get the decoration (i.e. color) setting for the Shell Output service.

@return null|bool 3-state boolean corresponding to the current color mode

public function getOutputDecorated()
    {
        if ($this->colorMode() === self::COLOR_MODE_AUTO) {
            return;
        } elseif ($this->colorMode() === self::COLOR_MODE_FORCED) {
            return true;
        } elseif ($this->colorMode() === self::COLOR_MODE_DISABLED) {
            return false;
        }
    }

protected function buildUsageLine($usage_data, $options_data) {
    if ($usage_data['use_argv_self']) {
      $self_name = $_SERVER['argv'][0];
    } else {
      $self_name = $usage_data['self'];
    }

    $has_options = (count($options_data['lines']) > 0 ? true : false);
    $has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);

    $out =
      ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
      "  {$self_name}".
      ($has_options ? ' [options]' : '').
      ($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
      "\n";

    return $out;
  }

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


Question:
Set Product order.

@route POST /api/v1/products/sort
@authentication required

public function sort()
    {
        if (!Input::has('sortable')) {
            return $this->jsonErrorResponse('"sortable" is required.');
        }

        $product = Subbly::api('subbly.product')->sort(Input::get('sortable'));

        return $this->jsonResponse(array(),
        array(
            'status' => array('message' => 'Product updated'),
        ));
    }

def _places(client, url_part, query=None, location=None, radius=None,
            keyword=None, language=None, min_price=0, max_price=4, name=None,
            open_now=False, rank_by=None, type=None, region=None, page_token=None):

    params = {"minprice": min_price, "maxprice": max_price}

    if query:
        params["query"] = query
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if keyword:
        params["keyword"] = keyword
    if language:
        params["language"] = language
    if name:
        params["name"] = convert.join_list(" ", name)
    if open_now:
        params["opennow"] = "true"
    if rank_by:
        params["rankby"] = rank_by
    if type:
        params["type"] = type
    if region:
        params["region"] = region
    if page_token:
        params["pagetoken"] = page_token

    url = "/maps/api/place/%ssearch/json" % url_part
    return client._request(url, params)

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


Question:
Updates hash with the bytebuffer given (using at maximum length bytes from that buffer)

@param buffer Array of bytes to be hashed
@param offset Offset to buffer array
@param length Use at maximum `length' bytes (absolute maximum is buffer.length)

public void update(byte buffer[], int offset, int length)
	{
		int index, partlen, i, start;

		/* Length can be told to be shorter, but not inter */
		if ((length - offset) > buffer.length)
			length = buffer.length - offset;

		/* compute number of bytes mod 64 */
		index = (int) (state.count & 0x3f);
		state.count += length;

		partlen = 64 - index;

		if (length >= partlen)
		{
			int[] decode_buf = new int[16];
			if (partlen == 64)
			{
				partlen = 0;
			}
			else
			{
				for (i = 0; i < partlen; i++)
					state.buffer[i + index] = buffer[i + offset];
				transform(state, state.buffer, 0, decode_buf);
			}

			for (i = partlen; (i + 63) < length; i += 64)
			{
				transform(state, buffer, i + offset, decode_buf);
			}

			index = 0;
		}
		else
			i = 0;

		/* buffer remaining input */
		if (i < length)
		{
			start = i;
			for (; i < length; i++)
				state.buffer[index + i - start] = buffer[i + offset];
		}
	}

def getRequest
      m = Request.new
      m.pieceIndex = @pieceIndex
      m.blockOffset = @offset
      m.blockLength = @length
      m
    end

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


Question:
Returns html for property
@param $property
@return string

protected function getGroupTitle($property)
	{
		if ($this->isParentProperty()){

			foreach ($property->getDomain()->getIterator() as $domain) {
				$domainLabel[] = $domain->getLabel();
			}

			$groupTitle = '' . _dh($property->getLabel()) . ''
				. ''
				. _dh(implode(' ', $domainLabel))
				. ' '
				. ' '
				. '';

		}else{
			$groupTitle = '' . _dh($property->getLabel()) . ''
				. ''
				. ' '
				. ''
				. 'getUri()).'\'>'
				. '';
		}
		return $groupTitle;
	}

function ( xhr, type ) {
		type = type || "";
		var result, obj;

		if ( ( regex.json_maybe.test( type ) || string.isEmpty( type ) ) && ( regex.json_wrap.test( xhr.responseText ) && Boolean( obj = json.decode( xhr.responseText, true ) ) ) ) {
			result = obj;
		}
		else if ( regex.xml.test( type ) ) {
			if ( type !== "text/xml" ) {
				xhr.overrideMimeType( "text/xml" );
			}

			result = xhr.responseXML;
		}
		else if ( type === "text/plain" && regex.is_xml.test( xhr.responseText) && xml.valid( xhr.responseText ) ) {
			result = xml.decode( xhr.responseText );
		}
		else {
			result = xhr.responseText;
		}

		return result;
	}

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


Question:
Mark all children of the given node that match the marking filter.

@param DataObject $node Parent node
@return array List of children marked by this operation

protected function markChildren(DataObject $node)
    {
        $this->markExpanded($node);

        // If too many children leave closed
        if ($this->isNodeLimited($node)) {
            // Limited nodes are always expanded
            $this->markClosed($node);
            return [];
        }

        // Iterate children if not limited
        $children = $this->getChildren($node);
        if (!$children) {
            return [];
        }

        // Mark all children
        $markedChildren = [];
        foreach ($children as $child) {
            $markingMatches = $this->markingFilterMatches($child);
            if (!$markingMatches) {
                continue;
            }
            // Mark a child node as unexpanded if it has children and has not already been expanded
            if ($this->getNumChildren($child) > 0 && !$this->isExpanded($child)) {
                $this->markUnexpanded($child);
            } else {
                $this->markExpanded($child);
            }

            $markedChildren[] = $child;
        }
        return $markedChildren;
    }

private static MyNode compactForm(MyNode n) {
        if (n.node.getNodeType() == Node.TEXT_NODE) {
            n.out = n.node.getNodeValue().trim();
        } else {
            n.out = n.node.getNodeName();
            if (n.out.startsWith("m:")) {
                n.out = n.out.substring(2);
            }
            if ("annotation-xml".equals(n.out)) {
                n.out = "";
            }
            if ("pquery".equals(n.out) || "cquery".equals(n.out)) {
                n.out = "";
            }
            if ("mws:qvar".equals(n.out)) {
                final String qname = n.node.getAttributes().getNamedItem("name").toString();
                if (n.qVar == null) {
                    n.out = "\\qvar{x_0}";
                    n.qVar = new HashMap<>();
                    n.qVar.put(qname, 0);
                } else {
                    Integer qInt = n.qVar.get(qname);
                    if (qInt == null) {
                        n.out = "\\qvar{x_" + n.qVar.size() + "}";
                        n.qVar.put(qname, n.qVar.size());
                    } else {
                        n.out = "\\qqvar{x_" + qInt + "}";
                    }
                }
            }
            if (n.node.hasChildNodes()) {
                String sChild = "";
                for (Node childNode = n.node.getFirstChild();
                     childNode != null; childNode = childNode.getNextSibling()) {
                    MyNode ret = compactForm(new MyNode(childNode, n.qVar));
                    String cn = ret.out;
                    n.qVar = ret.qVar;
                    if (!cn.isEmpty()) {
                        sChild += cn + ";";
                    }
                }
                if (sChild.endsWith(";")) {
                    sChild = sChild.substring(0, sChild.length() - 1).trim();
                }
                if (!sChild.isEmpty() && sChild.codePointAt(0) != 8290 && sChild.codePointAt(0) != 8289) {
                    if ("m:annotation-xml".equals(n.node.getNodeName())) {
                        n.out += sChild;
                    } else {
                        n.out += '[' + sChild + ']';
                    }
                }
            }
        }
        if ("mo".equals(n.out)) {
            //Remove empty mo elements
            n.out = "";
        }
        return n;
    }

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


Question:
Returns value of environment variable or default value
@param string $name
@param null $defaultValue
@return mixed value from env or defaultValue

public static function getVar(string $name, $defaultValue = null)
    {
        $value = getenv($name);
        return $value !== false ? $value : $defaultValue;
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question: Pass through to provider GradeEntrySearchSession.get_grade_entries_by_search

def get_grade_entries_by_search(self, grade_entry_query, grade_entry_search):
        """"""
        # Implemented from azosid template for -
        # osid.resource.ResourceSearchSession.get_resources_by_search_template
        if not self._can('search'):
            raise PermissionDenied()
        return self._provider_session.get_grade_entries_by_search(grade_entry_query, grade_entry_search)

protected function registerGroupProvider()
	{
		$this->app['sentry.group'] = $this->app->share(function($app)
		{
			$model = $app['config']['cartalyst/sentry::groups.model'];

			// Define the User model to use for relationships.
			if (method_exists($model, 'setUserModel'))
			{
				$userModel = $app['config']['cartalyst/sentry::users.model'];

				forward_static_call_array(
					array($model, 'setUserModel'),
					array($userModel)
				);
			}

			// Define the user group pivot table name to use for relationships.
			if (method_exists($model, 'setUserGroupsPivot'))
			{
				$pivotTable = $app['config']['cartalyst/sentry::user_groups_pivot_table'];

				forward_static_call_array(
					array($model, 'setUserGroupsPivot'),
					array($pivotTable)
				);
			}

			return new GroupProvider($model);
		});
	}

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


Question:
sets common context variables

contentPage

activeMenuName

activeMenu

rootContext

@param model
@param request
@return

protected String addCommonContextVars(ModelMap model, HttpServletRequest request)
	{
		return addCommonContextVars(model, request, null, null);
	}

function getInitialModel(routeInfo, page) {
    var initModelDeps = {
        appName:    routeInfo.appName,
        tokens:     routeInfo.tokens,
        routeInfo:  routeInfo,
        defaults:   page.defaults,
        activeUser: routeInfo.activeUser || {},
        currentScope: {}
    };

    // if no model, just return empty object
    if (!page.model) {
        return Q.when({});
    }
    // if function, inject and the returned value is the model
    else if (_.isFunction(page.model)) {
        return Q.when(injector.loadModule(page.model, null, { dependencies: initModelDeps }));
    }
    else {
        throw new Error(routeInfo.name + ' page invalid model() format: ' + page.model);
    }
}

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


Question: The manager of the database communication for adding and manipulating posts

public function init(Request $request, $postType, $id, $customFieldKey)
	{
		$postTypeModel = $this->getPostType($postType);
		if(!$postTypeModel){
    		$errorMessages = 'You are not authorized to do this.';
    		return $this->abort($errorMessages);
		}

		// Check if the post type has a identifier
		if(empty($postTypeModel->identifier)){
			$errorMessages = 'The post type does not have a identifier.';
			if(array_has($postTypeModel->errorMessages, 'post_type_identifier_does_not_exist')){
				$errorMessages = $postTypeModel->errorMessages['post_type_identifier_does_not_exist'];
			}
			return $this->abort($errorMessages);
		}

		// Disable editting of form
		if($postTypeModel->disableEdit){
			$errorMessages = 'The post type does not support editting.';
    		if(array_has($postTypeModel->errorMessages, 'post_type_identifier_does_not_support_edit')){
				$errorMessages = $postTypeModel->errorMessages['post_type_identifier_does_not_support_edit'];
    		}
    		return $this->abort($errorMessages);
		}

		// Validate if we need to validate a other post type before showing this post type
		$validateBefore = $this->validatePostTypeBefore($request, $postTypeModel, $id);
		if($validateBefore['status'] === false){
			$errorMessages = $validateBefore['message'];
    		return $this->abort($errorMessages, $validateBefore['config']);
		}

		$sanitizedKeys = $this->getValidationsKeys($postTypeModel);
		foreach($sanitizedKeys as $saniKey => $saniValue){
			$sanitizedKeys[$saniKey] = '';
		}

		$verifiedFields = [];
		$reloadFields = [];
		$reloadFieldsMethod = 'none';

		// For each custom field given, we need to validate the permission
		foreach($request->all() as $key => $value){

			// Lets check if the custom field exists and if we got permission
			$customFieldObject = $this->getCustomFieldObject($postTypeModel, $key);
			if(array_has($customFieldObject, 'single_field_updateable.active')){
				if($customFieldObject['single_field_updateable']['active']){
					$verifiedFields[] = $key;

					if(array_has($customFieldObject, 'single_field_updateable.reload_fields')){
						if(is_array($customFieldObject['single_field_updateable']['reload_fields'])){
							$reloadFieldsMethod = 'specific';
							$reloadFields[] = $customFieldObject['single_field_updateable']['reload_fields'];
						} else if ($customFieldObject['single_field_updateable']['reload_fields'] == '*'){
							$reloadFieldsMethod = 'all';
							$reloadFields[] = $sanitizedKeys;
						}
					}
				}
			}

		}

		// If updating all specific fields is enabled, we override the verified fields
		if($postTypeModel->enableAllSpecificFieldsUpdate){
			$whitelistedCustomFields = $this->getWhitelistedCustomFields($postTypeModel, $request->all());

			$reloadFields = $sanitizedKeys;

			// If there is a exlusion active, lets progress that
			if(is_array($postTypeModel->excludeSpecificFieldsFromUpdate)){
				foreach($postTypeModel->excludeSpecificFieldsFromUpdate as $excludeKey => $excludeValue){
					unset($whitelistedCustomFields[$excludeValue]);
					unset($reloadFields[$excludeValue]);
				}
			}

		} else {
			$whitelistedCustomFields = $this->getWhitelistedCustomFields($postTypeModel, $request->only($verifiedFields));
		}

		$toValidateKeys = [];
		foreach($whitelistedCustomFields as $whiteKey => $whiteValue){
			$customFieldObject = $this->getCustomFieldObject($postTypeModel, $whiteKey);
			if(is_array($customFieldObject)){
				if(array_key_exists('saveable', $customFieldObject) && $customFieldObject['saveable'] == false){

				} else {
					$toValidateKeys[$whiteKey] = $customFieldObject;
				}
			}
		}

		// Validating the request
		$validationRules = $this->validatePostFields($toValidateKeys, $request, $postTypeModel, true);

		// Get the post instance
		$post = $this->findPostInstance($postTypeModel, $request, $postType, $id, 'specific_field_post');
		if(!$post){
			$errorMessages = 'Post does not exist.';
			if(array_has($postTypeModel->errorMessages, 'post_does_not_exist')){
				$errorMessages = $postTypeModel->errorMessages['post_does_not_exist'];
			}
			return $this->abort($errorMessages);
		}

		// Need to remove validations if the logic is false
		$logicValidations = $this->removeValidationsByConditionalLogic($whitelistedCustomFields, $postTypeModel, $post);
		foreach($logicValidations as $postmetaKey => $postmetaValue){
			if($postmetaValue === false){
				if(array_key_exists($postmetaKey, $validationRules)){
					unset($validationRules[$postmetaKey]);
					unset($whitelistedCustomFields[$postmetaKey]);
				}
			}
		}

		$this->validatePost($request, $post, $validationRules);

		// Setting a full request so we can show to the front-end what values were given
		$fullRequest = $request;

		// Regenerate the request to pass it thru existing code
		$request = $this->resetRequestValues($request);
		foreach($whitelistedCustomFields as $postmetaKey => $postmetaValue){
			$request[$postmetaKey] = $postmetaValue;
		}
		// Manipulate the request so we can empty out the values where the conditional field is not shown
		$whitelistedCustomFields = $this->removeValuesByConditionalLogic($whitelistedCustomFields, $postTypeModel, $post);

		if(method_exists($postTypeModel, 'on_edit_single_field_event')){
			$onCheck = $postTypeModel->on_edit_single_field_event($postTypeModel, $post->id, $whitelistedCustomFields);
			if($onCheck['continue'] === false){
				$errorMessages = 'You are not authorized to do this.';
				if(array_key_exists('message', $onCheck)){
					$errorMessages = $onCheck['message'];
				}
				return $this->abort($errorMessages);
			}
		}

		// Saving the post values to the database
		$post = $this->savePostToDatabase('edit', $post, $postTypeModel, $request, $postType, true);

        // Saving the post meta values to the database
		$this->savePostMetaToDatabase($whitelistedCustomFields, $postTypeModel, $post, $fullRequest, $customFieldKey);

		// Lets fire events as registered in the post type
		$this->triggerEvent('on_edit_single_field_event', $postTypeModel, $post->id, $whitelistedCustomFields);

		$successMessage = 'Field succesfully updated.';
		if(array_has($postTypeModel->successMessage, 'field_updated')){
			$successMessage = $postTypeModel->successMessage['field_updated'];
		}

		$show = (new ShowPostController)->init($request, $postType, $id);
		$showResponse = json_decode($show->getContent());

		// Lets return the response
		return response()->json([
			'code' => 'success',
			'show_response' => $showResponse,
			'message' => $successMessage,
			'action' => 'edit',
			'post' => [
				'id' => $post->id,
				'post_title' => $post->post_title,
				'post_name' => $post->post_name,
				'status' => $post->status,
				'post_type' => $post->post_type,
				'created_at' => $post->created_at,
				'updated_at' => $post->updated_at,
			],
			'fields_updated' => $whitelistedCustomFields,
			'fields_given' => $fullRequest->all(),
			'reload_fields_method' => $reloadFieldsMethod,
			'reload_fields' => $reloadFields,
		], 200);
	}

public function savePermissionCategory(array $data = [])
    {
        $model = new PermissionCategory($this->db);
        $model->data($data);
        try{
            $res = $model->saveCategory();
            return $res;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

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


Question:
/*
This routine is only called during debugging.

private InputStream dumpInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream copiedStream = null;
        try {

            byte buf[] = new byte[2048];
            int len;
            while ((len = is.read(buf)) > 0) {
                baos.write(buf, 0, len);
            }
            byte[] streamBytes = baos.toByteArray();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, " InputStream dump ", baos.toString());
            }

            copiedStream = new ByteArrayInputStream(streamBytes);

            is.close();
        } catch (IOException e) {
            // an IOException here will mean that we screwed up the original stream
            // we'll need to return null and the caller will need to attempt to
            // re-obtain the stream
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, " InputStream dump failed ", e);
            }
            FFDCFilter.processException(e, CLASS_NAME + ".dumpInputStream", "630");

        } finally {
            try {
                baos.close();
            } catch (IOException e) {
                //AutoFFDC
            }
        }
        return copiedStream;

    }

func (ini *INI) SetComments(section, key string, comments ...string) {
	sec := ini.getSection(section)

	if key == "" {
		if sec == nil {
			sec = ini.addSection(section)
		}
		sec.Comments = comments
		return
	}

	if item := sec.getItem(key, ini.isCaseSensitive); item != nil {
		item.Comments = comments
	}
}

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


Question: // reference: https://github.com/cloudflare/cloudflared/blob/master/tunneldns/https_upstream.go#L54

func (ex *dohExchanger) Exchange(ctx context.Context, query *dns.Msg) (*dns.Msg, error) {
	queryBuf, err := query.Pack()
	if err != nil {
		return nil, fmt.Errorf("failed to pack DNS query: %s", err)
	}

	// No content negotiation for now, use DNS wire format
	buf, backendErr := ex.exchangeWireformat(queryBuf)
	if backendErr == nil {
		response := &dns.Msg{}
		if err := response.Unpack(buf); err != nil {
			return nil, fmt.Errorf("failed to unpack DNS response from body: %s", err)
		}

		response.Id = query.Id
		return response, nil
	}

	return nil, backendErr
}

func NewDNSProviderConfig(config *Config) (*DNSProvider, error) {
	if config == nil {
		return nil, errors.New("godaddy: the configuration of the DNS provider is nil")
	}

	if config.APIKey == "" || config.APISecret == "" {
		return nil, fmt.Errorf("godaddy: credentials missing")
	}

	if config.TTL < minTTL {
		return nil, fmt.Errorf("godaddy: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL)
	}

	return &DNSProvider{config: config}, nil
}

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


Question:
Get the [dealer_product_ids] column value.

@return   array

public function getDealerProductIds()
    {
        if (null === $this->dealer_product_ids_unserialized) {
            $this->dealer_product_ids_unserialized = array();
        }
        if (!$this->dealer_product_ids_unserialized && null !== $this->dealer_product_ids) {
            $dealer_product_ids_unserialized = substr($this->dealer_product_ids, 2, -2);
            $this->dealer_product_ids_unserialized = $dealer_product_ids_unserialized ? explode(' | ', $dealer_product_ids_unserialized) : array();
        }

        return $this->dealer_product_ids_unserialized;
    }

public function getItem($cacheId, & $success = null)
    {
        if (!$this->hasItem($cacheId)) {
            $success = false;

            return null;
        }

        $cacheId = $this->normalizeKey($cacheId);
        $success = true;

        return unserialize($this->cache->fetch($cacheId));
    }

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


Question: Return table sorted by weighted avg

public VoltTable sortByAverage(String tableName)
    {
        List<ProcProfRow> sorted = new ArrayList<ProcProfRow>(m_table);
        Collections.sort(sorted, new Comparator<ProcProfRow>() {
            @Override
            public int compare(ProcProfRow lhs, ProcProfRow rhs) {
                return compareByAvg(rhs, lhs);  // sort desc
            }
        });

        long sumOfAverage = 0L;
        for (ProcProfRow row : sorted) {
            sumOfAverage += (row.avg * row.invocations);
        }

        VoltTable result = TableShorthand.tableFromShorthand(
                tableName + "(TIMESTAMP:BIGINT, PROCEDURE:VARCHAR, WEIGHTED_PERC:BIGINT, INVOCATIONS:BIGINT," +
                "AVG:BIGINT, MIN:BIGINT, MAX:BIGINT, ABORTS:BIGINT, FAILURES:BIGINT)");
        for (ProcProfRow row : sorted ) {
            result.addRow(row.timestamp, row.procedure, calculatePercent(row.avg * row.invocations, sumOfAverage),
                    row.invocations, row.avg, row.min, row.max, row.aborts, row.failures);
        }

        return result;
    }

protected function set_new_sortorder() {
        $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid'));
        $this->raw_set('sortorder', $this->count_records($search));
    }

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


Question:
The hook called when the form is validated. Is used to validate that the
received nonce is valid.

public function hookIsValid(Dictionary $params)
    {
        // Validate nonce
        $form = $params['form'];
        $request = $params['request'];
        $arguments = $params['arguments'];

        $result = Nonce::validateNonce($form->getName(), $request->session, $arguments);
        $nonce_name = Nonce::getParameterName();
        if ($result === null)
        {
            $params['errors'] = [$nonce_name => [[
                'msg' => 'Nonce was not submitted for form {form}',
                'context' => ['form' => $form->getName()]
            ]]];
            $params['valid'] = false;
        }
        elseif ($result === false)
        {
            $params['errors'] = [$nonce_name => [[
                'msg' => 'Nonce was invalid for form {form}',
                'context' => ['form' => $form->getName()]
            ]]];
            $params['valid'] = false;
        }
    }

public function register(string $vendor, ...$args)
    {
        //determine class
        if (method_exists($this, 'resolve')) {
            $this->packages[$vendor] = $this->resolve(Package::class, $vendor);
        // @codeCoverageIgnoreStart
        } else {
            $this->packages[$vendor] = new Package($vendor);
        }
        // @codeCoverageIgnoreEnd

        //if the type is not pseudo (vendor or root)
        if ($this->packages[$vendor]->getPackageType() !== Package::TYPE_PSEUDO) {
            //let's try to call the bootstrap
            $cradle = $this;

            //we should check for events
            $file = $this->packages[$vendor]->getPackagePath() . '/' . $this->bootstrapFile;

            // @codeCoverageIgnoreStart
            if (file_exists($file)) {
                //so you can access cradle
                //within the included file
                include_once($file);
            } else if (file_exists($file . '.php')) {
                //so the IDE can have color
                include_once($file . '.php');
            }
            // @codeCoverageIgnoreEnd
        }

        return $this;
    }

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


Question: Return the appropriate initialized exception class for a response.

def error_for(response):
    """"""
    klass = error_classes.get(response.status)
    if klass is None:
        if 400 <= response.status < 500:
            klass = ClientError
        if 500 <= response.status < 600:
            klass = ServerError  # pragma: no cover
    return klass(response)

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

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


Question:
?? does not use mode, i think key_labels is unused. a hash is now used 2011-10-11 XXX FIXME
 WARNING, i have not tested this after changing it.

def append_key_label key, label, mode=@mode
      #@key_labels << [key, label] if !@key_labels.include? [key, label]
      @key_hash[mode] << [key, label] if !@key_hash[mode].include? [key, label]
      @repaint_required = true
    end

def render(self, *args, **kwargs):
        '''

        '''
        user_name = kwargs.get('user_name', args[0])
        kind = kwargs.get('kind', args[1])
        num = kwargs.get('num', args[2] if len(args) > 2 else 6)
        with_tag = kwargs.get('with_tag', False)
        glyph = kwargs.get('glyph', '')

        all_cats = MUsage.query_most(user_name, kind, num).objects()
        kwd = {
            'with_tag': with_tag,
            'router': router_post[kind],
            'glyph': glyph
        }
        return self.render_string('modules/info/list_user_equation.html',
                                  recs=all_cats,
                                  kwd=kwd)

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


Question:
Gets the current channel, if the node is connected and online, or null.

This is just a convenience method for {@link Computer#getChannel()} with null check.

@CheckForNull
    public final VirtualChannel getChannel() {
        Computer c = toComputer();
        return c==null ? null : c.getChannel();
    }

private Set<String> findReachableNodes(CmsAppCategoryNode rootNode, HashSet<String> reachableNodes) {

        reachableNodes.add(rootNode.getCategory().getId());
        for (CmsAppCategoryNode child : rootNode.getChildren()) {
            findReachableNodes(child, reachableNodes);
        }
        return reachableNodes;
    }

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


Question: Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given.

def validate(path, regex=None):

    validated = []
    for elem in path:
        key = elem[0]
        strkey = str(key)
        if (regex and (not regex.findall(strkey))):
            raise dpath.exceptions.InvalidKeyName("{} at {} does not match the expression {}"
                                                  "".format(strkey,
                                                            validated,
                                                            regex.pattern))
        validated.append(strkey)

public function checkParamSpecialChars(& $sValue, $aRaw = null)
    {
        if (is_object($sValue)) {
            return $sValue;
        }

        if (is_array($sValue)) {
            $newValue = [];
            foreach ($sValue as $sKey => $sVal) {
                $sValidKey = $sKey;
                if (!$aRaw || !in_array($sKey, $aRaw)) {
                    $this->checkParamSpecialChars($sValidKey);
                    $this->checkParamSpecialChars($sVal);
                    if ($sValidKey != $sKey) {
                        unset($sValue[$sKey]);
                    }
                }
                $newValue[$sValidKey] = $sVal;
            }
            $sValue = $newValue;
        } elseif (is_string($sValue)) {
            $sValue = str_replace(
                ['&', '<', '>', '"', "'", chr(0), '\\', "\n", "\r"],
                ['&', '<', '>', '"', ''', '', '\', '
', '
'],
                $sValue
            );
        }

        return $sValue;
    }

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


Question: Populate the client cache with an instance of the specified type

def populate_client_cache(self, low):
        '''

        '''
        reaction_type = low['state']
        if reaction_type not in self.client_cache:
            log.debug('Reactor is populating %s client cache', reaction_type)
            if reaction_type in ('runner', 'wheel'):
                # Reaction types that run locally on the master want the full
                # opts passed.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts)
                # The len() function will cause the module functions to load if
                # they aren't already loaded. We want to load them so that the
                # spawned threads don't need to load them. Loading in the
                # spawned threads creates race conditions such as sometimes not
                # finding the required function because another thread is in
                # the middle of loading the functions.
                len(self.client_cache[reaction_type].functions)
            else:
                # Reactions which use remote pubs only need the conf file when
                # instantiating a client instance.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts['conf_file'])

@Override
	public void clearCache() {
		entityCache.clearCache(CommerceDiscountRelImpl.class);

		finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

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


Question:
Write 'text' to file ('filename') assuming 'encoding'
    Return (eventually new) encoding

def write(text, filename, encoding='utf-8', mode='wb'):

    text, encoding = encode(text, encoding)
    with open(filename, mode) as textfile:
        textfile.write(text)
    return encoding

def query(self,sql):

    msg = "QUERY\0" + sql + "\0"
    self.sfile.write(msg)

    ret, output = self.__response__()
    reply = str(output[0])

    if ret:
      msg = "Error executing query on server %d:%s" % (ret, reply)
      raise LDBDClientException, msg

    return reply

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


Question: Initialize the Watcher.

protected function initialize($showTests)
    {
        $this->showComment($this->config('root.names.watcher'), 'info');

        if (!$this->is_initialized) {
            $this->loader->loadEverything($showTests);

            $this->is_initialized = true;
        }
    }

public static void listen(ClipboardListener listener, boolean sync) {
		listen(ClipboardMonitor.DEFAULT_TRY_COUNT, ClipboardMonitor.DEFAULT_DELAY, listener, sync);
	}

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


Question:
Add context values.

@param  string|array<string, mixed> $key
@param  mixed                       $value
@return static                      $this

public function with( $key, $value = null ) {
		if ( is_array( $key ) ) {
			$this->context = array_merge( $this->getContext(), $key );
		} else {
			$this->context[ $key ] = $value;
		}
		return $this;
	}

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

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


Question:
Refresh current theme in the editor

@param {boolean} force Forces a reload of the current theme.  It reloads the theme file.

function refresh(force) {
        if (force) {
            currentTheme = null;
        }

        $.when(force && loadCurrentTheme()).done(function () {
            var editor = EditorManager.getActiveEditor();
            if (!editor || !editor._codeMirror) {
                return;
            }

            var cm = editor._codeMirror;
            ThemeView.updateThemes(cm);

            // currentTheme can be undefined, so watch out
            cm.setOption("addModeClass", !!(currentTheme && currentTheme.addModeClass));
        });
    }

def _set_menu_toggles(self):
        """"""

        toggles = [
            (self.main_toolbar, "main_window_toolbar", _("Main toolbar")),
            (self.macro_toolbar, "macro_toolbar", _("Macro toolbar")),
            (self.macro_panel, "macro_panel", _("Macro panel")),
            (self.attributes_toolbar, "attributes_toolbar",
             _("Format toolbar")),
            (self.find_toolbar, "find_toolbar", _("Find toolbar")),
            (self.widget_toolbar, "widget_toolbar", _("Widget toolbar")),
            (self.entry_line_panel, "entry_line_panel", _("Entry line")),
            (self.table_list_panel, "table_list_panel", _("Table list")),
        ]

        for toolbar, pane_name, toggle_label in toggles:
            # Get pane from aui manager
            pane = self._mgr.GetPane(pane_name)

            # Get menu item to toggle
            toggle_id = self.menubar.FindMenuItem(_("View"), toggle_label)
            if toggle_id != -1:
                # Check may fail if translation is incomplete
                toggle_item = self.menubar.FindItemById(toggle_id)

                # Adjust toggle to pane visibility
                toggle_item.Check(pane.IsShown())

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


Question:
Renders the given react element using a web worker.

@param  {ReactElement}   element   - Node to update.
@return {ReactComponent}           - The rendered component instance.

function render(element) {
    // Is the given element valid?
    invariant(
        ReactElement.isValidElement(element),
        'render(): You must pass a valid ReactElement.'
    );

    const id = ReactInstanceHandles.createReactRootID(); // Creating a root id & creating the screen
    const component = instantiateReactComponent(element); // Mounting the app
    const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();

    ReactWWIDOperations.setRoot(new WorkerDomNodeStub('0', 'div', {}));

    // The initial render is synchronous but any updates that happen during
    // rendering, in componentWillMount or componentDidMount, will be batched
    // according to the current batching strategy.
    ReactUpdates.batchedUpdates(() => {
        transaction.perform(() => {
            component.mountComponent(id, transaction, {});
        });
        ReactUpdates.ReactReconcileTransaction.release(transaction);
    });

    return component._instance;
}

function initModelCreate (args) {
    var controller = this
    var model = this.model
    // get accountId column
    var accountIdColumn = model.columnName('accountId')
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // get relations to create from args if any
    var relations = args.create && args.create.relations
    // validate relations
    _.each(relations, (createArgs, relation) => {
        // this will throw error on invalid relation
        model.relation(relation)
    })
    // index inputs
    var input = {
        // whether or not create data includes meta columns
        meta: 'query.meta',
        // url to redirect to on success
        redirect: ['body.redirect', 'query.redirect'],
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/']) {
        this.paths['/'] = {}
    }
    // controller spec
    var node = {
        input: input,
        method: function (args) {
            return create(controller, args, node, relations)
        },
        methodName: 'create',
        role: role,
        template: 'instance',
    }
    // add handler for POST / to create instance
    this.paths['/'].post = [node]
}

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


Question: Sort and spill the current records in response to memory pressure.

@Override
  public long spill(long size, MemoryConsumer trigger) throws IOException {
    if (trigger != this) {
      if (readingIterator != null) {
        return readingIterator.spill();
      }
      return 0L; // this should throw exception
    }

    if (inMemSorter == null || inMemSorter.numRecords() <= 0) {
      return 0L;
    }

    logger.info("Thread {} spilling sort data of {} to disk ({} {} so far)",
      Thread.currentThread().getId(),
      Utils.bytesToString(getMemoryUsage()),
      spillWriters.size(),
      spillWriters.size() > 1 ? " times" : " time");

    ShuffleWriteMetrics writeMetrics = new ShuffleWriteMetrics();

    final UnsafeSorterSpillWriter spillWriter =
      new UnsafeSorterSpillWriter(blockManager, fileBufferSizeBytes, writeMetrics,
        inMemSorter.numRecords());
    spillWriters.add(spillWriter);
    spillIterator(inMemSorter.getSortedIterator(), spillWriter);

    final long spillSize = freeMemory();
    // Note that this is more-or-less going to be a multiple of the page size, so wasted space in
    // pages will currently be counted as memory spilled even though that space isn't actually
    // written to disk. This also counts the space needed to store the sorter's pointer array.
    inMemSorter.reset();
    // Reset the in-memory sorter's pointer array only after freeing up the memory pages holding the
    // records. Otherwise, if the task is over allocated memory, then without freeing the memory
    // pages, we might not be able to get memory for the pointer array.

    taskContext.taskMetrics().incMemoryBytesSpilled(spillSize);
    taskContext.taskMetrics().incDiskBytesSpilled(writeMetrics.bytesWritten());
    totalSpillBytes += spillSize;
    return spillSize;
  }

def fits(self, jobShape):
        """"""
        return jobShape.memory <= self.shape.memory and \
               jobShape.cores <= self.shape.cores and \
               jobShape.disk <= self.shape.disk and \
               (jobShape.preemptable or not self.shape.preemptable)

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


Question:
Fetch an entity from the data store

@return ModelEntityInterface

final public function fetch()
    {
        if(!isset($this->_entity))
        {
            $context = $this->getContext();

            if ($this->invokeCommand('before.fetch', $context) !== false)
            {
                $context->result = $this->_actionFetch($context);
                $this->invokeCommand('after.fetch', $context);
            }

            $this->_entity = ObjectConfig::unbox($context->result);
        }

        return $this->_entity;
    }

func (c *Client) MGet(keys ...string) ([]string, error) {
	tmp := make([]interface{}, len(keys)+1)
	tmp[0] = "MGET"
	for n, k := range keys {
		tmp[n+1] = k
	}
	v, err := c.execOnFirst(true, tmp...)
	if err != nil {
		return nil, err
	}
	switch v.(type) {
	case []interface{}:
		items := v.([]interface{})
		resp := make([]string, len(items))
		for n, item := range items {
			switch item.(type) {
			case string:
				resp[n] = item.(string)
			}
		}
		return resp, nil
	}
	return nil, ErrServerError
}

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


Question: Return a string suitable for JavaScript.

def js_output(self, attrs=None):
        """"""
        result = []
        items = sorted(self.items())
        for key, value in items:
            result.append(value.js_output(attrs))
        return _nulljoin(result)

function _printItem (item) {
  switch(item.type) {
    case 'option':
      console.log(item.index + ': ' + item.label);
      break;
    case 'break':
      for (var breakString = ''; breakString.length < item.charCount;) {
        breakString += item.character;
      }

      console.log(breakString);
      break;
    case 'text':
      console.log(item.text);
      break;
    default:
      console.error('Invalid item type: ' + item.type);
      process.exit();
  }
}

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


Question:
Handling blur event
@param {aria.utils.Event} event
@protected

function (event) {
            var inputField = this.getTextInputField();
            var blurredElement = event.target;

            if (blurredElement === inputField) {
                if (inputField.nextSibling != null && inputField.value === "") {
                    this._makeInputFieldLastChild();
                }
            } else if (blurredElement.parentNode.className.indexOf("highlight") != -1) {
                this.unhighlightOption(blurredElement.parentNode);
            }
            // call TextInput onblur handler with avoidCallback set to true
            this.$TextInput._dom_onblur.call(this, event, true);

            if (this._cfg.onblur) {
                // timeout is needed to retrieve (on every browser) the activeElement
                ariaCoreTimer.addCallback({
                    fn : function () {
                        var isAncestor = ariaUtilsDom.isAncestor;
                        var focusedEl = Aria.$window.document.activeElement;

                        // if onblur is defined and window lost focus ( ==null ) or if focus is not in the widget or
                        // dropdown element
                        if (this._cfg
                                && (focusedEl == null || ((this._dropdownPopup == null || !isAncestor(focusedEl, this._dropdownPopup.domElement)) && !isAncestor(focusedEl, this._domElt)))) {
                            this.evalCallback(this._cfg.onblur);
                        }
                    },
                    scope : this,
                    delay : 100
                });
            }
        }

private function parseAfterThrowing($method, $args, \Throwable $throwable)
    {
        $isCancelThrow = false;
        $this->doAspect($method, 'afterThrowing', function($aspectClassName, $methodName, AfterThrowing $annotation) use($method, $args, $throwable, &$isCancelThrow){
            // 验证异常是否捕获
            if(isset($annotation->allow[0]) || isset($annotation->deny[0]))
            {
                $throwableClassName = get_class($throwable);
                if(isset($annotation->allow[0]))
                {
                    $allowResult = false;
                    foreach($annotation->allow as $rule)
                    {
                        $allowResult = Imi::checkRuleMatch($rule, $throwableClassName);
                        if($allowResult)
                        {
                            break;
                        }
                    }
                    if(!$allowResult)
                    {
                        return;
                    }
                }
                $denyResult = false;
                foreach($annotation->deny as $rule)
                {
                    $denyResult = Imi::checkRuleMatch($rule, $throwableClassName);
                    if($denyResult)
                    {
                        return;
                    }
                }
            }
            // 处理
            $joinPoint = new AfterThrowingJoinPoint('afterThrowing', $method, $args, $this->object, $this, $throwable);
            call_user_func([new $aspectClassName, $methodName], $joinPoint);
            if(!$isCancelThrow && $joinPoint->isCancelThrow())
            {
                $isCancelThrow = true;
            }
        });
        // 不取消依旧抛出
        if(!$isCancelThrow)
        {
            throw $throwable;
        }
    }

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


Question:
Returns the scopes for the given id

@param string $id
@return Set

public function get($id) {
		if (!$this->securities->has($id)) {
			$this->securities->set($id, new Set());
		}
		return $this->securities->get($id);
	}

func (a *ResolveNodeArgs) SetBackendNodeID(backendNodeID BackendNodeID) *ResolveNodeArgs {
	a.BackendNodeID = &backendNodeID
	return a
}

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


Question:
根据主键值返回对应的表名，注意分表的情况

默认表名为：[表前缀] + 全部小写的匹配表名

在以下场景下，需要重写此方法以指定表名
+ 1. 自动匹配的表名与实际表名不符
+ 2. 存在分表
+ 3. Model类名不含有Model_

protected function getTableName($id) {
        $className = get_class($this);
        $pos = strpos($className, '\\Model\\');

        $tableName = $pos !== FALSE ? substr($className, $pos + 7) : $className;
        $tableName = str_replace('\\', '_', trim($tableName, '//'));

        return strtolower($tableName);
    }

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

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


Question:
Set 'AttachmentType' value

@param \AgentSIB\Diadoc\Api\Proto\Events\AttachmentType $value

public function setAttachmentType(\AgentSIB\Diadoc\Api\Proto\Events\AttachmentType $value = null)
    {
        $this->AttachmentType = $value;
    }

public void marshall(DescribeEventAggregatesRequest describeEventAggregatesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeEventAggregatesRequest.getFilter(), FILTER_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getAggregateField(), AGGREGATEFIELD_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Return whether *collection* is compatible with this collection.

        To be compatible *collection* must have the same head, tail and padding
        properties as this collection.

def is_compatible(self, collection):
        '''

        '''
        return all([
            isinstance(collection, Collection),
            collection.head == self.head,
            collection.tail == self.tail,
            collection.padding == self.padding
        ])

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question: // RegisterDefaultPlugins provides a set of default plugins for relay

func RegisterDefaultPlugins(pm *PluginManager) {
	addBuilder(pm)
	addGoFriday(pm)
	addGoStaticBundle(pm)
	addJSWatchBuild(pm)
	addJsClient(pm)
	addWatchBuildRun(pm)
	addCommander(pm)
}

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

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

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


Question:
自动绑定（Autowiring）自动解析（Automatic Resolution）

@param $className
@return object
@throws \Exception

public function build($className)
        {

                if(is_string($className) and $this->offsetExists($className)) {
                        $className =  $this->offsetGet($className);
                        if(is_object($className)) {
                                return $className;
                        }
                }

                // 如果是匿名函数（Anonymous functions），也叫闭包函数（closures）
                if ($className instanceof \Closure) {
                        // 执行闭包函数，并将结果
                        return $this->getClosure($className, $this);
                }
                /** @var \ReflectionClass $reflector */
                $reflector = new \ReflectionClass($className);

                // 检查类是否可实例化, 排除抽象类abstract和对象接口interface
                if (!$reflector->isInstantiable()) {
                        throw new \Exception("Can't instantiate ".$className);
                }

                /** @var \ReflectionMethod $constructor 获取类的构造函数 */
                $constructor = $reflector->getConstructor();
                // 若无构造函数，直接实例化并返回
                if (is_null($constructor)) {
                        return new $className;
                }

                // 取构造函数参数,通过 ReflectionParameter 数组返回参数列表
                $parameters = $constructor->getParameters();
                // 递归解析构造函数的参数
                $dependencies = $this->getDependencies($parameters);
                // 创建一个类的新实例，给出的参数将传递到类的构造函数。
                $class =  $reflector->newInstanceArgs($dependencies);
                $this->aliases[$className] = $class;
                return $class;
        }

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question: // collectMappingSources saves the mapping sources of a profile.

func collectMappingSources(p *profile.Profile, source string) plugin.MappingSources {
	ms := plugin.MappingSources{}
	for _, m := range p.Mapping {
		src := struct {
			Source string
			Start  uint64
		}{
			source, m.Start,
		}
		key := m.BuildID
		if key == "" {
			key = m.File
		}
		if key == "" {
			// If there is no build id or source file, use the source as the
			// mapping file. This will enable remote symbolization for this
			// mapping, in particular for Go profiles on the legacy format.
			// The source is reset back to empty string by unsourceMapping
			// which is called after symbolization is finished.
			m.File = source
			key = source
		}
		ms[key] = append(ms[key], src)
	}
	return ms
}

def match_source(self, src):

        srcs = []

        names = [src.name]
        for col in self.config['assoc_xmatch_columns']:
            if col in src.assoc and src.assoc[col]:
                names += [src.assoc[col]]

        for name in names:
            name = name.replace(' ', '').lower()
            if name not in self._src_dict:
                continue
            srcs += [s for s in self._src_dict[name] if s not in srcs]

        return srcs

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


Question: Executes the use case.

@Override
	public final void run() {

		LOGGER.debug("Executing " + getClass().getSimpleName());
		markAsInProgress();

		if (!Lists.isNullOrEmpty(listeners)) {
			Runnable startUseCaseRunnable = new Runnable() {
				@Override
				public void run() {
					for (UseCaseListener listener : listeners) {
						notifyUseCaseStart(listener);
					}
				}
			};
			if (handler != null) {
				handler.post(startUseCaseRunnable);
			} else {
				startUseCaseRunnable.run();
			}
		}

		Trace trace = null;
		if (timingTrackingEnabled()) {
			trace = TraceHelper.startTrace(getClass());
		}

		try {

			LOGGER.debug("Started " + getClass().getSimpleName());
			executionTime = null;
			startTime = DateUtils.nowMillis();
			doExecute();
			executionTime = DateUtils.nowMillis() - startTime;
			LOGGER.debug("Finished " + getClass().getSimpleName() + ". Execution time: " + DateUtils.formatDuration(executionTime));

			if (trace != null) {
				trace.putAttribute("result", "success");
				trace.incrementMetric("successes", 1);
			}

			markAsSuccessful();

			if (!Lists.isNullOrEmpty(listeners)) {
				Runnable finishedUseCaseRunnable = new Runnable() {
					@Override
					public void run() {
						for (UseCaseListener listener : listeners) {
							notifyFinishedUseCase(listener);
						}
						markAsNotified();
					}
				};
				if (handler != null) {
					handler.post(finishedUseCaseRunnable);
				} else {
					finishedUseCaseRunnable.run();
				}
			}

		} catch (RuntimeException e) {
			if (trace != null) {
				trace.putAttribute("result", "failure");
				trace.incrementMetric("failures", 1);
			}
			final AbstractException abstractException = wrapException(e);
			markAsFailed(abstractException);
			logHandledException(abstractException);

			if (!Lists.isNullOrEmpty(listeners)) {
				Runnable finishedFailedUseCaseRunnable = new Runnable() {
					@Override
					public void run() {
						for (UseCaseListener listener : listeners) {
							notifyFailedUseCase(abstractException, listener);
						}
						markAsNotified();
					}
				};
				if (handler != null) {
					handler.post(finishedFailedUseCaseRunnable);
				} else {
					finishedFailedUseCaseRunnable.run();
				}
			}
		} finally {
			if (trace != null) {
				trace.stop();
			}
		}
	}

def exec(options)
      self.params = options[:params]
      self.request = options[:request]
      self.caller = options[:caller]
      self.options = options.except(:params, :request, :caller)

      setup
      raise Lev.configuration.security_transgression_error, auth_error_details unless authorized?
      validate_paramified_params
      handle unless errors?
    end

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


Question:
Load GIT Info
@throws \RuntimeException

protected function loadGitInfo()
    {
        // Carregar versao
        $process = new Process('git log --pretty="%H" -n1 HEAD', base_path());
        if ($process->run() != 0)
            throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from git repository clone and that git binary is available.');
        $this->params['package_version'] = trim($process->getOutput());

        // Carregar Data de atualizacao
        $process = new Process('git log -n1 --pretty=%ci HEAD', base_path());
        if ($process->run() != 0)
            throw new \RuntimeException('Can\'t run git log. You must ensure to run compile from git repository clone and that git binary is available.');

        $date = new \DateTime(trim($process->getOutput()));
        $date->setTimezone(new \DateTimeZone('UTC'));
        $this->versionDate = $date->format('Y-m-d H:i:s');
        $this->params['release_date'] = trim($process->getOutput());
    }

func (g *GormTransaction) Commit() error {
	err := g.db.Commit().Error
	g.db = nil
	return errors.WithStack(err)
}

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


Question:
Returns whether or not `seq1` is a subsequence of `seq2`. That is, whether
 or not `seq2` contains every element in `seq1` in the same order (and
 possibly more elements besides).

 @param seq1 [Array]
 @param seq2 [Array]
 @return [Boolean]

def subsequence?(seq1, seq2)
      i = j = 0
      loop do
        return true if i == seq1.size
        return false if j == seq2.size
        i += 1 if seq1[i] == seq2[j]
        j += 1
      end
    end

def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - assignment_id
        """ID"""
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # OPTIONAL - include
        """Associations to include with the group."""
        if include is not None:
            self._validate_enum(include, ["submission_history", "submission_comments", "rubric_assessment", "visibility", "course", "user"])
            params["include"] = include

        self.logger.debug("GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id}".format(**path), data=data, params=params, no_data=True)

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


Question:
Returns true if the passed MessagePart fails the filter's signedpart
filter settings.

@param MessagePart $part
@return boolean

private function failsSignedPartFilter(MessagePart $part)
    {
        if ($this->signedpart === static::FILTER_OFF) {
            return false;
        } elseif (!$part->isMime() || $part->getParent() === null) {
            return ($this->signedpart === static::FILTER_INCLUDE);
        }
        $partMimeType = $part->getContentType();
        $parentMimeType = $part->getParent()->getContentType();
        $parentProtocol = $part->getParent()->getHeaderParameter('Content-Type', 'protocol');
        if (strcasecmp($parentMimeType, 'multipart/signed') === 0 && strcasecmp($partMimeType, $parentProtocol) === 0) {
            return ($this->signedpart === static::FILTER_EXCLUDE);
        }
        return ($this->signedpart === static::FILTER_INCLUDE);
    }

@VisibleForTesting
  protected void validateHttpRpcPluginPath(final String path) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(path),
        "Invalid HttpRpcPlugin path. Path is null or empty.");
    final String testPath = path.trim();
    Preconditions.checkArgument(!HAS_PLUGIN_BASE_WEBPATH.matcher(path).matches(),
        "Invalid HttpRpcPlugin path %s. Path contains system's plugin base path.",
        testPath);

    URI uri = URI.create(testPath);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(uri.getPath()),
        "Invalid HttpRpcPlugin path %s. Parsed path is null or empty.", testPath);
    Preconditions.checkArgument(!uri.getPath().equals("/"),
        "Invalid HttpRpcPlugin path %s. Path is equal to root.", testPath);
    Preconditions.checkArgument(Strings.isNullOrEmpty(uri.getQuery()),
        "Invalid HttpRpcPlugin path %s. Path contains query parameters.", testPath);
  }

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


Question:
Perform min across the DataFrame.

        Args:
            axis (int): The axis to take the min on.
            skipna (bool): True to skip NA values, false otherwise.

        Returns:
            The min of the DataFrame.

def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):

        axis = self._get_axis_number(axis) if axis is not None else 0
        data = self._validate_dtypes_min_max(axis, numeric_only)
        return data._reduce_dimension(
            data._query_compiler.min(
                axis=axis,
                skipna=skipna,
                level=level,
                numeric_only=numeric_only,
                **kwargs
            )
        )

def framesToFrameRanges(frames, zfill=0):

        _build = FrameSet._build_frange_part
        curr_start = None
        curr_stride = None
        curr_frame = None
        last_frame = None
        curr_count = 0
        for curr_frame in frames:
            if curr_start is None:
                curr_start = curr_frame
                last_frame = curr_frame
                curr_count += 1
                continue
            if curr_stride is None:
                curr_stride = abs(curr_frame-curr_start)
            new_stride = abs(curr_frame-last_frame)
            if curr_stride == new_stride:
                last_frame = curr_frame
                curr_count += 1
            elif curr_count == 2 and curr_stride != 1:
                yield _build(curr_start, curr_start, None, zfill)
                curr_start = last_frame
                curr_stride = new_stride
                last_frame = curr_frame
            else:
                yield _build(curr_start, last_frame, curr_stride, zfill)
                curr_stride = None
                curr_start = curr_frame
                last_frame = curr_frame
                curr_count = 1
        if curr_count == 2 and curr_stride != 1:
            yield _build(curr_start, curr_start, None, zfill)
            yield _build(curr_frame, curr_frame, None, zfill)
        else:
            yield _build(curr_start, curr_frame, curr_stride, zfill)

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


Question:
Sequence ::= SequenceStart WSC SequenceValue? WSC SequenceEnd
        Set := SetStart WSC SequenceValue? WSC SetEnd
        SequenceValue ::= Value (WSC SeparatorSymbol WSC Value)*

def parse_iterable(self, stream, start, end):

        values = []

        self.expect(stream, start)
        self.skip_whitespace_or_comment(stream)

        if self.has_next(end, stream):
            self.expect(stream, end)
            return values

        while 1:
            self.skip_whitespace_or_comment(stream)
            values.append(self.parse_value(stream))
            self.skip_whitespace_or_comment(stream)

            if self.has_next(end, stream):
                self.expect(stream, end)
                return values

            self.expect(stream, self.seporator)

Scope enterScope() {
    final Map<VarKey, Variable> currentFrame = new LinkedHashMap<>();
    final Label scopeExit = new Label();
    frames.push(currentFrame);
    return new Scope() {
      boolean exited;

      @Override
      Variable createSynthetic(
          SyntheticVarName varName, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.SYNTHETIC, varName.name());
        // synthetics are prefixed by $ by convention
        String name = fieldNames.generateName("$" + varName.name());
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Variable createTemporary(String name, Expression initExpr) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.TEMPORARY, name);
        name = fieldNames.generateName("$$" + name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, SaveStrategy.NEVER);
      }

      @Override
      Variable create(String name, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.USER_DEFINED, name);
        name = fieldNames.generateName(name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Statement exitScope() {
        checkState(!exited, "Scope already exited");
        exited = true;
        frames.pop();
        // Use identity semantics to make sure we visit each label at most once.  visiting a label
        // more than once tends to corrupt internal asm state.
        final Set<Label> endLabels = Sets.newIdentityHashSet();
        for (Variable var : currentFrame.values()) {
          endLabels.add(var.local.end());
          availableSlots.clear(
              var.local.index(), var.local.index() + var.local.resultType().getSize());
        }
        return new Statement() {
          // TODO(lukes): we could generate null writes for when object typed fields go out of
          // scope.  This would potentially allow intermediate results to be collected sooner.
          @Override
          protected void doGen(CodeBuilder adapter) {
            for (Label label : endLabels) {
              adapter.visitLabel(label);
            }
          }
        };
      }

      private Variable doCreate(
          String name,
          Label start,
          Label end,
          Expression initExpr,
          VarKey key,
          SaveStrategy strategy) {
        int index = reserveSlotFor(initExpr.resultType());
        LocalVariable local =
            LocalVariable.createLocal(name, index, initExpr.resultType(), start, end);
        Variable var;
        switch (strategy) {
          case DERIVED:
            var = new DerivedVariable(initExpr, local);
            break;
          case NEVER:
            var = new TemporaryVariable(initExpr, local);
            break;
          case STORE:
            var = new FieldSavedVariable(initExpr, local);
            break;
          default:
            throw new AssertionError();
        }
        currentFrame.put(key, var);
        allVariables.add(var);
        return var;
      }
    };
  }

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


Question: TODO: Implement point mode

function NetbiosPointMode(opts) {
  var self = (this instanceof NetbiosPointMode)
           ? this
           : Object.create(null);

  if (typeof opts.transactionIdFunc !== 'function') {
    throw new Error('NetbiosPointMode() requires a transaction ID creation ' +
                    'function');
  } else if (!opts.localMap) {
    throw new Error('NetbiosPointMode() requires a local name map');
  } else if (!opts.remoteMap) {
    throw new Error('NetbiosPointMode() requires a remote name map');
  }

  self._transactionIdFunc = opts.transactionIdFunc;
  self._localMap = opts.localMap;
  self._remoteMap = opts.remoteMap;

  self._localMap.on('timeout', self._sendRefresh.bind(self));

  return self;
}

public WriteRequest add(Series series, DataPoint datapoint) {
    WritableDataPoint mdp = new WritableDataPoint(series, datapoint.getTimestamp(), datapoint.getValue());
    data.add(mdp);
    return this;
  }

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


Question:
// InterpretCreateError converts a generic error on a create
// operation into the appropriate API error.

func InterpretCreateError(err error, qualifiedResource unversioned.GroupResource, name string) error {
	switch {
	case storage.IsNodeExist(err):
		return errors.NewAlreadyExists(qualifiedResource, name)
	case storage.IsUnreachable(err):
		return errors.NewServerTimeout(qualifiedResource, "create", 2) // TODO: make configurable or handled at a higher level
	default:
		return err
	}
}

public function run() {
    $values = $this->formValues;

    try {
      $creative = $this->service->creatives->get($values['account_id'],
          $values['buyer_creative_id'], $values['ad_group_id']);
      print '
Found creative
';
      $this->printResult($creative);
    } catch (Google_Exception $ex) {
      if ($ex->getCode() == 404 || $ex->getCode() == 403) {
        print '
Creative not found or can\'t access creative
';
      } else {
        throw $ex;
      }
    }
  }

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


Question: Lazily retrieve and build User instances from returned data

def _evaluate(self):
        """"""
        if self._elements:
            for element in self._elements:
                yield element
        else:
            for user_id in self.__user_ids:
                element = self._swimlane.users.get(id=user_id)
                self._elements.append(element)
                yield element

private function generateValues($default, $items)
    {
        foreach ($items as $key => $item) {
            /** @type $item CacheItemInterface */
            if (!$item->isHit()) {
                yield $key => $default;
            } else {
                yield $key => $item->get();
            }
        }
    }

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


Question: F743-506, F743-14447 RTC109678

private Date parseXSDDateTime(String fieldName, String dateTime) {
        try {
            return new Date(DateHelper.parse(dateTime));
        } catch (IllegalArgumentException ex) {
            FFDCFilter.processException(ex, CLASS_NAME + ".parseXSDDateTime", "566", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "failed to parse schedule date/time", ex);
            throw new ScheduleExpressionParserException(ScheduleExpressionParserException.Error.VALUE, fieldName, dateTime); // d660135
        }
    }

def generateRaDec(self):

        self.prefix = self.PAR_PREFIX

        if not isinstance(self.wcs,pywcs.WCS):
            print(
                textutil.textbox(
                    'WCS not a valid PyWCS object. '
                    'Conversion of RA/Dec not possible...'
                    ),
                file=sys.stderr
            )
            raise ValueError

        if self.xypos is None or len(self.xypos[0]) == 0:
            self.xypos = None
            warnstr = textutil.textbox(
                'WARNING: \n'
                'No objects found for this image...'
            )

            for line in warnstr.split('\n'):
                log.warning(line)

            print(warnstr)
            return

        if self.radec is None:
            print('     Found {:d} objects.'.format(len(self.xypos[0])))
            if self.wcs is not None:
                ra, dec = self.wcs.all_pix2world(self.xypos[0], self.xypos[1], self.origin)
                self.radec = [ra, dec] + copy.deepcopy(self.xypos[2:])
            else:
                # If we have no WCS, simply pass along the XY input positions
                # under the assumption they were already sky positions.
                self.radec = copy.deepcopy(self.xypos)

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


Question:
Updates the current device status.
        :param deviceName: the device name.
        :param state: the state.
        :param reason: the reason for the change.
        :return:

def updateDeviceStatus(self, deviceName, state, reason=None):

        logger.info('Updating recording device state for ' + deviceName + ' to ' + state.name +
                    ('' if reason is None else '[reason: ' + reason + ']'))
        currentState = self.recordingDevices.get(deviceName)
        count = 0
        if currentState is not None:
            if currentState['state'] == MeasurementStatus.RECORDING.name:
                count = currentState['count']
        self.recordingDevices[deviceName] = {
            'state': state.name,
            'reason': reason,
            'time': datetime.datetime.utcnow().strftime(DATETIME_FORMAT),
            'count': count
        }

func (d *SerialDevice) merge(dev SerialDevice) bool {
	changed := false
	if d.Port != dev.Port {
		changed = true
		d.Port = dev.Port
	}
	if d.SerialNumber != dev.SerialNumber {
		changed = true
		d.SerialNumber = dev.SerialNumber
	}
	if d.ProductID != dev.ProductID {
		changed = true
		d.ProductID = dev.ProductID
	}
	if d.VendorID != dev.VendorID {
		changed = true
		d.VendorID = dev.VendorID
	}

	// if d.Serial != dev.Serial {
	// 	d.Serial = dev.Serial
	// }
	return changed
}

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


Question:
Remove an item.

@param string $cacheId

@return bool

public function removeItem($cacheId)
    {
        $path = $this->keyPath($cacheId);

        if (!FileUtils::exists($path)) {
            return true;
        }

        return unlink($path);
    }

public function _GetCacheParameters()
    {
        $aParameters = parent::_GetCacheParameters();

        $oShop = TdbShop::GetInstance();
        $oActiveCategory = $oShop->GetActiveCategory();
        $oActiveItem = $oShop->GetActiveItem();

        if (!is_null($oActiveCategory)) {
            $aParameters['activecategoryid'] = $oActiveCategory->id;
        }
        if (!is_null($oActiveItem)) {
            $aParameters['activeitemid'] = $oActiveItem->id;
        }

        return $aParameters;
    }

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


Question:
Returns a closure with schema
@param schema Map schema
@param options Options
@returns {Function}
@private

function _buildMap(schema, options) {
    options = options || {};
    return function(data) {
        return _map(data, schema, options);
    };
}

func (s *NotificationConfiguration) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "NotificationConfiguration"}
	if s.LambdaFunctionConfigurations != nil {
		for i, v := range s.LambdaFunctionConfigurations {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LambdaFunctionConfigurations", i), err.(request.ErrInvalidParams))
			}
		}
	}
	if s.QueueConfigurations != nil {
		for i, v := range s.QueueConfigurations {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueueConfigurations", i), err.(request.ErrInvalidParams))
			}
		}
	}
	if s.TopicConfigurations != nil {
		for i, v := range s.TopicConfigurations {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TopicConfigurations", i), err.(request.ErrInvalidParams))
			}
		}
	}

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

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