Question:
Creates the SQL for this query. Returns the SQL string and list of
        parameters.

        If 'with_limits' is False, any limit/offset information is not included
        in the query.

def as_sql(self, with_limits=True, with_col_aliases=False, subquery=False):  # pylint:disable=arguments-differ
        # the argument `subquery` is only for old Django 1.10
        # pylint:disable=too-many-locals,too-many-branches,too-many-statements

        # After executing the query, we must get rid of any joins the query
        # setup created. So, take note of alias counts before the query ran.
        # However we do not want to get rid of stuff done in pre_sql_setup(),
        # as the pre_sql_setup will modify query state in a way that forbids
        # another run of it.
        if with_limits and self.query.low_mark == self.query.high_mark:
            return '', ()
        self.subquery = subquery
        refcounts_before = self.query.alias_refcount.copy()
        soql_trans = self.query_topology()
        try:
            extra_select, order_by, group_by = self.pre_sql_setup()
            if with_limits and self.query.low_mark == self.query.high_mark:
                return '', ()
            distinct_fields = self.get_distinct()

            # This must come after 'select', 'ordering', and 'distinct' -- see
            # docstring of get_from_clause() for details.
            from_, f_params = self.get_from_clause()

            where, w_params = self.compile(self.where) if self.where is not None else ("", [])
            having, h_params = self.compile(self.having) if self.having is not None else ("", [])
            params = []
            result = ['SELECT']

            if self.query.distinct:
                result.append(self.connection.ops.distinct_sql(distinct_fields))

            out_cols = []
            col_idx = 1
            for _, (s_sql, s_params), alias in self.select + extra_select:
                if alias:
                    # fixed by removing 'AS'
                    s_sql = '%s %s' % (s_sql, self.connection.ops.quote_name(alias))
                elif with_col_aliases and not isinstance(with_col_aliases, salesforce.backend.base.DatabaseWrapper):
                    s_sql = '%s AS %s' % (s_sql, 'Col%d' % col_idx)
                    col_idx += 1
                if soql_trans and re.match(r'^\w+\.\w+$', s_sql):
                    tab_name, col_name = s_sql.split('.')
                    s_sql = '%s.%s' % (soql_trans[tab_name], col_name)
                params.extend(s_params)
                out_cols.append(s_sql)

            result.append(', '.join(out_cols))

            result.append('FROM')
            result.extend(from_)
            params.extend(f_params)

            if where:
                result.append('WHERE %s' % where)
                params.extend(w_params)

            grouping = []
            for g_sql, g_params in group_by:
                grouping.append(g_sql)
                params.extend(g_params)
            if grouping:
                if distinct_fields:
                    raise NotSupportedError(
                        "annotate() + distinct(fields) is not implemented.")
                if not order_by:
                    order_by = self.connection.ops.force_no_ordering()
                result.append('GROUP BY %s' % ', '.join(grouping))

            if having:
                result.append('HAVING %s' % having)
                params.extend(h_params)

            if order_by:
                ordering = []
                for _, (o_sql, o_params, _) in order_by:
                    ordering.append(o_sql)
                    params.extend(o_params)
                result.append('ORDER BY %s' % ', '.join(ordering))

            if with_limits:
                if self.query.high_mark is not None:
                    result.append('LIMIT %d' % (self.query.high_mark - self.query.low_mark))
                if self.query.low_mark:
                    if self.query.high_mark is None:
                        val = self.connection.ops.no_limit_value()
                        if val:
                            result.append('LIMIT %d' % val)
                    result.append('OFFSET %d' % self.query.low_mark)

            if self.query.select_for_update and self.connection.features.has_select_for_update:
                if self.connection.get_autocommit():
                    raise TransactionManagementError(
                        "select_for_update cannot be used outside of a transaction."
                    )

                # If we've been asked for a NOWAIT query but the backend does
                # not support it, raise a DatabaseError otherwise we could get
                # an unexpected deadlock.
                nowait = self.query.select_for_update_nowait
                if nowait and not self.connection.features.has_select_for_update_nowait:
                    raise DatabaseError('NOWAIT is not supported on this database backend.')
                result.append(self.connection.ops.for_update_sql(nowait=nowait))

            return ' '.join(result), tuple(params)
        finally:
            # Finally do cleanup - get rid of the joins we created above.
            self.query.reset_refcounts(refcounts_before)

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

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


Question: // Retrieve The metric tracking object for this network component.

func (r Network_Component) GetMetricTrackingObject() (resp datatypes.Metric_Tracking_Object, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Component", "getMetricTrackingObject", nil, &r.Options, &resp)
	return
}

public static hanode_routemonitor_binding[] get(nitro_service service, Long id) throws Exception{
		hanode_routemonitor_binding obj = new hanode_routemonitor_binding();
		obj.set_id(id);
		hanode_routemonitor_binding response[] = (hanode_routemonitor_binding[]) obj.get_resources(service);
		return response;
	}

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


Question:
Finalize response for delivery to client

Apply final preparations to the resposne object
so that it is suitable for delivery to the client.

@param  \Slim\Interfaces\Http\RequestInterface $request
@return \Slim\Interfaces\Http\Response Self
@api

public function finalize(\Slim\Interfaces\Http\RequestInterface $request)
    {
        $sendBody = true;

        if (in_array($this->status, array(204, 304)) === true) {
            $this->headers->remove('Content-Type');
            $this->headers->remove('Content-Length');
            $sendBody = false;
        } else {
            $size = @$this->getSize();
            if ($size) {
                $this->headers->set('Content-Length', $size);
            }
        }

        // Serialize cookies into HTTP header
        $this->cookies->setHeaders($this->headers);

        // Remove body if HEAD request
        if ($request->isHead() === true) {
            $sendBody = false;
        }

        // Truncate body if it should not be sent with response
        if ($sendBody === false) {
            $this->body->close();
            $this->body = new \Guzzle\Stream\Stream(fopen('php://temp', 'r+'));
        }

        return $this;
    }

def _cleanup(self) -> None:
        """"""
        if self._cleanup_handle:
            self._cleanup_handle.cancel()

        now = self._loop.time()
        timeout = self._keepalive_timeout

        if self._conns:
            connections = {}
            deadline = now - timeout
            for key, conns in self._conns.items():
                alive = []
                for proto, use_time in conns:
                    if proto.is_connected():
                        if use_time - deadline < 0:
                            transport = proto.transport
                            proto.close()
                            if (key.is_ssl and
                                    not self._cleanup_closed_disabled):
                                self._cleanup_closed_transports.append(
                                    transport)
                        else:
                            alive.append((proto, use_time))

                if alive:
                    connections[key] = alive

            self._conns = connections

        if self._conns:
            self._cleanup_handle = helpers.weakref_handle(
                self, '_cleanup', timeout, self._loop)

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


Question:
Defines a model as readable

@param string $id

public function addReadableModel($id) {

        common_Logger::i('ADDING MODEL '.$id);

        $readables = $this->getOption(self::OPTION_READABLE_MODELS);
        $this->setOption(self::OPTION_READABLE_MODELS, array_unique(array_merge($readables, array($id))));

        // update in persistence
        ModelManager::setModel($this);
    }

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

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


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

@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case AfplibPackage.IID__CON_DATA1:
				setConData1((byte[])newValue);
				return;
			case AfplibPackage.IID__XBASE:
				setXBase((Integer)newValue);
				return;
			case AfplibPackage.IID__YBASE:
				setYBase((Integer)newValue);
				return;
			case AfplibPackage.IID__XUNITS:
				setXUnits((Integer)newValue);
				return;
			case AfplibPackage.IID__YUNITS:
				setYUnits((Integer)newValue);
				return;
			case AfplibPackage.IID__XSIZE:
				setXSize((Integer)newValue);
				return;
			case AfplibPackage.IID__YSIZE:
				setYSize((Integer)newValue);
				return;
			case AfplibPackage.IID__CON_DATA2:
				setConData2((byte[])newValue);
				return;
			case AfplibPackage.IID__XC_SIZE_D:
				setXCSizeD((Integer)newValue);
				return;
			case AfplibPackage.IID__YC_SIZE_D:
				setYCSizeD((Integer)newValue);
				return;
			case AfplibPackage.IID__CON_DATA3:
				setConData3((byte[])newValue);
				return;
			case AfplibPackage.IID__COLOR:
				setColor((Integer)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
// HandleAdmissionFailure gracefully handles admission rejection, and, in some cases,
// to allow admission of the pod despite its previous failure.

func (c *CriticalPodAdmissionHandler) HandleAdmissionFailure(admitPod *v1.Pod, failureReasons []predicates.PredicateFailureReason) (bool, []predicates.PredicateFailureReason, error) {
	if !kubetypes.IsCriticalPod(admitPod) {
		return false, failureReasons, nil
	}
	// InsufficientResourceError is not a reason to reject a critical pod.
	// Instead of rejecting, we free up resources to admit it, if no other reasons for rejection exist.
	nonResourceReasons := []predicates.PredicateFailureReason{}
	resourceReasons := []*admissionRequirement{}
	for _, reason := range failureReasons {
		if r, ok := reason.(*predicates.InsufficientResourceError); ok {
			resourceReasons = append(resourceReasons, &admissionRequirement{
				resourceName: r.ResourceName,
				quantity:     r.GetInsufficientAmount(),
			})
		} else {
			nonResourceReasons = append(nonResourceReasons, reason)
		}
	}
	if len(nonResourceReasons) > 0 {
		// Return only reasons that are not resource related, since critical pods cannot fail admission for resource reasons.
		return false, nonResourceReasons, nil
	}
	err := c.evictPodsToFreeRequests(admitPod, admissionRequirementList(resourceReasons))
	// if no error is returned, preemption succeeded and the pod is safe to admit.
	return err == nil, nil, err
}

def on_data(self, raw_data):

        try:
            data = json.loads(raw_data)
        except ValueError:
            logger.error('value error: %s' % raw_data)
            return

        unique_id = data.get('id')

        if self._error_handler(data, unique_id):
            return False

        operation = data['op']
        if operation == 'connection':
            self._on_connection(data, unique_id)
        elif operation == 'status':
            self._on_status(data, unique_id)
        elif operation in ['mcm', 'ocm']:
            # historic data does not contain unique_id
            if self.stream_unique_id not in [unique_id, 'HISTORICAL']:
                logger.warning('Unwanted data received from uniqueId: %s, expecting: %s' %
                               (unique_id, self.stream_unique_id))
                return
            self._on_change_message(data, unique_id)

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


Question: Recursively renders this view.

public function recursiveRender()
    {
        $field_input = $this->template->cloneRegion('InputField');
        $field_no_label = $this->template->cloneRegion('InputNoLabel');
        $labeled_group = $this->template->cloneRegion('LabeledGroup');
        $no_label_group = $this->template->cloneRegion('NoLabelGroup');

        $this->template->del('Content');

        foreach ($this->elements as $el) {

            // Buttons go under Button section
            if ($el instanceof \atk4\ui\Button) {
                $this->template->appendHTML('Buttons', $el->getHTML());
                continue;
            }

            if ($el instanceof \atk4\ui\FormLayout\Generic) {
                if ($el->label && !$el->inline) {
                    $template = $labeled_group;
                    $template->set('label', $el->label);
                } else {
                    $template = $no_label_group;
                }

                if ($el->width) {
                    $template->set('width', $el->width);
                }

                if ($el->inline) {
                    $template->set('class', 'inline');
                }
                $template->setHTML('Content', $el->getHTML());

                $this->template->appendHTML('Content', $template->render());
                continue;
            }

            // Anything but fields or explicitly defined fields gets inserted directly
            if (!$el instanceof \atk4\ui\FormField\Generic || !$el->layoutWrap) {
                $this->template->appendHTML('Content', $el->getHTML());
                continue;
            }

            $template = $field_input;
            $label = $el->caption ?: $el->field->getCaption();

            // Anything but fields gets inserted directly
            if ($el instanceof \atk4\ui\FormField\CheckBox) {
                $template = $field_no_label;
                $el->template->set('Content', $label);
                /*
                $el->addClass('field');
                $this->template->appendHTML('Fields', '
'.$el->getHTML().'
');
                continue;
                 */
            }

            if ($this->label && $this->inline) {
                $el->placeholder = $label;
                $label = $this->label;
                $this->label = null;
            } elseif ($this->label || $this->inline) {
                $template = $field_no_label;
                $el->placeholder = $label;
            }

            // Fields get extra pampering
            $template->setHTML('Input', $el->getHTML());
            $template->trySet('label', $label);
            $template->trySet('label_for', $el->id.'_input');
            $template->set('field_class', $el->getFieldClass());

            if ($el->field->required) {
                $template->append('field_class', 'required ');
            }

            if (isset($el->width)) {
                $template->append('field_class', $el->width.' wide ');
            }

            if ($el->hint && $template->hasTag('Hint')) {
                $hint = new \atk4\ui\Label([null, 'pointing', 'id'=>$el->id.'_hint']);
                if (is_object($el->hint) || is_array($el->hint)) {
                    $hint->add($el->hint);
                } else {
                    $hint->set($el->hint);
                }
                $template->setHTML('Hint', $hint->getHTML());
            } elseif ($template->hasTag('Hint')) {
                $template->del('Hint');
            }

            $this->template->appendHTML('Content', $template->render());
        }

        // Now collect JS from everywhere
        foreach ($this->elements as $el) {
            if ($el->_js_actions) {
                $this->_js_actions = array_merge_recursive($this->_js_actions, $el->_js_actions);
            }
        }
    }

def from_raw(self, robj: RawObject) -> RootNode:

        cooked = self.schema.from_raw(robj)
        return RootNode(cooked, self.schema, cooked.timestamp)

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


Question:
This function searches for classes that are not namespaced at all.

@example ZendException

@return bool Returns true if the class is found, otherwise false.

protected function searchForNonNamespacedClass()
    {
        $filename = $this->_classFilename;

        foreach($this->_includePaths as $includePath)
        {
            $filePath = $includePath . DIRECTORY_SEPARATOR . $filename;

            if(file_exists($filePath) == true)
            {
                require($filename);

                return true;
            }
        }

        return false;
    }

private function parseNamespace($loc): string
    {
        $tokens = $this->getTokenStream();
        $ns     = '';

        if (\in_array($this->tokens->type($loc), [T_FUNCTION, T_CONST])) {
            $ns .= $this->tokens->value($loc) . ' ';
            $loc = $tokens->next($loc);
        }

        while (\in_array($tokens->type($loc), [T_NS_SEPARATOR, T_STRING])) {
            $ns .= $tokens->value($loc);
            $loc = $tokens->next($loc);
        }

        return $ns;
    }

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


Question: Use this API to fetch all the vpnsessionpolicy resources that are configured on netscaler.

public static vpnsessionpolicy[] get(nitro_service service) throws Exception{
		vpnsessionpolicy obj = new vpnsessionpolicy();
		vpnsessionpolicy[] response = (vpnsessionpolicy[])obj.get_resources(service);
		return response;
	}

def get_config_from_env(cls):

        core_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'core-site.xml')
        core_configs = cls.read_core_config(core_path)

        hdfs_path = os.path.join(os.environ['HADOOP_HOME'], 'conf', 'hdfs-site.xml')
        hdfs_configs = cls.read_hdfs_config(hdfs_path)

        if (not core_configs) and (not hdfs_configs):
            raise Exception("No config found in %s nor in %s" % (core_path, hdfs_path))

        configs = {
            'use_trash': hdfs_configs.get('use_trash', core_configs.get('use_trash', False)),
            'use_sasl': core_configs.get('use_sasl', False),
            'hdfs_namenode_principal': hdfs_configs.get('hdfs_namenode_principal', None),
            'namenodes': hdfs_configs.get('namenodes', []) or core_configs.get('namenodes', [])
        }

        return configs

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


Question: Marshall the given parameter object.

public void marshall(UntagResourceRequest untagResourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(untagResourceRequest.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(untagResourceRequest.getTagKeys(), TAGKEYS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question: convert a yaml file to a data structure

def parse_yaml_from_file(path):
    '''  '''

    try:
        data = file(path).read()
        return parse_yaml(data)
    except IOError:
        raise errors.AnsibleError("file not found: %s" % path)
    except yaml.YAMLError, exc:
        if hasattr(exc, 'problem_mark'):
            mark = exc.problem_mark
            if mark.line -1 >= 0:
                before_probline = data.split("\n")[mark.line-1]
            else:
                before_probline = ''
            probline = data.split("\n")[mark.line]
            arrow = " " * mark.column + "^"
            msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s

%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
        else:
            # No problem markers means we have to throw a generic
            # "stuff messed up" type message. Sry bud.
            msg = "Could not parse YAML. Check over %s again." % path
        raise errors.AnsibleYAMLValidationFailed(msg)

public static DeploymentEntry create(Map<String, Object> config) {
		return new DeploymentEntry(ConfigUtil.normalizeYaml(config));
	}

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


Question: Return an async iterable for all the items at a specified endpoint.

async def getiter(self, url: str, url_vars: Dict[str, str] = {},
                      *, accept: str = sansio.accept_format(),
                      jwt: Opt[str] = None,
                      oauth_token: Opt[str] = None
                      ) -> AsyncGenerator[Any, None]:
        """"""
        data, more = await self._make_request("GET", url, url_vars, b"", accept,
                                              jwt=jwt, oauth_token=oauth_token)

        if isinstance(data, dict) and "items" in data:
            data = data["items"]

        for item in data:
            yield item
        if more:
            # `yield from` is not supported in coroutines.
            async for item in self.getiter(more, url_vars, accept=accept,
                                           jwt=jwt, oauth_token=oauth_token):
                yield item

protected <T extends RaftRequest, U extends RaftResponse> void sendRequest(T request, BiFunction<MemberId, T, CompletableFuture<U>> sender, int count, CompletableFuture<U> future) {
    MemberId node = next();
    if (node != null) {
      log.trace("Sending {} to {}", request, node);
      int selectionId = this.selectionId;
      sender.apply(node, request).whenCompleteAsync((r, e) -> {
        if (e != null || r != null) {
          handleResponse(request, sender, count, selectionId, node, r, e, future);
        } else {
          future.complete(null);
        }
      }, context);
    } else {
      future.completeExceptionally(new ConnectException("Failed to connect to the cluster"));
    }
  }

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


Question: A method used to generated a Swagger property for a model

function generatePropertyDefinition(name, path, definitionName) {
    var property = {};
    var type = path.options.type ? swagger20TypeFor(path.options.type) : 'string'; // virtuals don't have type

    if (skipProperty(name, path, controller)) {
      return;
    }
    // Configure the property
    if (path.options.type === mongoose.Schema.Types.ObjectId) {
      if ("_id" === name) {
        property.type = 'string';
      }
      else if (path.options.ref) {
        property.$ref = '#/definitions/' + utils.capitalize(path.options.ref);
      }
    }
    else if (path.schema) {
      //Choice (1. embed schema here or 2. reference and publish as a root definition)
      property.type = 'array';
      property.items = {
        //2. reference
        $ref: '#/definitions/'+ definitionName + utils.capitalize(name)
      };
    }
    else {
      property.type = type;
	  if ('array' === type) {
	    if (isArrayOfRefs(path.options.type)) {
  		  property.items = {
  		    type: 'string'  //handle references as string (serialization for objectId)
  		  };
  		}
      else {
        var resolvedType = referenceForType(path.options.type);
        if (resolvedType.isPrimitive) {
          property.items = {
            type: resolvedType.type
          };
        }
        else {
          property.items = {
            $ref: resolvedType.type
          };
        }
      }
	  }
      var format = swagger20TypeFormatFor(path.options.type);
      if (format) {
        property.format = format;
      }
      if ('__v' === name) {
        property.format = 'int32';
      }
    }

	/*
    // Set enum values if applicable
    if (path.enumValues && path.enumValues.length > 0) {
      // Pending:  property.allowableValues = { valueType: 'LIST', values: path.enumValues };
    }
    // Set allowable values range if min or max is present
    if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
      // Pending: property.allowableValues = { valueType: 'RANGE' };
    }
    if (!isNaN(path.options.min)) {
      // Pending: property.allowableValues.min = path.options.min;
    }
    if (!isNaN(path.options.max)) {
      // Pending: property.allowableValues.max = path.options.max;
    }
	*/
    if (!property.type && !property.$ref) {
      warnInvalidType(name, path);
      property.type = 'string';
    }
    return property;
  }

public ProjectModel getByName(String name)
    {
        return getUnique(getQuery().getRawTraversal().has(ProjectModel.NAME, name));
    }

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


Question:
Atomically sets the max value.

If the current value is larger than the provided value, the call is ignored.
So it will not happen that a smaller value will overwrite a larger value.

public static <E> void setMax(E obj, AtomicLongFieldUpdater<E> updater, long value) {
        for (; ; ) {
            long current = updater.get(obj);
            if (current >= value) {
                return;
            }

            if (updater.compareAndSet(obj, current, value)) {
                return;
            }
        }
    }

def split(self, N, force=False):

        mode = self.mode
        assert mode in ("batch", "cycle", "optimal")
        logging.debug("set split mode=%s" % mode)

        self.names = self.__class__.get_names(self.filename, N)
        if self.outputdir:
            self.names = [op.join(self.outputdir, x) for x in self.names]

        if not need_update(self.filename, self.names) and not force:
            logging.error("file %s already existed, skip file splitting" % \
                    self.names[0])
            return

        filehandles = [open(x, "w") for x in self.names]

        if mode == "batch":
            for batch, fw in zip(self._batch_iterator(N), filehandles):
                count = self.write(fw, batch)
                logging.debug("write %d records to %s" % (count, fw.name))

        elif mode == "cycle":
            handle = self._open(self.filename)
            for record, fw in zip(handle, cycle(filehandles)):
                count = self.write(fw, [record])

        elif mode == "optimal":
            """
            This mode is based on Longest Processing Time (LPT) algorithm:

            A simple, often-used algorithm is the LPT algorithm (Longest
            Processing Time) which sorts the jobs by its processing time and
            then assigns them to the machine with the earliest end time so far.
            This algorithm achieves an upper bound of 4/3 - 1/(3m) OPT.

            Citation: <http://en.wikipedia.org/wiki/Multiprocessor_scheduling>
            """
            endtime = [0] * N
            handle = self._open(self.filename)
            for record in handle:
                mt, mi = min((x, i) for (i, x) in enumerate(endtime))
                fw = filehandles[mi]
                count = self.write(fw, [record])
                endtime[mi] += len(record)

        for fw in filehandles:
            fw.close()

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


Question:
Process the TwoFactor OTP backup.

@param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorTotpBackupRequest $request

@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse

public function backupTotp(AccountTwoFactorTotpBackupRequest $request)
    {
        $currentUser = $request->user($this->getGuard());
        $twoFactor = $currentUser->getTwoFactor();
        $twoFactor['totp']['backup'] = $this->generateTotpBackups();
        $twoFactor['totp']['backup_at'] = now()->toDateTimeString();

        $currentUser->fill(['two_factor' => $twoFactor])->forceSave();

        return intend([
            'back' => true,
            'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.rebackup')],
        ]);
    }

protected function getAuthorizationParameters(array $options)
    {
        $options = parent::getAuthorizationParameters($options);
        $options['purpose'] = $this->purpose;
        return $options;
    }

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


Question:
Encrypt password.

@param text the text
@return the string

public static Password createPassword(char[] password) {
		byte[] salt = JKSecurityUtil.salt();
		byte[] hash = JKSecurityUtil.hash(password, salt);

		Password pass = new Password();
		pass.setHash(encodeInToBase64(hash));
		pass.setSalt(encodeInToBase64(salt));
		return pass;
	}

protected void setEmailBox() {

        m_sendEmail.setEnabled(
            !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword1())
                | !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword2()));
    }

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


Question:
Parse the content of a PLIST file from country-files.com return the
        parsed values in dictionaries.
        Country-files.com provides Prefixes and Exceptions

def _parse_country_file(self, cty_file, country_mapping_filename=None):

        import plistlib

        cty_list = None
        entities = {}
        exceptions = {}
        prefixes = {}

        exceptions_index = {}
        prefixes_index = {}

        exceptions_counter = 0
        prefixes_counter = 0

        mapping = None

        with open(country_mapping_filename, "r") as f:
            mapping = json.loads(f.read(),encoding='UTF-8')

        cty_list = plistlib.readPlist(cty_file)

        for item in cty_list:
            entry = {}
            call = str(item)
            entry[const.COUNTRY] = unicode(cty_list[item]["Country"])
            if mapping:
                 entry[const.ADIF] = int(mapping[cty_list[item]["Country"]])
            entry[const.CQZ] = int(cty_list[item]["CQZone"])
            entry[const.ITUZ] = int(cty_list[item]["ITUZone"])
            entry[const.CONTINENT] = unicode(cty_list[item]["Continent"])
            entry[const.LATITUDE] = float(cty_list[item]["Latitude"])
            entry[const.LONGITUDE] = float(cty_list[item]["Longitude"])*(-1)

            if cty_list[item]["ExactCallsign"]:
                if call in exceptions_index.keys():
                    exceptions_index[call].append(exceptions_counter)
                else:
                    exceptions_index[call] = [exceptions_counter]
                exceptions[exceptions_counter] = entry
                exceptions_counter += 1
            else:
                if call in prefixes_index.keys():
                    prefixes_index[call].append(prefixes_counter)
                else:
                    prefixes_index[call] = [prefixes_counter]
                prefixes[prefixes_counter] = entry
                prefixes_counter += 1

        self._logger.debug(str(len(prefixes))+" Prefixes added")
        self._logger.debug(str(len(prefixes_index))+" Prefixes in Index")
        self._logger.debug(str(len(exceptions))+" Exceptions added")
        self._logger.debug(str(len(exceptions_index))+" Exceptions in Index")

        result = {
            "prefixes" : prefixes,
            "exceptions" : exceptions,
            "prefixes_index" : prefixes_index,
            "exceptions_index" : exceptions_index,
        }

        return result

def handle_import(self, name, compilation, rule):

        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)

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


Question:
Terminates the ObjectManager.

@throws ObjectManagerException

public final void shutdown()
                    throws ObjectManagerException
    {
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass
                        , "shutdown"
                            );

        objectManagerState.shutdown();

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this, cclass
                       , "shutdown"
                            );
    }

public ClassDoc exception() {
        ClassDocImpl exceptionClass;
        if (!(holder instanceof ExecutableMemberDoc)) {
            exceptionClass = null;
        } else {
            ExecutableMemberDocImpl emd = (ExecutableMemberDocImpl)holder;
            ClassDocImpl con = (ClassDocImpl)emd.containingClass();
            exceptionClass = (ClassDocImpl)con.findClass(exceptionName);
        }
        return exceptionClass;
    }

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


Question:
Set this {@link AxisAngle4d} to be equivalent to the given
{@link Quaterniondc}.

@param q
the quaternion to set this AngleAxis4d from
@return this

public AxisAngle4d set(Quaterniondc q) {
        double acos = safeAcos(q.w());
        double invSqrt = 1.0 / Math.sqrt(1.0 - q.w() * q.w());
        this.x = q.x() * invSqrt;
        this.y = q.y() * invSqrt;
        this.z = q.z() * invSqrt;
        this.angle = acos + acos;
        return this;
    }

public QueryControllerQuery addQuery(String queryStr, String queryId, String groupId) {
		int position = getElementPosition(queryId);

		QueryControllerQuery query = new QueryControllerQuery(queryId);
		query.setQuery(queryStr);
		QueryControllerGroup group = getGroup(groupId);
		if (group == null) {
		    group = new QueryControllerGroup(groupId);
            entities.add(group);
            fireElementAdded(group);
		}
		if (position == -1) {
			group.addQuery(query);
			fireElementAdded(query, group);
		} else {
			group.updateQuery(query);
			fireElementChanged(query, group);
		}
		return query;
	}

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


Question: Execute code in the kernel without increasing the prompt

def silent_execute(self, code):
        """"""
        try:
            self.kernel_client.execute(to_text_string(code), silent=True)
        except AttributeError:
            pass

func RecordAndReplay(cmd []string, wd string, quiet bool, debugInfoDirs []string) (p *Process, tracedir string, err error) {
	tracedir, err = Record(cmd, wd, quiet)
	if tracedir == "" {
		return nil, "", err
	}
	p, err = Replay(tracedir, quiet, debugInfoDirs)
	return p, tracedir, err
}

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


Question:
Create adapter from an existing doctrine/dbal connection.

@param \Doctrine\DBAL\Connection $dbalConnection

@return \Soluble\DbWrapper\Adapter\Doctrine\Dbal2Adapter

public static function createAdapterFromDoctrine2(\Doctrine\DBAL\Connection $dbalConnection)
    {
        return new \Soluble\DbWrapper\Adapter\Doctrine\Dbal2Adapter($dbalConnection);
    }

public void marshall(DynamoDBAction dynamoDBAction, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(dynamoDBAction.getTableName(), TABLENAME_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRoleArn(), ROLEARN_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getOperation(), OPERATION_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyField(), HASHKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyValue(), HASHKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getHashKeyType(), HASHKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyField(), RANGEKEYFIELD_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyValue(), RANGEKEYVALUE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getRangeKeyType(), RANGEKEYTYPE_BINDING);
            protocolMarshaller.marshall(dynamoDBAction.getPayloadField(), PAYLOADFIELD_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:
/*[deutsch]
<p>Erzeugt ein unbegrenztes offenes Intervall bis zum angegebenen
Endzeitpunkt. </p>

@param   end     timestamp of upper boundary (exclusive)
@return  new timestamp interval
@since   2.0

public static TimestampInterval until(PlainTimestamp end) {

        Boundary<PlainTimestamp> past = Boundary.infinitePast();
        return new TimestampInterval(past, Boundary.of(OPEN, end));

    }

function Source(id, version, label, description,
    format, caps, tags, device_id, parents) {

  // Globally unique identifier for the Source
  this.id = this.generateID(id);
  // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating
  // precisely when an attribute of the resource last changed
  this.version = this.generateVersion(version);
  // Freeform string label for the Source
  this.label = this.generateLabel(label);
  // Detailed description of the Source
  this.description = this.generateDescription(description);
  // Format of the data coming from the Source as a URN
  this.format = this.generateFormat(format);
  // Capabilities (not yet defined)
  this.caps = this.generateCaps(caps);
  // Key value set of freeform string tags to aid in filtering Sources. Values
  // should be represented as an array of strings. Can be empty.
  this.tags = this.generateTags(tags);
  // Globally unique identifier for the Device which initially created the Source
  this.device_id = this.generateDeviceID(device_id);
  // Array of UUIDs representing the Source IDs of Grains which came together at
  // the input to this Source (may change over the lifetime of this Source)
  this.parents = this.generateParents(parents);
  return immutable(this, { prototype: Source.prototype });
}

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


Question: Compute (alt, az, distance) relative to the observer's horizon.

def _to_altaz(position_au, observer_data, temperature_C, pressure_mbar):

    elevation_m = observer_data.elevation_m
    R = observer_data.altaz_rotation

    if (elevation_m is None) or (R is None):
        raise ValueError('to compute an altazimuth position, you must'
                         ' observe from a specific Earth location that'
                         ' you specify using a Topos instance')

    # TODO: wobble

    position_au = einsum('ij...,j...->i...', R, position_au)
    r_au, alt, az = to_polar(position_au)

    if temperature_C is None:
        alt = Angle(radians=alt)
    else:
        if temperature_C == 'standard':
            temperature_C = 10.0
        if pressure_mbar == 'standard':
            pressure_mbar = 1010.0 * exp(-elevation_m / 9.1e3)
        alt = refract(alt * RAD2DEG, temperature_C, pressure_mbar)
        alt = Angle(degrees=alt)

    return alt, Angle(radians=az), Distance(r_au)

def D(self, ID, asp):

        obj = self.chart.getObject(ID).copy()
        obj.relocate(obj.lon - asp)
        ID = 'D_%s_%s' % (ID, asp)
        return self.G(ID, obj.lat, obj.lon)

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


Question:
Installs Drupal and imports configuration.

@command internal:drupal:install

@validateDrushConfig
@hidden

@return \Robo\Result
The `drush site-install` command result.
@throws BltException

public function install() {

    // Allows for installs to define custom user 0 name.
    if ($this->getConfigValue('drupal.account.name') !== NULL) {
      $username = $this->getConfigValue('drupal.account.name');
    }
    else {
      // Generate a random, valid username.
      // @see \Drupal\user\Plugin\Validation\Constraint\UserNameConstraintValidator
      $username = RandomString::string(10, FALSE,
        function ($string) {
          return !preg_match('/[^\x{80}-\x{F7} a-z0-9@+_.\'-]/i', $string);
        },
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#%^&*()_?/.,+=><'
      );
    }
    /** @var \Acquia\Blt\Robo\Tasks\DrushTask $task */
    $task = $this->taskDrush()
      ->drush("site-install")
      ->arg($this->getConfigValue('project.profile.name'))
      ->rawArg("install_configure_form.enable_update_status_module=NULL")
      ->option('sites-subdir', $this->getConfigValue('site'))
      ->option('site-name', $this->getConfigValue('project.human_name'))
      ->option('site-mail', $this->getConfigValue('drupal.account.mail'))
      ->option('account-name', $username, '=')
      ->option('account-mail', $this->getConfigValue('drupal.account.mail'))
      ->option('locale', $this->getConfigValue('drupal.locale'))
      ->verbose(TRUE)
      ->printOutput(TRUE);

    // Install site from existing config if supported.
    $strategy = $this->getConfigValue('cm.strategy');
    $cm_core_key = $this->getConfigValue('cm.core.key');
    $install_from_config = $this->getConfigValue('cm.core.install_from_config');
    if (in_array($strategy, ['core-only', 'config-split']) && $cm_core_key == 'sync' && $install_from_config) {
      $core_config_file = $this->getConfigValue('docroot') . '/' . $this->getConfigValue("cm.core.dirs.$cm_core_key.path") . '/core.extension.yml';
      if (file_exists($core_config_file)) {
        $task->option('existing-config');
      }
    }

    $result = $task->interactive($this->input()->isInteractive())->run();
    if (!$result->wasSuccessful()) {
      throw new BltException("Failed to install Drupal!");
    }

    return $result;
  }

func GetAction(boshInitDeploy func(string)) func(c *cli.Context) error {
	return func(c *cli.Context) (e error) {
		var boshBase *boshinit.BoshBase
		if boshBase, e = boshinit.NewBoshBase(c); e != nil {
			lo.G.Error(e.Error())
			return e
		}
		if err := utils.CheckRequired(c, "vsphere-address", "vsphere-user", "vsphere-password", "vsphere-datacenter-name",
			"vsphere-vm-folder", "vsphere-template-folder", "vsphere-datastore", "vsphere-disk-path",
			"vsphere-clusters", "vsphere-subnet1-name", "vsphere-subnet1-range", "vsphere-subnet1-range", "vsphere-subnet1-dns"); err != nil {
			lo.G.Error(err.Error())
			return err
		}
		vSphereClusters := c.StringSlice("vsphere-clusters")
		vSphereResourcePools := c.StringSlice("vsphere-resource-pool")
		vsphereConfig := boshinit.VSphereInitConfig{
			VSphereAddress:        c.String("vsphere-address"),
			VSphereUser:           c.String("vsphere-user"),
			VSpherePassword:       c.String("vsphere-password"),
			VSphereDatacenterName: c.String("vsphere-datacenter-name"),
			VSphereVMFolder:       c.String("vsphere-vm-folder"),
			VSphereTemplateFolder: c.String("vsphere-template-folder"),
			VSphereDataStore:      c.String("vsphere-datastore"),
			VSphereDiskPath:       c.String("vsphere-disk-path"),
			VSphereClusters:       vSphereClusters,
			VSphereNetworks: []boshinit.Network{boshinit.Network{
				Name:    c.String("vsphere-subnet1-name"),
				Range:   c.String("vsphere-subnet1-range"),
				Gateway: c.String("vsphere-subnet1-gateway"),
				DNS:     c.StringSlice("vsphere-subnet1-dns"),
			}},
		}

		if len(vSphereResourcePools) > 0 {
			vsphereConfig.VSphereResourcePool = vSphereResourcePools
		}
		provider := boshinit.NewVSphereIaaSProvider(vsphereConfig, boshBase)

		if err := boshBase.HandleDeployment(provider, boshInitDeploy); err != nil {
			return err
		}

		return nil
	}
}

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


Question:
This normalizes or finds objects (id's) and for the type returns back an
objective-c type of '@' or '#'

function normalizeObjects(types) {
  var ret = types[0].type ? types[0].type : types[0];
  var args = types[1].map(function(item) { return item.type ? item.type : item; });
  return [ret, args];
 }

func updateIdentity(set *apps.StatefulSet, pod *v1.Pod) {
	pod.Name = getPodName(set, getOrdinal(pod))
	pod.Namespace = set.Namespace
	if pod.Labels == nil {
		pod.Labels = make(map[string]string)
	}
	pod.Labels[apps.StatefulSetPodNameLabel] = pod.Name
}

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


Question:
Sets the host the client works with by default. This method accepts any valid {@link URL} formatted string.
This will extract the schema, host and port to use by default.

@throws IllegalArgumentException if the given URL is invalid

public T hostFromUrl(String urlStr) {
        if (StringUtils.isNotBlank(urlStr)) {
            try {
                URL url = new URL(urlStr);
                defaultHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Cannot parse the url " + urlStr, e);
            }
        } else {
            defaultHost = null;
        }
        return self();
    }

public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
            protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
            protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
            protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
            protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
            protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
            protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
            protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
            protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_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:
Creates a new identifier. The identifier can be either a partial (e.g. {@code .foo} or a full
name (e.g. {@code foo} or {@code foo.bar.bar.quux}.

public static Identifier create(String identifier, SourceLocation location) {
    checkArgument(!identifier.isEmpty());
    return new AutoValue_Identifier(identifier, location);
  }

func parseTag(s string) (prefix, tag string, err error) {
	splitString := strings.Split(s, ":")
	if len(splitString) == 1 {
		prefix = splitString[0]
	} else if len(splitString) == 2 {
		prefix, tag = splitString[0], splitString[1]
	} else {
		// Unlikely edge case but it doesn't hurt to test for it.
		return "", "", fmt.Errorf("Path should not contain more than one colon: %q", s)
	}

	if strings.HasSuffix(prefix, "/") {
		return "", "", fmt.Errorf(`Image name must not have a trailing "/": %s`, prefix)
	}

	return prefix, tag, nil
}

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


Question: Return a list of Odoo command line arguments from the Click context.

def get_odoo_args(self, ctx):
        """"""
        config = ctx.params.get("config")
        addons_path = ctx.params.get("addons_path")
        database = ctx.params.get("database")
        log_level = ctx.params.get("log_level")
        logfile = ctx.params.get("logfile")

        odoo_args = []

        if config:
            odoo_args.extend(["--config", config])
        if addons_path:
            odoo_args.extend(["--addons-path", addons_path])
        if database:
            odoo_args.extend(["--database", database])
        if log_level:
            odoo_args.extend(["--log-level", log_level])
        if logfile:
            odoo_args.extend(["--logfile", logfile])

        return odoo_args

def cmd_all(args):
    """"""
    for penlist in penStore.data:
        puts(penlist)
        with indent(4, '  -'):
            for penfile in penStore.data[penlist]:
                puts(penfile)

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


Question:
Validate a LogoutResponse

@param LogoutResponse $response

public function validateLogoutResponse(LogoutResponse $response)
    {
        $this->validateIssuer($response);

        if ($this->hasSignature($response)) {
            $this->validateSignature(
                $response,
                KeyHelper::createPublicKey(
                    $this->getMetadata()->getFirstIdpSsoDescriptor()
                        ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING)
                        ->getCertificate()
                )
            );
        }
    }

public function Quit($close_on_error = true) {
    $this->error = null; // so there is no confusion

    if(!$this->connected()) {
      $this->error = array(
              "error" => "Called Quit() without being connected");
      return false;
    }

    // send the quit command to the server
    fputs($this->smtp_conn,"quit" . $this->CRLF);

    // get any good-bye messages
    $byemsg = $this->get_lines();

    if($this->do_debug >= 2) {
      echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '
';
    }

    $rval = true;
    $e = null;

    $code = substr($byemsg,0,3);
    if($code != 221) {
      // use e as a tmp var cause Close will overwrite $this->error
      $e = array("error" => "SMTP server rejected quit command",
                 "smtp_code" => $code,
                 "smtp_rply" => substr($byemsg,4));
      $rval = false;
      if($this->do_debug >= 1) {
        echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
';
      }
    }

    if(empty($e) || $close_on_error) {
      $this->Close();
    }

    return $rval;
  }

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


Question:
Try to find the transient for the translation set or retrieve them.

@access private

@return object|null

private function find_or_initialize_translation_details() {
		$set = get_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale );

		if ( ! $set ) {
			$set = $this->retrieve_translation_details();
			set_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale, $set, DAY_IN_SECONDS );
		}

		return $set;
	}

protected function handleMissingData(ResourceMetaDataInterface $resource, CollectionInterface $collection)
    {
        $message = sprintf('Could not publish resource %s with SHA1 hash %s of collection %s because there seems to be no corresponding data in the storage.', $resource->getFilename(), $resource->getSha1(), $collection->getName());
        $this->messageCollector->append($message);
    }

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


Question: Return a list of plugin instances and pass through arguments.

def get_plugins(cls, *args, **kwargs):

        return [plugin(*args, **kwargs) for plugin in cls.plugins]

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

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

        $this->removeScope($xml);

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

        $this->parseLoops($xml);

        $this->parseFilters($xml);

        $this->parseTemplateDirectives($xml);

        $this->parseParameters($xml);

        $this->parseCommands($xml);

        $this->parseForms($xml);

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

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

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

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

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

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

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


Question:
Update entry specified by pathInfo and posted entry.

@param entry
@param areq Details of HTTP request
@throws com.rometools.rome.propono.atom.server.AtomException

@Override
    public void putEntry(final AtomRequest areq, final Entry entry) throws AtomException {
        LOG.debug("putEntry");
        final String[] pathInfo = StringUtils.split(areq.getPathInfo(), "/");
        final String handle = pathInfo[0];
        final String collection = pathInfo[1];
        final String fileName = pathInfo[2];
        final FileBasedCollection col = service.findCollectionByHandle(handle, collection);
        try {
            col.updateEntry(entry, fileName);

        } catch (final Exception fe) {
            throw new AtomException(fe);
        }
    }

function(setting, value) {
        if (-1 === this._supportedPostParams.indexOf(setting)) {
            this.console.error('Parameter unsupported, may cause error:', setting);
        }
        this._reqParam[setting] = value;
        return this;
    }

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


Question: // Custom renders a customized statement list. Pass in options to specify multi-line, and tokens for open, close, separator.

func (s *Statement) Custom(options Options, statements ...Code) *Statement {
	g := &Group{
		close:     options.Close,
		items:     statements,
		multi:     options.Multi,
		name:      "custom",
		open:      options.Open,
		separator: options.Separator,
	}
	*s = append(*s, g)
	return s
}

func formatFirewallRulesTabular(writer io.Writer, rules firewallRules) {
	tw := output.TabWriter(writer)
	w := output.Wrapper{tw}

	sort.Sort(rules)

	w.Println("Service", "Whitelist subnets")
	for _, rule := range rules {
		w.Println(rule.KnownService, strings.Join(rule.WhitelistCIDRS, ","))
	}
	tw.Flush()
}

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


Question: GEN-LAST:event_createButtonActionPerformed

private void batchFileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_batchFileButtonActionPerformed
        // Load a batch file
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                        new FileInputStream(file), "UTF8"))) {
                String str;

                sequenceArea.setText("");

                while ((str = in.readLine()) != null) {
                    sequenceArea.setText(sequenceArea.getText() + str + '\n');
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println("Encoding exception");
            } catch (IOException e) {
                System.out.println("Cannot read from file" + fileChooser.getSelectedFile().toString());
            } catch (Exception e) {
                System.out.println("Exception");
            }

        }
    }

private int getComponentState(JComponent c, Region region) {
        if (region == SeaGlassRegion.SEARCH_FIELD_CANCEL_BUTTON && c.isEnabled()) {
            if (((JTextComponent) c).getText().length() == 0) {
                return DISABLED;
            } else if (isCancelArmed) {
                return PRESSED;
            }

            return ENABLED;
        }

        return SeaGlassLookAndFeel.getComponentState(c);
    }

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


Question: Returns original field value or None

def get_original_field_value(self, name):

        name = self.get_real_name(name)

        try:
            value = self.__original_data__[name]
        except KeyError:
            return None

        try:
            return value.export_original_data()
        except AttributeError:
            return value

public function deserialize($data, Category $category, array $options = [])
    {
        $this->sipe('name', 'setName', $data, $category);
        $this->sipe('details', 'setDetails', $data, $category);

        if (isset($data['clacoForm']['id']) && !in_array(Options::REFRESH_UUID, $options)) {
            $clacoForm = $this->clacoFormRepo->findOneBy(['uuid' => $data['clacoForm']['id']]);

            if (!empty($clacoForm)) {
                $category->setClacoForm($clacoForm);
            }
        }

        $category->emptyManagers();
        if (isset($data['managers'])) {
            foreach ($data['managers'] as $managerData) {
                $manager = $this->userRepo->findOneBy(['username' => $managerData['username']]);

                if (!empty($manager)) {
                    $category->addManager($manager);
                }
            }
        }

        if (isset($data['fieldsValues'])) {
            $this->deserializeFieldChoiceCategory($data['fieldsValues'], $category);
        }

        return $category;
    }

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


Question:
// evalTime evals a builtinFromUnixTime1ArgSig.
// See https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_from-unixtime

func (b *builtinFromUnixTime1ArgSig) evalTime(row chunk.Row) (res types.Time, isNull bool, err error) {
	return evalFromUnixTime(b.ctx, b.tp.Decimal, row, b.args[0])
}

public function dateAdd($number = 0, $interval = "d") {
        $hours =  $this->hour;
        $minutes =  $this->minute;
        $seconds =  $this->second;
        $month =  $this->month;
        $day =  $this->day;
        $year =  $this->year;

        switch ($interval) {
            case "yyyy":
                //---Add $number to year
                $year += $number;
                break;

            case "q":
                //---Add $number to quarter
                $month += ($number*3);
                break;

            case "m":
                //---Add $number to month
                $month += $number;
                break;

            case "y":
            case "d":
            case "w":
                //---Add $number to day of year, day, day of week
                $day += $number;
                break;

            case "ww":
                //---Add $number to week
                $day += ($number*7);
                break;

            case "h":
                //---Add $number to hours
                $hours += $number;
                break;

            case "n":
                //---Add $number to minutes
                $minutes += $number;
                break;

            case "s":
                //---Add $number to seconds
                $seconds += $number;
                break;
        }

        return (new Date(mktime($hours,
                                $minutes,
                                $seconds,
                                $month,
                                $day,
                                $year)));

    }

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


Question:
Returns the item values as array.

@return Associative list of item properties and their values

public function toArray()
	{
		$list = parent::toArray();

		$list['locale.languageid'] = $this->getLanguageId();
		$list['locale.currencyid'] = $this->getCurrencyId();
		$list['locale.position'] = $this->getPosition();
		$list['locale.status'] = $this->getStatus();

		return $list;
	}

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question:
Applies tree root condition if multi root

@param $condition

protected function applyRootCondition(&$condition)
    {
        if (false !== $this->rootAttribute) {
            $condition[] = [$this->rootAttribute => $this->node->{$this->rootAttribute}];
        }
    }

private static void setUnconditionalArgumentNullness(
      Updates bothUpdates, List<Node> arguments, ClassAndMethod callee) {
    Set<Integer> requiredNonNullParameters = REQUIRED_NON_NULL_PARAMETERS.get(callee.name());
    for (LocalVariableNode var : variablesAtIndexes(requiredNonNullParameters, arguments)) {
      bothUpdates.set(var, NONNULL);
    }
  }

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


Question:
Convert attribute value to MultiValue.

@param string $value
@return MultiValue

private static function convertMultiValue($value)
    {
        $protoMultiValue = new \Attrpubapi\MultiValue();
        $protoMultiValue->mergeFromString($value);
        $items = [];
        foreach ($protoMultiValue->getValues() as $protoValue) {
            $items[] = self::convertValueBasedOnContentType(
                $protoValue->getData(),
                $protoValue->getContentType()
            );
        }
        return new MultiValue($items);
    }

func (cm AsStandard) MValidationLookup(resource string) *metadata.MValidationLookup {
	mvl := metadata.MValidationLookup{}
	mi := metadata.MIValidationLookup
	for _, cd := range cm.Elements[mi.Name] {
		if cd.Attr["Resource"] != resource {
			continue
		}
		metadata.FieldTransfer(cd.Attr).To(&mvl)
		for _, entry := range cd.Entries() {
			tmp := metadata.ValidationLookup{}
			entry.SetFields(&tmp)
			id := mi.ID(&tmp)
			tmp.MValidationLookupType = cm.MValidationLookupType(resource, id)
			mvl.ValidationLookup = append(mvl.ValidationLookup, tmp)
		}
	}
	return &mvl
}

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


Question:
// Validate checks the field values on DatadogConfig with the rules defined in
// the proto definition for this message. If any rules are violated, an error
// is returned.

func (m *DatadogConfig) Validate() error {
	if m == nil {
		return nil
	}

	if len(m.GetCollectorCluster()) < 1 {
		return DatadogConfigValidationError{
			field:  "CollectorCluster",
			reason: "value length must be at least 1 bytes",
		}
	}

	if len(m.GetServiceName()) < 1 {
		return DatadogConfigValidationError{
			field:  "ServiceName",
			reason: "value length must be at least 1 bytes",
		}
	}

	return nil
}

public void marshall(DescribeRuleRequest describeRuleRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeRuleRequest.getName(), NAME_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:
Applies the given {@code procedure} to each non-zero element of the specified column of this matrix.

@param j the column index.
@param procedure the {@link VectorProcedure}.

public void eachNonZeroInColumn(int j, VectorProcedure procedure) {
        VectorIterator it = nonZeroIteratorOfColumn(j);

        while (it.hasNext()) {
            double x = it.next();
            int i = it.index();
            procedure.apply(i, x);
        }
    }

public static double[][] computeMinMax(Relation<? extends NumberVector> relation) {
    int dim = RelationUtil.dimensionality(relation);
    double[] mins = new double[dim], maxs = new double[dim];
    for(int i = 0; i < dim; i++) {
      mins[i] = Double.MAX_VALUE;
      maxs[i] = -Double.MAX_VALUE;
    }
    for(DBIDIter iditer = relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
      final NumberVector o = relation.get(iditer);
      for(int d = 0; d < dim; d++) {
        final double v = o.doubleValue(d);
        mins[d] = (v < mins[d]) ? v : mins[d];
        maxs[d] = (v > maxs[d]) ? v : maxs[d];
      }
    }
    return new double[][] { mins, maxs };
  }

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


Question: Extract the actual Type to be used for a containing annotation.

private Type extractContainingType(Attribute.Compound ca,
                                       DiagnosticPosition pos,
                                       TypeSymbol annoDecl)
    {
        // The next three checks check that the Repeatable annotation
        // on the declaration of the annotation type that is repeating is
        // valid.

        // Repeatable must have at least one element
        if (ca.values.isEmpty()) {
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }
        Pair<MethodSymbol,Attribute> p = ca.values.head;
        Name name = p.fst.name;
        if (name != names.value) { // should contain only one element, named "value"
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }
        if (!(p.snd instanceof Attribute.Class)) { // check that the value of "value" is an Attribute.Class
            log.error(pos, "invalid.repeatable.annotation", annoDecl);
            return null;
        }

        return ((Attribute.Class)p.snd).getValue();
    }

@Override
  public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) {
    return checkInvocation(
        tree, ((JCMemberReference) tree).referentType, state, ASTHelpers.getSymbol(tree));
  }

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


Question: Make sure all items of config are in schema

def check_extraneous(config, schema):
    """"""
    if not isinstance(config, dict):
        raise ValueError("Config {} is not a dictionary".format(config))
    for k in config:
        if k not in schema:
            raise ValueError("Unexpected config key `{}` not in {}".format(
                k, list(schema.keys())))
        v, kreq = schema[k]
        if v is None:
            continue
        elif isinstance(v, type):
            if not isinstance(config[k], v):
                if v is str and isinstance(config[k], string_types):
                    continue
                raise ValueError(
                    "Config key `{}` has wrong type {}, expected {}".format(
                        k,
                        type(config[k]).__name__, v.__name__))
        else:
            check_extraneous(config[k], v)

protected function checkSchemes(\SwaggerValidator\Common\Context $context)
    {
        if (!isset($this->schemes)) {
            return true;
        }

        foreach ($this->schemes as $oneScheme) {
            if (strtolower($context->getDataValue()) && strtolower($oneScheme)) {
                return true;
            }
        }

        return $context->setValidationError(\SwaggerValidator\Common\Context::VALIDATION_TYPE_DATAVALUE, 'Scheme requested is not allowed', __METHOD__, __LINE__);
    }

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


Question:
// Patch gets a specific commit patch based on the url of the service
//
// https://developer.github.com/v3/repos/commits/#get-a-single-commit

func (c *CommitsService) Patch(uri *Hyperlink, params M) (patch io.ReadCloser, result *Result) {
	if uri == nil {
		uri = &CommitsURL
	}
	url, err := uri.Expand(params)
	if err != nil {
		return nil, &Result{Err: err}
	}
	patch, result = c.client.getBody(url, patchMediaType)

	return
}

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

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

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

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

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/reports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/reports".format(**path), data=data, params=params, all_pages=True)

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


Question: Marshall the given parameter object.

public void marshall(DescribeTapesRequest describeTapesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeTapesRequest.getGatewayARN(), GATEWAYARN_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getTapeARNs(), TAPEARNS_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getMarker(), MARKER_BINDING);
            protocolMarshaller.marshall(describeTapesRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Dispatches failure to all of the callbacks registered with this list. This may only be called
once.

@throws IllegalStateException if this callback has already fired.

@Override
  public void onFailure(Throwable cause) {
    checkState();
    for (Callback<T> cb : callbacks) {
      cb.onFailure(cause);
    }
    callbacks = null; // note that we've fired
  }

func tryDialPipe(ctx context.Context, path *string) (syscall.Handle, error) {
	for {
		select {
		case <-ctx.Done():
			return syscall.Handle(0), ctx.Err()
		default:
			h, err := createFile(*path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
			if err == nil {
				return h, nil
			}
			if err != cERROR_PIPE_BUSY {
				return h, &os.PathError{Err: err, Op: "open", Path: *path}
			}
			// Wait 10 msec and try again. This is a rather simplistic
			// view, as we always try each 10 milliseconds.
			time.Sleep(time.Millisecond * 10)
		}
	}
}

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


Question:
<p>
Escapes the specified target text as required for Java code.
</p>

@param target the text to be escaped
@return the escaped text.
@since 2.0.11

public static String escapeJava(final Object target) {
        if (target == null) {
            return null;
        }
        return JavaEscape.escapeJava(target.toString());
    }

public static String replaceAllSpecialChracters(String toBeReplaced) {
	toBeReplaced = toBeReplaced.replaceAll("&", "&");
	toBeReplaced = toBeReplaced.replaceAll("<", "<");
	toBeReplaced = toBeReplaced.replaceAll(">", ">");
	toBeReplaced = toBeReplaced.replaceAll("\"", """);
	toBeReplaced = toBeReplaced.replaceAll("'", "'");
	// toBeReplaced = toBeReplaced.replace("^", "&circ");
	// toBeReplaced = toBeReplaced.replaceAll("0xb", "");
	int len = toBeReplaced.length();
	char[] temp = toBeReplaced.toCharArray();
	for (int i = 0; i < len; i++) {
	    char xCode = temp[i];
	    if ((xCode > '\u0000' && xCode <= '\u0020') || (xCode == '\u0026')
		    || (xCode == '\u0022') || (xCode == '\u02C6')
		    || (xCode == '\u201C') || (xCode == '\u201D')
		    || (xCode == '\u201E')) {
		String sub1 = toBeReplaced.substring(0, i);
		String sub2 = toBeReplaced.substring(i + 1, len);

		String replacement = "";
		if ((xCode > '\u0000' && xCode <= '\u0020'))
		    replacement = " ";
		if (xCode == '\u0026')
		    replacement = " ";
		if (xCode == '\u0022')
		    replacement = " ";
		if (xCode == '\u02C6')
		    replacement = " ";
		if (xCode == '\u201C')
		    replacement = " ";
		if (xCode == '\u201D')
		    replacement = " ";
		if (xCode == '\u201E')
		    replacement = " ";

		toBeReplaced = sub1 + replacement + sub2;
	    }
	    len = toBeReplaced.length();
	    temp = toBeReplaced.toCharArray();
	}

	return (toBeReplaced);
    }

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


Question:
@param Request $request

@return Response

public function changeFieldTypeAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw $this->createAccessDeniedException();
        }

        $type = $request->get('type');
        $fieldType = $this->fieldManager->getFieldTypeByCode($type);

        $formName = $request->get('formPath');

        $formPath = $this->getFormPath($formName);
        // Extract first item to create named builder
        $rootPath = array_shift($formPath);
        $formChildren = $formPath;
        $rootFormBuilder = $this->formFactory->createNamedBuilder($rootPath, FormType::class, null, ['translation_domain' => 'AdvancedContentBundle']);
        // Create formBuilder recursively, according to formName
        $formBuilder = $this->createEmbeddedForm($formPath, $rootFormBuilder);
        $formBuilder->add('options', FormType::class);

        $fieldType->addFieldOptions($formBuilder);

        $form = $rootFormBuilder->getForm();
        foreach ($formChildren as $child) {
            $form = $form->get($child);
        }
        $formView = $form->createView();

        $response = [
            'success' => 1,
            'optionHtml'    => $this->renderView('@SherlockodeAdvancedContent/ContentType/field_options_render.html.twig', [
                'options' => $formView['options'],
            ]),
            'layoutHtml'    => $this->renderView('@SherlockodeAdvancedContent/ContentType/field_layout.html.twig', [
                'form' => $formView,
            ])
        ];

        return new JsonResponse($response);
    }

protected function GetResponseURL($sResponse)
    {
        $sReturnURLBase = $this->getActivePageService()->getActivePage()->GetRealURLPlain(array(), true);
        if ('.html' === substr($sReturnURLBase, -5)) {
            $sReturnURLBase = substr($sReturnURLBase, 0, -5);
        }
        if ('/' !== substr($sReturnURLBase, -1)) {
            $sReturnURLBase .= '/';
        }
        // remove http:// and https:// since these are set in the interface
        $sReturnURLBase = str_replace('https://', '', $sReturnURLBase);
        $sReturnURLBase = str_replace('http://', '', $sReturnURLBase);

        return $sReturnURLBase.self::URL_IDENTIFIER.$sResponse;
    }

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


Question:
Subscribe to a particular signal
 @param signal_name Symbol
 @param step Symbol May be :first_pass or :second_pass
 @param block Proc

def subscribe_signal(signal_name, step=:first_pass, &block)
      key = SecureRandom.hex(5)
      @subscriptions ||= Hash.new()
      @subscriptions[signal_name] ||= Hash.new
      @subscriptions[signal_name][key] = block
      key
    end

public function process(array $data, array $config)
	{
		// Intersect the data given the with the data keys provided.
		$specifiedData = array_intersect_key($data, array_flip(array_keys($config)));

		// Unset password if null, otherwise hash it for saving.
		if(array_key_exists('password', $specifiedData))
		{
			// Unset password rules if null.
			if(is_null($specifiedData['password']))
			{
				unset($rules['password']);
			}
		}

		// Validate and set our errors if they exist.
		$this->errorPayload = $this->validator->validate($specifiedData, $config);

		// Return sanitized data if no validation errors exist.
		if($this->errorPayload->getStatus() == Payload::STATUS_VALID)
		{
			// Hash password if present.
			if(array_key_exists('password', $specifiedData))
			{
				$specifiedData['password'] = Hash::make($specifiedData['password']);
			}

			return new Payload($specifiedData, Payload::STATUS_VALID);
		}

		return $this->errorPayload;
	}

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


Question:
Generates a URL for Site API Content object or ContentInfo object, from the given parameters.

@param mixed $name
@param mixed $parameters
@param mixed $referenceType

public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string
    {
        if (!$name instanceof Content && !$name instanceof ContentInfo) {
            throw new RouteNotFoundException('Could not match route');
        }

        if (empty($name->mainLocationId)) {
            throw new LogicException('Cannot generate an UrlAlias route for content without main location.');
        }

        return $this->generator->generate(
            $name->mainLocation->innerLocation,
            $parameters,
            $referenceType
        );
    }

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

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


Question: // Retrieve The VLANs that are trunked to this network component.

func (r Network_Component) GetNetworkVlanTrunks() (resp []datatypes.Network_Component_Network_Vlan_Trunk, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Component", "getNetworkVlanTrunks", nil, &r.Options, &resp)
	return
}

def check_hardware_virtualization(self, source_node):

        for project in self._projects.values():
            for node in project.nodes:
                if node == source_node:
                    continue
                if node.hw_virtualization and node.__class__.__name__ != source_node.__class__.__name__:
                    return False
        return True

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


Question:
// ReadFrom implements io.ReaderFrom interface. It deserializes
// the group statistics from the wire format.

func (g *GroupStats) ReadFrom(r io.Reader) (int64, error) {
	var length uint16

	n, err := encoding.ReadFrom(r, &length, &defaultPad2,
		&g.Group, &g.RefCount, &defaultPad4, &g.PacketCount, &g.ByteCount,
		&g.DurationSec, &g.DurationNSec)

	if err != nil {
		return n, err
	}

	limrd := io.LimitReader(r, int64(length-groupStatsLen))
	counterMaker := encoding.ReaderMakerOf(BucketCounter{})

	nn, err := encoding.ReadSliceFrom(limrd, counterMaker, g.BucketStats)
	return n + nn, err
}

func (c *Chat) UnmarshalJSON(data []byte) error {
	s := &struct {
		ID                          int        `json:"id"`
		Type                        string     `json:"type"`
		Title                       string     `json:"title"`
		Username                    string     `json:"username"`
		FirstName                   string     `json:"first_name"`
		LastName                    string     `json:"last_name"`
		Photo                       *ChatPhoto `json:"photo"`
		Description                 string     `json:"description"`
		InviteLink                  string     `json:"invite_link"`
		PinnedMessage               *Message   `json:"pinned_message"`
		StickerSetName              string     `json:"sticker_set_name"`
		AllMembersAreAdministrators bool       `json:"all_members_are_administrators"`
		CanSetStickerSet            bool       `json:"can_set_sticker_set"`
	}{}
	err := json.Unmarshal(data, s)
	if err != nil {
		return err
	}
	*c = Chat{
		ID:                          fmt.Sprint(s.ID),
		Type:                        s.Type,
		Title:                       s.Title,
		Username:                    s.Username,
		FirstName:                   s.FirstName,
		LastName:                    s.LastName,
		Photo:                       s.Photo,
		Description:                 s.Description,
		InviteLink:                  s.InviteLink,
		PinnedMessage:               s.PinnedMessage,
		StickerSetName:              s.StickerSetName,
		AllMembersAreAdministrators: s.AllMembersAreAdministrators,
		CanSetStickerSet:            s.CanSetStickerSet,
	}
	return nil
}

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