Question:
@param $color
@param $count
@param $colorsCount

@return float

protected function getColorScore($color, $count, $colorsCount)
	    {
	        $sRGBComponents = $this->getSRGBComponents($this->getRGBComponents($color));
	        $max 			= max($sRGBComponents);
	        $min 			= min($sRGBComponents);
	        $diff 			= $max - $min;
	        $sum 			= $max + $min;
	        $saturation 	= $diff ? ($sum / 2 > .5 ? $diff / (2 - $diff) : $diff / $sum) : 0;
	        $luminosity 	= ($sum / 2 + .2126 * $sRGBComponents[0] + .7152 * $sRGBComponents[1] + .0722 * $sRGBComponents[2]) / 2;

	        return $saturation < .5 ?
	            (1 - $luminosity) * $count / $colorsCount :
	            $count * ($saturation) * $luminosity;
	    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


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

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

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

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

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


Question:
Step the batch of environments.

    The results of the step can be accessed from the variables defined below.

    Args:
      action: Tensor holding the batch of actions to apply.

    Returns:
      Operation.

def simulate(self, action):

    with tf.name_scope('environment/simulate'):
      if action.dtype in (tf.float16, tf.float32, tf.float64):
        action = tf.check_numerics(action, 'action')
      observ_dtype = self._parse_dtype(self._batch_env.observation_space)
      observ, reward, done = tf.py_func(
          lambda a: self._batch_env.step(a)[:3], [action],
          [observ_dtype, tf.float32, tf.bool], name='step')
      observ = tf.check_numerics(observ, 'observ')
      reward = tf.check_numerics(reward, 'reward')
      return tf.group(
          self._observ.assign(observ),
          self._action.assign(action),
          self._reward.assign(reward),
          self._done.assign(done))

def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []

    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities

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


Question:
Returns the class associated to the class name given in parameter

@param classname
the class name
@return the class

public static Class<?> getClass(String classname) {
		Class<?> clazz = null;
		try {
			clazz = Class.forName(classname);

		} catch (Exception e) {
			// Try the second approach
		}
		if (null == clazz) {
			Exception classNotFoundEx = null;
			try {
				clazz = Class.forName(classname, true, new ClassLoaderResourceUtils().getClass().getClassLoader());
			} catch (Exception e) {
				// Try the third approach
				classNotFoundEx = e;
			}
			if (null == clazz) {
				ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader();
				if (null != threadClassLoader) {
					try {
						clazz = Class.forName(classname, true, threadClassLoader);
					} catch (Exception e) {
						throw new BundlingProcessException(e.getMessage() + " [The custom class " + classname
								+ " could not be instantiated, check wether it is available on the classpath and"
								+ " verify that it has a zero-arg constructor].\n" + " The specific error message is: "
								+ e.getClass().getName() + ":" + e.getMessage(), e);
					}
				} else {
					throw new BundlingProcessException(classNotFoundEx.getMessage() + " [The custom class " + classname
							+ " could not be instantiated, check wether it is available on the classpath and"
							+ " verify that it has a zero-arg constructor].\n" + " The specific error message is: "
							+ classNotFoundEx.getClass().getName() + ":" + classNotFoundEx.getMessage(),
							classNotFoundEx);
				}

			}
		}
		return clazz;
	}

public static Type getReturnType(final String methodDescriptor) {
    // Skip the first character, which is always a '('.
    int currentOffset = 1;
    // Skip the argument types, one at a each loop iteration.
    while (methodDescriptor.charAt(currentOffset) != ')') {
      while (methodDescriptor.charAt(currentOffset) == '[') {
        currentOffset++;
      }
      if (methodDescriptor.charAt(currentOffset++) == 'L') {
        while (methodDescriptor.charAt(currentOffset++) != ';') {
          // Skip the argument descriptor content.
        }
      }
    }
    return getType(methodDescriptor, currentOffset + 1, methodDescriptor.length());
  }

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


Question:
Returns the text value of a child element. Returns
null if there is no child element found.

@param element element
@return text value

static String getElementText(Element element) {
        StringBuffer buf = new StringBuffer();

        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.TEXT_NODE ||
                    node.getNodeType() == Node.CDATA_SECTION_NODE) {
                Text text = (Text) node;
                buf.append(text.getData().trim());
            }
        }

        return buf.toString();
    }

protected function getCellXML($rowIndex, $cellNumber, $cellValue, $styleId)
    {
        $columnIndex = CellHelper::getCellIndexFromColumnIndex($cellNumber);
        $cellXML = '<c r="' . $columnIndex . $rowIndex . '"';
        $cellXML .= ' s="' . $styleId . '"';

        if (CellHelper::isNonEmptyString($cellValue)) {
            $cellXML .= $this->getCellXMLFragmentForNonEmptyString($cellValue);
        } else if (CellHelper::isBoolean($cellValue)) {
            $cellXML .= ' t="b"><v>' . intval($cellValue) . '</v></c>';
        } else if (CellHelper::isNumeric($cellValue)) {
            $cellXML .= '><v>' . $cellValue . '</v></c>';
        } else if (empty($cellValue)) {
            if ($this->styleHelper->shouldApplyStyleOnEmptyCell($styleId)) {
                $cellXML .= '/>';
            } else {
                // don't write empty cells that do no need styling
                // NOTE: not appending to $cellXML is the right behavior!!
                $cellXML = '';
            }
        } else {
            throw new InvalidArgumentException('Trying to add a value with an unsupported type: ' . gettype($cellValue));
        }

        return $cellXML;
    }

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


Question:
check if a given exception matches the class of any in the list

@param $list
@param Exception $exception
@return bool

protected function isInList($list, Exception $exception)
    {
        // check if we actually have a list and its an array
        if ($list && is_array($list)) {
            // if we do lets loop through and check if our exception matches any of the classes
            foreach ($list as $type) {
                if ($exception instanceof $type) {
                    // if we match return true
                    return true;
                }
            }
        }

        // we got to the end there must be no match
        return false;
    }

public function addRoute($route)
    {
        if (!$route instanceof Route && !is_array($route)) {
            throw new \LogicException('Route invalid. Expected Route instance or array.');
        } elseif ($route instanceof Route) {
            $name = $route->getName();
            if (isset($this->routes[$name])) {
                throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name));
            }
            $this->routes[$route->getName()] = $route;
        } elseif (is_array($route) && !count($route) == 4) {
            throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).');
        } else {
            list($methods, $patternUri, $action, $name) = array_values($route);

            $this->routes[$name] = new Route($methods, $patternUri, $action, $name);
        }

        return $this;
    }

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


Question:
Insert data into the storage key specified.

@param array|string $key
@param array        $data

public function insert($storageName, $key, array $data)
    {
        try {
            $this->conn->insert($this->table, [
                $this->keyColumn  => $key,
                $this->dataColumn => serialize($data),
            ]);
        } catch (\Exception $e) {
        }
    }

private void addNameSpaceStorage(int nsID, NameSpaceSliceStorage nsStorage)
      throws IOException {
    if (!this.nsStorageMap.containsKey(nsID)) {
      this.nsStorageMap.put(nsID, nsStorage);
    }
  }

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


Question:
Basic authorisation, transaction type and protocol version.

@return Array

protected function getBaseData()
    {
        $data = array();

        $data['VPSProtocol'] = $this->VPSProtocol;
        $data['TxType'] = $this->getTxType();
        $data['Vendor'] = $this->getVendor();
        $data['AccountType'] = $this->getAccountType() ?: static::ACCOUNT_TYPE_E;

        // TODO: move this to getDerivedLanguage()

        if ($language = $this->getLanguage()) {
            // Although documented as ISO639, the gateway expects
            // the code to be upper case.

            $language = strtoupper($language);

            // If a locale has been passed in instead, then just take the first part.
            // e.g. both "en" and "en-gb" becomes "EN".

            list($language) = preg_split('/[-_]/', $language);

            $data['Language'] = $language;
        }

        return $data;
    }

func (c *Client) ListSinceBlockAsync(blockHash *chainhash.Hash) FutureListSinceBlockResult {
	var hash *string
	if blockHash != nil {
		hash = btcjson.String(blockHash.String())
	}

	cmd := btcjson.NewListSinceBlockCmd(hash, nil, nil)
	return c.sendCmd(cmd)
}

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


Question: //Wire bind an action to an event on target

func Wire(ws *websocket.Conn, target, event, act string) error {
	return errNotImplemented
}

func (uw *UnitWriter) Activate(unit, wantPath string) {
	if uw.err != nil {
		return
	}

	if err := os.Symlink(path.Join("..", unit), wantPath); err != nil && !os.IsExist(err) {
		uw.err = errwrap.Wrap(errors.New("failed to link service want"), err)
	}
}

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


Question:
/*
(non-Javadoc)
@see net.timewalker.ffmq4.listeners.AbstractListener#stop()

@Override
	public void stop()
	{
		if (!started)
			return;

		log.info("Stopping listener ["+getName()+"]");

		// Close the listen socket
		multiplexer.unregisterServerSocketHandler(this);
		multiplexer.stop();
		multiplexer = null;

		// Close remaining clients
		closeRemainingClients();

		started = false;
	}

def schedule(cls, mapreduce_spec):

    task_name = mapreduce_spec.mapreduce_id + "-finalize"
    finalize_task = taskqueue.Task(
        name=task_name,
        url=(mapreduce_spec.params["base_path"] + "/finalizejob_callback/" +
             mapreduce_spec.mapreduce_id),
        params={"mapreduce_id": mapreduce_spec.mapreduce_id},
        headers=util._get_task_headers(mapreduce_spec.mapreduce_id))
    queue_name = util.get_queue_name(None)
    if not _run_task_hook(mapreduce_spec.get_hooks(),
                          "enqueue_controller_task",
                          finalize_task,
                          queue_name):
      try:
        finalize_task.add(queue_name)
      except (taskqueue.TombstonedTaskError,
              taskqueue.TaskAlreadyExistsError), e:
        logging.warning("Task %r already exists. %s: %s",
                        task_name, e.__class__, e)

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


Question:
Update the trafficControl for all the session which has
just been opened.

private void updateTrafficMask() {
        int queueSize = trafficControllingSessions.size();

        while (queueSize > 0) {
            T session = trafficControllingSessions.poll();

            if (session == null) {
                return;
            }

            SessionState state = getState(session);

            switch (state) {
                case OPENED:
                    updateTrafficControl(session);
                    break;

                case CLOSING:
                    break;

                case OPENING:
                    // Retry later if session is not yet fully initialized.
                    // (In case that Session.suspend??() or session.resume??() is
                    // called before addSession() is processed)
                    // We just put back the session at the end of the queue.
                    trafficControllingSessions.add(session);

                    break;

                default:
                    throw new IllegalStateException(String.valueOf(state));
            }

            // As we have handled one session, decrement the number of
            // remaining sessions.
            queueSize--;
        }
    }

public static void createAndRegister() {
    synchronized (monitor) {
      checkState(handler == null, "OC-Agent exporter is already registered.");
      OcAgentTraceExporterHandler newHandler = new OcAgentTraceExporterHandler();
      registerInternal(newHandler);
    }
  }

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


Question:
Retrieve file copy async job
        :param id: Async job identifier
        :param api: Api instance
        :return:

def get_file_copy_job(cls, id, api=None):

        id = Transform.to_async_job(id)

        api = api if api else cls._API
        async_job = api.get(
            url=cls._URL['get_file_copy_job'].format(id=id)
        ).json()
        return AsyncJob(api=api, **async_job)

def download(self, uuid, url, forced_file_name=None,
                 progress_bar=True, chunk_size=256,
                 directory=None, overwrite=False):

        self.last_req_time = None
        url = self.get_full_url(url)
        self.log.debug("download url : " + url)
        # Building request
        request = urllib2.Request(url)
        # request.add_header('Content-Type', 'application/json; charset=UTF-8')
        request.add_header('Accept', 'application/json,*/*;charset=UTF-8')
        # request start
        starttime = datetime.datetime.now()
        # doRequest
        resultq = urllib2.urlopen(request)
        code = resultq.getcode()
        file_name = uuid
        self.log.debug("ret code : '" + str(code) + "'")
        if code == 200:
            content_lenth = resultq.info().getheader('Content-Length')
            if not content_lenth:
                msg = "No content lengh header found !"
                self.log.debug(msg)
                progress_bar = False
            else:
                file_size = int(content_lenth.strip())
            if forced_file_name:
                file_name = forced_file_name
            else:
                content_dispo = resultq.info().getheader('Content-disposition')
                if content_dispo:
                    content_dispo = content_dispo.strip()
                    file_name = extract_file_name(content_dispo)
            if directory:
                if os.path.isdir(directory):
                    file_name = directory + "/" + file_name
            if os.path.isfile(file_name):
                if not overwrite:
                    cpt = 1
                    while 1:
                        if not os.path.isfile(file_name + "." + str(cpt)):
                            file_name += "." + str(cpt)
                            break
                        cpt += 1
                else:
                    self.log.warn("'%s' already exists. It was overwriten.",
                                  file_name)
            stream = None
            pbar = None
            if progress_bar:
                widgets = [FileTransferSpeed(), ' <<<', Bar(), '>>> ',
                           Percentage(), ' ', ETA()]
                pbar = ProgressBar(widgets=widgets, maxval=file_size)
                stream = FileWithCallback(file_name, 'w', pbar.update,
                                          file_size, file_name)
                pbar.start()
            else:
                stream = file(file_name, 'w')
            while 1:
                chunk = resultq.read(chunk_size)
                if not chunk:
                    break
                stream.write(chunk)
            stream.flush()
            stream.close()
            if pbar:
                pbar.finish()
        # request end
        endtime = datetime.datetime.now()
        self.last_req_time = str(endtime - starttime)
        self.log.debug("download url : %(url)s : request time : %(time)s",
                       {"url": url,
                        "time": self.last_req_time})
        return (file_name, self.last_req_time)

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


Question: Output the number of GraphQL queries grouped by their query_hash within the last time.

def _dump_query_timestamps(self, current_time: float):
        """"""
        windows = [10, 11, 15, 20, 30, 60]
        print("GraphQL requests:", file=sys.stderr)
        for query_hash, times in self._graphql_query_timestamps.items():
            print("  {}".format(query_hash), file=sys.stderr)
            for window in windows:
                reqs_in_sliding_window = sum(t > current_time - window * 60 for t in times)
                print("    last {} minutes: {} requests".format(window, reqs_in_sliding_window), file=sys.stderr)

func (t *partitionedTable) locatePartition(ctx sessionctx.Context, pi *model.PartitionInfo, r []types.Datum) (int64, error) {
	var err error
	var idx int
	switch t.meta.Partition.Type {
	case model.PartitionTypeRange:
		idx, err = t.locateRangePartition(ctx, pi, r)
	case model.PartitionTypeHash:
		idx, err = t.locateHashPartition(ctx, pi, r)
	}
	if err != nil {
		return 0, errors.Trace(err)
	}
	return pi.Definitions[idx].ID, nil
}

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


Question:
汉字转拼音函数

@param string $s
@param bool $quanpin
@param bool $daxie
@return string

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
Returns a pretrained model for the given dataset, if available.

@param pretrainedType
@return
@throws IOException

public <M extends Model> M initPretrained(PretrainedType pretrainedType) throws IOException {
        String remoteUrl = pretrainedUrl(pretrainedType);
        if (remoteUrl == null)
            throw new UnsupportedOperationException(
                            "Pretrained " + pretrainedType + " weights are not available for this model.");

        String localFilename = new File(remoteUrl).getName();

        File rootCacheDir = DL4JResources.getDirectory(ResourceType.ZOO_MODEL, modelName());
        File cachedFile = new File(rootCacheDir, localFilename);

        if (!cachedFile.exists()) {
            log.info("Downloading model to " + cachedFile.toString());
            FileUtils.copyURLToFile(new URL(remoteUrl), cachedFile);
        } else {
            log.info("Using cached model at " + cachedFile.toString());
        }

        long expectedChecksum = pretrainedChecksum(pretrainedType);
        if (expectedChecksum != 0L) {
            log.info("Verifying download...");
            Checksum adler = new Adler32();
            FileUtils.checksum(cachedFile, adler);
            long localChecksum = adler.getValue();
            log.info("Checksum local is " + localChecksum + ", expecting " + expectedChecksum);

            if (expectedChecksum != localChecksum) {
                log.error("Checksums do not match. Cleaning up files and failing...");
                cachedFile.delete();
                throw new IllegalStateException(
                                "Pretrained model file failed checksum. If this error persists, please open an issue at https://github.com/deeplearning4j/deeplearning4j.");
            }
        }

        if (modelType() == MultiLayerNetwork.class) {
            return (M) ModelSerializer.restoreMultiLayerNetwork(cachedFile);
        } else if (modelType() == ComputationGraph.class) {
            return (M) ModelSerializer.restoreComputationGraph(cachedFile);
        } else {
            throw new UnsupportedOperationException(
                            "Pretrained models are only supported for MultiLayerNetwork and ComputationGraph.");
        }
    }

func (s *CreateBatchPredictionInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "CreateBatchPredictionInput"}
	if s.BatchPredictionDataSourceId == nil {
		invalidParams.Add(request.NewErrParamRequired("BatchPredictionDataSourceId"))
	}
	if s.BatchPredictionDataSourceId != nil && len(*s.BatchPredictionDataSourceId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("BatchPredictionDataSourceId", 1))
	}
	if s.BatchPredictionId == nil {
		invalidParams.Add(request.NewErrParamRequired("BatchPredictionId"))
	}
	if s.BatchPredictionId != nil && len(*s.BatchPredictionId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("BatchPredictionId", 1))
	}
	if s.MLModelId == nil {
		invalidParams.Add(request.NewErrParamRequired("MLModelId"))
	}
	if s.MLModelId != nil && len(*s.MLModelId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("MLModelId", 1))
	}
	if s.OutputUri == nil {
		invalidParams.Add(request.NewErrParamRequired("OutputUri"))
	}

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

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


Question:
Get the map of metadata of the project.

@param connection the db connection.
@return the map of metadata.
@throws SQLException

public static LinkedHashMap<String, String> getProjectMetadata( IHMConnection connection ) throws Exception {
        LinkedHashMap<String, String> metadataMap = new LinkedHashMap<>();
        try (IHMStatement statement = connection.createStatement()) {
            statement.setQueryTimeout(30); // set timeout to 30 sec.

            String sql = "select " + MetadataTableFields.COLUMN_KEY.getFieldName() + ", " + //
                    MetadataTableFields.COLUMN_VALUE.getFieldName() + " from " + TABLE_METADATA;
            IHMResultSet rs = statement.executeQuery(sql);
            while( rs.next() ) {
                String key = rs.getString(MetadataTableFields.COLUMN_KEY.getFieldName());
                String value = rs.getString(MetadataTableFields.COLUMN_VALUE.getFieldName());
                if (!key.endsWith("ts")) {
                    metadataMap.put(key, value);
                } else {
                    try {
                        long ts = Long.parseLong(value);
                        String dateTimeString = ETimeUtilities.INSTANCE.TIME_FORMATTER_LOCAL.format(new Date(ts));
                        metadataMap.put(key, dateTimeString);
                    } catch (Exception e) {
                        metadataMap.put(key, value);
                    }
                }
            }

        }
        return metadataMap;
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $session = $this->mustBeModelManagerSession($this->getSession());

        $relations = $session->getInspector()
            ->getSchemaRelations($this->fetchSchemaOid()
        );

        $output->writeln(
            sprintf(
                "Scanning schema '<fg=green>%s</fg=green>'.",
                $this->schema
            )
        );

        if ($relations->isEmpty()) {
            $output->writeln("<bg=yellow>No relations found.</bg=yellow>");
        } else {
            foreach ($relations as $relation_info) {
                $command = $this->getApplication()->find('pomm:generate:relation-all');
                $arguments = [
                    'command'          => 'pomm:generate:relation-all',
                    'config-name'      => $this->config_name,
                    'relation'         => $relation_info['name'],
                    'schema'           => $this->schema,
                    '--force'          => $input->getOption('force'),
                    '--bootstrap-file' => $input->getOption('bootstrap-file'),
                    '--prefix-dir'     => $input->getOption('prefix-dir'),
                    '--prefix-ns'      => $input->getOption('prefix-ns'),
                    '--flexible-container' => $input->getOption('flexible-container'),
                    '--psr4'           => $input->getOption('psr4')
                ];
                $command->run(new ArrayInput($arguments), $output);
            }
        }
    }

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


Question:
Getter for headers property.

@return array

public function getHeaders()
    {
        $defaultHeaders = config('api.defaultHeaders');

        return $defaultHeaders
            ? array_merge($defaultHeaders, $this->headers)
            : $this->headers;
    }

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question: // output (deduped) functions.

func functions(args []string) {
	files, err := ioutil.ReadDir("functions")
	if err != nil {
		return
	}

	for _, file := range files {
		if !utils.ContainsString(args, file.Name()) {
			fmt.Printf("%s ", file.Name())
		}
	}
}

def getInfo(self):

        devinfo = _hidraw_devinfo()
        self._ioctl(_HIDIOCGRAWINFO, devinfo, True)
        return DevInfo(devinfo.bustype, devinfo.vendor, devinfo.product)

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


Question:
Log failed job and delete it from the main queue.

@param JobInterface $job
@param string       $reason

public function logFailedJob(JobInterface $job, $reason)
    {
        if (mb_strlen($reason) > 191) {
            $reason = mb_substr($reason, 0, 191);
        }

        $this->connection->transact(function () use ($job, $reason) {
            $this->connection->execute('INSERT INTO `' . self::FAILED_JOBS_TABLE_NAME . '` (`type`, `channel`, `batch_id`, `data`, `failed_at`, `reason`) VALUES (?, ?, ?, ?, ?, ?)', get_class($job), $job->getChannel(), $job->getBatchId(), json_encode($job->getData()), date('Y-m-d H:i:s'), $reason);
            $this->deleteJob($job);
        });
    }

public Observable<ServiceResponse<InputStream>> downloadQueryLogsWithServiceResponseAsync(UUID appId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.downloadQueryLogs(appId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<InputStream>>>() {
                @Override
                public Observable<ServiceResponse<InputStream>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<InputStream> clientResponse = downloadQueryLogsDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
Do the work of shutting down this engine and its repositories.

@return true if the engine was shutdown (or was not running), and false if the engine is still running and could not be
shutdown

protected boolean doShutdown() {
        if (state == State.NOT_RUNNING) {
            LOGGER.debug("Engine already shut down.");
            return true;
        }
        LOGGER.debug("Shutting down engine...");
        final Lock lock = this.lock.writeLock();
        try {
            lock.lock();
            state = State.STOPPING;

            if (!repositories.isEmpty()) {
                // Now go through all of the repositories and request they all be shutdown ...
                Queue<Future<Boolean>> repoFutures = new LinkedList<Future<Boolean>>();
                Queue<String> repoNames = new LinkedList<String>();
                for (JcrRepository repository : repositories.values()) {
                    if (repository != null) {
                        repoNames.add(repository.getName());
                        repoFutures.add(repository.shutdown());
                    }
                }

                // Now block while each is shutdown ...
                while (repoFutures.peek() != null) {
                    String repoName = repoNames.poll();
                    try {
                        // Get the results from the future (this will return only when the shutdown has completed) ...
                        repoFutures.poll().get();

                        // We've successfully shut down, so remove it from the map ...
                        repositories.remove(repoName);
                    } catch (ExecutionException | InterruptedException e) {
                        Logger.getLogger(getClass()).error(e, JcrI18n.failedToShutdownDeployedRepository, repoName);
                    }
                }
            }

            if (repositories.isEmpty()) {
                // All repositories were properly shutdown, so now stop the service for starting and shutting down the repos ...
                repositoryStarterService.shutdown();
                repositoryStarterService = null;

                // Do not clear the set of repositories, so that restarting will work just fine ...
                this.state = State.NOT_RUNNING;
            } else {
                // Could not shut down all repositories, so keep running ..
                this.state = State.RUNNING;
            }
        } catch (RuntimeException e) {
            this.state = State.RUNNING;
            throw e;
        } finally {
            lock.unlock();
        }
        return this.state != State.RUNNING;
    }

def srun_nodes(self):

        count = self.execution.get('srun_nodes', 0)
        if isinstance(count, six.string_types):
            tag = count
            count = 0
        elif isinstance(count, SEQUENCES):
            return count
        else:
            assert isinstance(count, int)
            tag = self.tag
        nodes = self._srun_nodes(tag, count)
        if 'srun_nodes' in self.execution:
            self.execution['srun_nodes'] = nodes
            self.execution['srun_nodes_count'] = len(nodes)
        return nodes

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


Question:
指定具体命名风格来生成相应命名风格的字符串.

@param str
待转换字符串. 若为null，则返回null.
@param namingStyle
命名风格的枚举. 若namingStyle为null，CAMEL
@return namingStyle命名风格的字符串
@author zhd
@since 1.0.0

public static String to(String str, NamingStyle namingStyle) {
        NamingStyle ns = namingStyle;
        if (str == null) {
            return null;
        }
        if (ns == null) {
            ns = NamingStyle.CAMEL;
        }
        String formatStr;
        switch (ns) {
        case CAMEL:
            formatStr = toLowerCamel(str);
            break;
        case SNAKE:
            formatStr = toSnake(str);
            break;
        case PASCAL:
            formatStr = toPascal(str);
            break;
        case KEBAB:
            formatStr = toKebab(str);
            break;
        default:
            formatStr = toLowerCamel(str);
            break;
        }
        return formatStr;
    }

public static PluginBean unmarshallPlugin(Map<String, Object> source) {
        if (source == null) {
            return null;
        }
        PluginBean bean = new PluginBean();
        bean.setId(asLong(source.get("id")));
        bean.setName(asString(source.get("name")));
        bean.setDescription(asString(source.get("description")));
        bean.setCreatedBy(asString(source.get("createdBy")));
        bean.setCreatedOn(asDate(source.get("createdOn")));
        bean.setGroupId(asString(source.get("groupId")));
        bean.setArtifactId(asString(source.get("artifactId")));
        bean.setVersion(asString(source.get("version")));
        bean.setType(asString(source.get("type")));
        bean.setClassifier(asString(source.get("classifier")));
        bean.setDeleted(asBoolean(source.get("deleted")));
        postMarshall(bean);
        return bean;
    }

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


Question: [Optional] implement MultigetGridDialect:

@Override
	public List<Tuple> getTuples(EntityKey[] keys, TupleContext tupleContext) {
		Objects.requireNonNull( keys );
		if ( keys.length == 0 ) {
			return Collections.emptyList();
		}
		else if ( keys.length == 1 ) {
			return Collections.singletonList( getTuple( keys[0], tupleContext ) );
		}
		else {
			final String cacheName = cacheName( keys[0] );
			final ProtoStreamMappingAdapter mapper = provider.getDataMapperForCache( cacheName );
			final Map<EntityKey,ProtostreamId> keyConversionMatch = new HashMap<>();
			final Set<ProtostreamId> convertedKeys = new HashSet<>();
			for ( EntityKey ek : keys ) {
				if ( ek == null ) {
					continue;
				}
				assert cacheName( ek ).equals( cacheName ) : "The javadoc comment promised batches would be loaded from the same table";
				ProtostreamId idBuffer = mapper.createIdPayload( ek.getColumnNames(), ek.getColumnValues() );
				keyConversionMatch.put( ek, idBuffer );
				convertedKeys.add( idBuffer );
			}
			final Map<ProtostreamId, ProtostreamPayload> loadedBulk = mapper.withinCacheEncodingContext( c -> {
				//TODO getAll doesn't support versioned entries ?!
				return c.getAll( convertedKeys );
			} );

			final List<Tuple> results = new ArrayList<>( keys.length );
			for ( int i = 0; i < keys.length; i++ ) {
				EntityKey originalKey = keys[i];
				if ( originalKey == null ) {
					results.add( null );
					continue;
				}
				ProtostreamId protostreamId = keyConversionMatch.get( originalKey );
				ProtostreamPayload payload = loadedBulk.get( protostreamId );
				if ( payload == null ) {
					results.add( null );
					continue;
				}
				results.add( payload.toTuple( SnapshotType.UNKNOWN ) );
			}
			return results;
		}
	}

def getdict(self, crop=True):

        global mp_D_Y0
        D = mp_D_Y0
        if crop:
            D = cr.bcrop(D, self.dstep.cri.dsz, self.dstep.cri.dimN)
        return D

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


Question:
// GatewayRight checks if the token grants the specified right for
// the Gateway with the specified ID

func (claims *Claims) GatewayRight(gatewayID string, right types.Right) bool {
	return claims.GatewayAccess(gatewayID) && containsRight(claims.Gateways[gatewayID], right)
}

func (this *Runtime) start_announcer() {
	switch {
	case this.zk == nil, this.Namespace == nil:
		glog.Infoln("No zk or no announcement namespace defined.  Not announcing.")
		go func() {
			for {
				if a := <-this.announce; a == stop_announce {
					glog.Infoln("Stopping announcer")
					break
				} else {
					glog.Infoln("Skipping announcement:", a)
				}
			}
		}()
	default:
		go func() {
			for {
				if a := <-this.announce; a == stop_announce {
					glog.Infoln("Stopping announcer")
					break
				} else {
					key := a.Key
					if len(key) == 0 {
						key = fmt.Sprintf("%d", time.Now().Unix())
					}

					path := this.Namespace.Sub(key)
					var err error
					switch a.Value.(type) {
					case []byte:
						err = zk.CreateOrSetBytes(this.zk, path, a.Value.([]byte), a.Ephemeral)
					case string:
						err = zk.CreateOrSetString(this.zk, path, a.Value.(string), a.Ephemeral)
					default:
						if value, err := json.Marshal(a.Value); err == nil {
							err = zk.CreateOrSetBytes(this.zk, path, value, a.Ephemeral)
						}
					}

					if err != nil {
						this.Log("Cannot annouce to", path.Path(), "Err=", err.Error())
					} else {
						this.Log("ANNOUNCE", path.Path())
					}
				}
			}
		}()
	}
}

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


Question:
Get the resource comment by group and key.

@param string $key the resource key to find
@return string the resource comment

public function GetComment($key) {
        $resources = $this->GetList();
        $keyExist = array_key_exists($key, $resources);
        if ($keyExist) {
            return $resources[$key][\Puzzlout\Framework\BO\F_common_resource::F_COMMON_RESOURCE_COMMENT];
        } else {
//      throw new \Puzzlout\Framework\Exceptions\ResourceNotFoundException(
//      "The resource comment doesn't exist for Group => " . $this->GroupValue . " and Key => " . $key, 0, null);
            return "???";
        }
    }

def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end

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


Question:
get sha1 hash from stream

@param resource $stream
@return string str1 hash

protected function getStreamSHA1($stream)
    {
        Util::rewindStream($stream);
        $context = hash_init('sha1');
        hash_update_stream($context, $stream);
        return hash_final($context);
    }

public void marshall(AssociateResourceShareRequest associateResourceShareRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(associateResourceShareRequest.getResourceShareArn(), RESOURCESHAREARN_BINDING);
            protocolMarshaller.marshall(associateResourceShareRequest.getResourceArns(), RESOURCEARNS_BINDING);
            protocolMarshaller.marshall(associateResourceShareRequest.getPrincipals(), PRINCIPALS_BINDING);
            protocolMarshaller.marshall(associateResourceShareRequest.getClientToken(), CLIENTTOKEN_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: // SetParams - to set strategy dynamically

func (swap *Swap) SetParams(local *Params) {
	defer swap.lock.Unlock()
	swap.lock.Lock()
	swap.local = local
	swap.setParams(local)
}

@Override
    public Object getValue(String paramName) throws IllegalArgumentException {
        if (!hasValue(paramName)) {
            throw new IllegalArgumentException("Can't find criteria with name " + paramName);
        }
        if (LIMIT_NAME.equals(paramName)) {
            return limit;
        }
        if (OFFSET_NAME.equals(paramName)) {
            return offset;
        }
        return criterias.get(paramName).getValue();
    }

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


Question:
Returns the clockwise angle between three points.
It starts at p0, that goes clock-wise around c until it reaches p1

@param p0
@param c
@param p1
@return

public static double getClockwiseAngleBetweenThreePoints(final Point2D p0, final Point2D c, final Point2D p1)
    {
        final Point2D a = c.sub(p1);

        final Point2D b = c.sub(p0);

        return Math.atan2(a.getY(), a.getX()) - Math.atan2(b.getY(), b.getX());
    }

protected function processVariable(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();
        $variableName = $tokens[$stackPtr]['content'];
        $scopeIdentifier = $phpcsFile->getFilename() . $variableName;
        $level = $tokens[$stackPtr]['level'];
        $functionIndex = $phpcsFile->findPrevious(T_FUNCTION, $stackPtr);
        $lastScopeOpen = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$scopeOpeners, $stackPtr);

        //Inline scope openers do not increment the level value
        $scopeOpenDistance = $tokens[$stackPtr]['line'] - $tokens[$lastScopeOpen]['line'];
        if (
            in_array($tokens[$lastScopeOpen]['code'], PHP_CodeSniffer_Tokens::$scopeOpeners) === true
            && ($scopeOpenDistance === 1 || $scopeOpenDistance === 0)//Include the variables in the condition
            && $tokens[$stackPtr]['level'] === $tokens[$lastScopeOpen]['level']
        ) {
            ++$level;
        }

        if (
            $functionIndex !== false
            && array_key_exists('scope_closer', $tokens[$functionIndex])
            && $tokens[$functionIndex]['scope_closer'] > $stackPtr
        ) {
            //Member variables are always ok
            if ($variableName === '$this') {
                return;
            }

            // find previous non-whitespace token. if it's a double colon, assume static class var
            $objOperator = $phpcsFile->findPrevious([T_WHITESPACE], ($stackPtr - 1), null, true);
            if ($tokens[$objOperator]['code'] === T_DOUBLE_COLON) {
                return;
            }

            $scopeIdentifier .= $tokens[$functionIndex]['scope_condition'];
        }

        //If this is the first time we've seen this variable in this file/function store the scope depth.
        if (array_key_exists($scopeIdentifier, $this->_variableScopes) === false) {
            $this->_variableScopes[$scopeIdentifier] = $level;
        } elseif ($this->_variableScopes[$scopeIdentifier] > $level) {
            //Verify that the variables we've seen are not appearing in higher scopes.
            $phpcsFile->addWarning("Variable '{$variableName}' is in the wrong scope.", $stackPtr, 'Found');
        }
    }

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


Question:
Create path, including leading components.

            Used by sos.sosreport to set up sos_* directories.

def makedirs(self, path, mode=0o700):

        os.makedirs(os.path.join(self._archive_root, path), mode=mode)
        self.log_debug("created directory at '%s' in FileCacheArchive '%s'"
                       % (path, self._archive_root))

public function setupEnvironment($basePath, $application = 'site')
	{
		if ($application != 'site')
		{
			$basePath .= '/' . $application;
		}

		$server  = array(
			'HTTP_HOST'       => 'undefined',
			'HTTP_USER_AGENT' => 'undefined',
			'REQUEST_METHOD'  => 'GET',
		);
		$_SERVER = array_merge($_SERVER, $server);

		define('JPATH_BASE', $basePath);
		define('DS', DIRECTORY_SEPARATOR);

		require_once JPATH_BASE . '/includes/defines.php';
		require_once JPATH_LIBRARIES . '/loader.php';

		spl_autoload_register('__autoload');

		require_once JPATH_BASE . '/includes/framework.php';

		if ($application == 'administrator')
		{
			require_once JPATH_BASE . '/includes/helper.php';
			require_once JPATH_BASE . '/includes/toolbar.php';

			// JUri uses $_SERVER['HTTP_HOST'] without check
			$_SERVER['HTTP_HOST'] = 'CLI';
		}

		jimport('joomla.installer.installer');
		jimport('joomla.installer.helper');

		$mainframe = \JFactory::getApplication($application);
		$mainframe->initialise();
	}

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


Question:
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/frinfo_c.html

    :param frcode: the idcode for some frame.
    :type frcode: int
    :return: a tuple of attributes associated with the frame.
    :rtype: tuple

def frinfo(frcode):

    frcode = ctypes.c_int(frcode)
    cent = ctypes.c_int()
    frclss = ctypes.c_int()
    clssid = ctypes.c_int()
    found = ctypes.c_int()
    libspice.frinfo_c(frcode, ctypes.byref(cent), ctypes.byref(frclss),
                      ctypes.byref(clssid), ctypes.byref(found))
    return cent.value, frclss.value, clssid.value, bool(found.value)

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_time_since_last_change = ET.SubElement(fcoe_intf_list, "fcoe-intf-time-since-last-change")
        fcoe_intf_time_since_last_change.text = kwargs.pop('fcoe_intf_time_since_last_change')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question:
A method that colorizes strings, not Colr objects.
            Raises InvalidColr for invalid color names.
            The 'reset_all' code is appended if text is given.

def color(
            self, text=None, fore=None, back=None, style=None,
            no_closing=False):

        has_args = (
            (fore is not None) or
            (back is not None) or
            (style is not None)
        )
        if hasattr(text, '__colr__') and not has_args:
            # Use custom __colr__ method in the absence of arguments.
            return str(self._call_dunder_colr(text))

        # Stringify everything before operating on it.
        text = str(text) if text is not None else ''
        if _disabled:
            return text

        # Considered to have unclosed codes if embedded codes exist and
        # the last code was not a color code.
        embedded_codes = get_codes(text)
        has_end_code = embedded_codes and embedded_codes[-1] == closing_code
        # Add closing code if not already added, there is text, and
        # some kind of color/style was used (whether from args, or
        # color codes were included in the text already).
        # If the last code embedded in the text was a closing code,
        # then it is not added.
        # This can be overriden with `no_closing`.
        needs_closing = (
            text and
            (not no_closing) and
            (not has_end_code) and
            (has_args or embedded_codes)
        )
        if needs_closing:
            end = closing_code
        else:
            end = ''
        return ''.join((
            self.color_code(fore=fore, back=back, style=style),
            text,
            end,
        ))

def _clean_text(self, text):

        clean = []
        for char in text:
            if char in self.punc_stops:
                clean += '.'
            elif char not in self.punc:
                clean += char
            else:
                pass
        return (''.join(clean)).lower()

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


Question: // callMetrics logs metrics for every outgoing Mesos call

func callMetrics(metricsAPI *metricsAPI, clock func() time.Time, timingMetrics bool) callrules.Rule {
	timed := metricsAPI.callLatency
	if !timingMetrics {
		timed = nil
	}
	harness := xmetrics.NewHarness(metricsAPI.callCount, metricsAPI.callErrorCount, timed, clock)
	return callrules.Metrics(harness, nil)
}

public function getLogger($name = 'main')
    {
        if (!$this->hasLogger($name)) {
            throw new LoggerNotFoundException(sprintf("Logger instance '%s' not found", $name));
        }

        return $this->channels[$name];
    }

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


Question:
Execute commands

@param string $command
@param array $parameters

@return mixed

public function execute($command, $parameters = array())
    {
        try {
            $cmdSet = $this->client->createCommand($command, $parameters);
            return $this->client->executeCommand($cmdSet);
        }catch(\Exception $e) {
            $this->exception = $e;
            return false;
        }
    }

def parse
      @commands.each do |_, cmd|
        if cmd.flags?
          # or for the || seems to not do what I want it to do...
          next unless argv_index = ARGV.index(cmd.flags.short) || ARGV.index(cmd.flags.long)
        else
          next unless argv_index = ARGV.index(cmd.index.to_s)
        end
        cmd.given = true unless argv_index.nil?
        if cmd.type.nil?
          yield cmd if block_given?
        else
          if parsed = parse_cmd(cmd, flags)
            cmd.arguments = parsed || cmd.default
            yield cmd if block_given?
          elsif cmd.default
            cmd.arguments = cmd.default
            yield cmd if block_given?
          end
        end
      end
    end

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


Question: Await result if coroutine was returned.

def _await_if_required(
        target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
    ) -> typing.Callable[..., typing.Any]:
        """"""

        @functools.wraps(target)
        def wrapper(*args, **kwargs):  # type: (typing.Any, typing.Any) -> typing.Any
            """Decorator/wrapper."""
            result = target(*args, **kwargs)
            if asyncio.iscoroutine(result):
                loop = asyncio.new_event_loop()
                result = loop.run_until_complete(result)
                loop.close()
            return result

        return wrapper

func (flags *WaitFlags) AddFlags(cmd *cobra.Command) {
	flags.PrintFlags.AddFlags(cmd)
	flags.ResourceBuilderFlags.AddFlags(cmd.Flags())

	cmd.Flags().DurationVar(&flags.Timeout, "timeout", flags.Timeout, "The length of time to wait before giving up.  Zero means check once and don't wait, negative means wait for a week.")
	cmd.Flags().StringVar(&flags.ForCondition, "for", flags.ForCondition, "The condition to wait on: [delete|condition=condition-name].")
}

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


Question:
Get the list of classpath components

@param ucl url classloader
@return List of classpath components

private static List getUrlClassLoaderClasspathComponents(URLClassLoader ucl)
    {
        List components = new ArrayList();

        URL[] urls = new URL[0];

        // Workaround for running on JBoss with UnifiedClassLoader3 usage
        // We need to invoke getClasspath() method instead of getURLs()
        if (ucl.getClass().getName().equals("org.jboss.mx.loading.UnifiedClassLoader3"))
        {
            try
            {
                Method classPathMethod = ucl.getClass().getMethod("getClasspath", new Class[] {});
                urls = (URL[]) classPathMethod.invoke(ucl, new Object[0]);
            }
            catch(Exception e)
            {
                LogFactory.getLog(ClasspathUtils.class).debug("Error invoking getClasspath on UnifiedClassLoader3: ", e);
            }
        }
        else
        {
        	// Use regular ClassLoader method to get classpath
            urls = ucl.getURLs();
        }

        for (int i = 0; i < urls.length; i++)
        {
            URL url = urls[i];
            components.add(getCanonicalPath(url.getPath()));
        }

        return components;
    }

def get_routing_tuples(cls):
        ''''''
        for callback in cls.callbacks:
            ep_name = '{}.{}'.format(cls.api.__name__, callback.__name__)
            yield (Rule(cls.endpoint_path,
                        endpoint=ep_name,
                        methods=callback.swagger_ops),
                   callback)

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


Question:
Sets the parameters attribute of the WeightDescriptor object.

@param  params            The new parameters value
@throws CDKException if more than 1 parameter is specified or if the parameter
is not of type String
@see #getParameters

@Override
    public void setParameters(Object[] params) throws CDKException {
        if (params.length > 1) {
            throw new CDKException("weight only expects one parameter");
        }
        if (!(params[0] instanceof String)) {
            throw new CDKException("The parameter must be of type String");
        }
        // ok, all should be fine
        elementName = (String) params[0];
    }

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: Returns whether the given unicode char is allowed in output

def _allowed_char(c):

    c = ord(c)
    if c < 0:
        return False
    if c < 128:
        return _ascii_allowed[c]
    # Genereally allow unicodes, TODO: check for unicode control characters
    # characters
    return True

@Override
    @Deprecated
    public InputStream getUnicodeStream(int columnIndex) throws SQLException {
        checkColumnBounds(columnIndex);
        throw SQLError.noSupport();
    }

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


Question: render the supplied block for the specified function

function namespace (options) {
  options.hash.kind = 'namespace'
  var result = ddata._identifier(options)
  return result ? options.fn(result) : 'ERROR, Cannot find namespace.'
}

def add_route(app_or_blueprint, fn, context=default_context):

    transmute_func = TransmuteFunction(
        fn,
        args_not_from_request=["request"]
    )
    handler = create_handler(transmute_func, context=context)
    get_swagger_spec(app_or_blueprint).add_func(transmute_func, context)
    for p in transmute_func.paths:
        sanic_path = _convert_to_sanic_path(p)
        app_or_blueprint.add_route(handler, sanic_path, methods=list(transmute_func.methods))

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


Question:
@param array        $data
@param Options|null $options

@return Options

public function deserialize(array $data, Options $options = null)
    {
        if (empty($options)) {
            $options = $this->optionsRepo->findOneBy(['id' => $data['id']]);
        }
        if (empty($options)) {
            $options = new Options();
        }
        if (isset($data['user'])) {
            $user = isset($data['user']['id']) ? $this->userRepo->findOneBy(['uuid' => $data['user']['id']]) : null;
            $options->setUser($user);
        }
        if (isset($data['data'])) {
            $options->setOptions($data['data']);
        }

        return $options;
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
Get value for specific key

@param  string $key
@param  mixed $default
@return mixed

public function get($key, $default = null) {

        $stmt = $this->connection->query("SELECT * FROM ".$this->table." WHERE `key`='{$key}';");
        $res  = $stmt->fetch(\PDO::FETCH_ASSOC);

        return  isset($res["key"]) ? json_decode($res["keyval"], true) : $default;
    }

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:
Main entry point that compiles all the specified or found compass
        projects.

def compile(self):

        if self.disabled:
            return
        self._check_configs()
        for _, cfg in self.configs.iteritems():
            cfg.parse()
            if cfg.changes_found() or self.skip_mtime_check:
                self.log.debug("Changes found for " + cfg.path \
                        + " or checks disabled. Compiling...")
                cfg.compile(self)

func All(basedir string, values []byte, namespace string, strict bool) support.Linter {
	// Using abs path to get directory context
	chartDir, _ := filepath.Abs(basedir)

	linter := support.Linter{ChartDir: chartDir}
	rules.Chartfile(&linter)
	rules.Values(&linter)
	rules.Templates(&linter, values, namespace, strict)
	return linter
}

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


Question: // addChild add an child, all Childs is sorted

func (t *Trie) addChild(b byte, n *Trie) {
	chars, childs := t.ChildChars, t.Childs
	l := len(chars)
	chars, childs = make([]byte, l+1), make([]*Trie, l+1)
	copy(chars, t.ChildChars)
	copy(childs, t.Childs)

	for ; l > 0 && chars[l-1] > b; l-- {
		chars[l], childs[l] = chars[l-1], childs[l-1]
	}
	chars[l], childs[l] = b, n
	t.ChildChars, t.Childs = chars, childs
}

func FodderEnsureCleanNewline(fodder *Fodder) {
	if !FodderHasCleanEndline(*fodder) {
		FodderAppend(fodder, MakeFodderElement(FodderLineEnd, 0, 0, []string{}))
	}
}

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


Question:
Decorate each HTTP verb method to check if the request is authenticated

    :param request_handler: a tornado.web.RequestHandler instance

def _wrap_class(request_handler, validator):

    METHODS = ['get', 'post', 'put', 'head', 'options', 'delete', 'patch']
    for name in METHODS:
        method = getattr(request_handler, name)
        setattr(request_handler, name, _auth_required(method, validator))

    return request_handler

def get_urls(self):

        urls = super(AccountAdmin, self).get_urls()
        from django.conf.urls import url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.opts.app_label, self.opts.model_name

        extra_urls = [
            url(r'^login/(?P<provider>(\w|-)+)/$',
                wrap(OAuthRedirect.as_view()), name='%s_%s_login' % info),
            url(r'^callback/(?P<provider>(\w|-)+)/$',
                wrap(OAuthCallback.as_view()), name='%s_%s_callback' % info),
            url(r'^(.+)/json/$', wrap(self.json_view), name='%s_%s_json' % info),
        ]
        return extra_urls + urls

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


Question:
Set digit at position to provided value.  Position should be a value
        of 0 to 3 with 0 being the left most digit on the display.  Digit should
        be a number 0-9, character A-F, space (all LEDs off), or dash (-).

def set_digit(self, pos, digit, decimal=False):

        if self.invert:
            self.set_digit_raw(pos, IDIGIT_VALUES.get(str(digit).upper(), 0x00))
        else:
            self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit).upper(), 0x00))

        if decimal:
            self.set_decimal(pos, True)

def update(self, reseed):

        self._screen.print_at(" ", self._x, self._y)
        cell = None
        for _ in range(self._rate):
            self._y += 1
            cell = self._screen.get_from(self._x, self._y)
            if cell is None or cell[0] != 32:
                break

        if ((cell is not None and cell[0] in [ord(x) for x in self._snow_chars + " "]) and
                (self._y < self._screen.start_line + self._screen.height)):
            self._screen.print_at(self._char,
                                  self._x,
                                  self._y)
        else:
            if self._y > self._screen.start_line + self._screen.height:
                self._y = self._screen.start_line + self._screen.height

            drift_index = -1
            if cell:
                drift_index = self._drift_chars.find(chr(cell[0]))
            if 0 <= drift_index < len(self._drift_chars) - 1:
                drift_char = self._drift_chars[drift_index + 1]
                self._screen.print_at(drift_char, self._x, self._y)
            else:
                self._screen.print_at(",", self._x, self._y - 1)
            if reseed:
                self._reseed()

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


Question: src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:559:1: inlineListExpression : LEFT_SQUARE ( expressionList )? RIGHT_SQUARE ;

public final void inlineListExpression() throws RecognitionException {
		try {
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:5: ( LEFT_SQUARE ( expressionList )? RIGHT_SQUARE )
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:9: LEFT_SQUARE ( expressionList )? RIGHT_SQUARE
			{
			match(input,LEFT_SQUARE,FOLLOW_LEFT_SQUARE_in_inlineListExpression3100); if (state.failed) return;
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:21: ( expressionList )?
			int alt61=2;
			int LA61_0 = input.LA(1);
			if ( (LA61_0==BOOL||(LA61_0 >= DECIMAL && LA61_0 <= DECR)||LA61_0==FLOAT||LA61_0==HEX||(LA61_0 >= ID && LA61_0 <= INCR)||(LA61_0 >= LEFT_PAREN && LA61_0 <= LESS)||LA61_0==MINUS||LA61_0==NEGATION||LA61_0==NULL||LA61_0==PLUS||(LA61_0 >= STAR && LA61_0 <= TIME_INTERVAL)) ) {
				alt61=1;
			}
			switch (alt61) {
				case 1 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:21: expressionList
					{
					pushFollow(FOLLOW_expressionList_in_inlineListExpression3102);
					expressionList();
					state._fsp--;
					if (state.failed) return;
					}
					break;

			}

			match(input,RIGHT_SQUARE,FOLLOW_RIGHT_SQUARE_in_inlineListExpression3105); if (state.failed) return;
			}

		}

		catch (RecognitionException re) {
		    throw re;
		}

		finally {
			// do for sure before leaving
		}
	}

def _match_replace_binary(cls, ops: list) -> list:
    """"""
    n = len(ops)
    if n <= 1:
        return ops
    ops_left = ops[:n // 2]
    ops_right = ops[n // 2:]
    return _match_replace_binary_combine(
        cls,
        _match_replace_binary(cls, ops_left),
        _match_replace_binary(cls, ops_right))

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


Question:
Template method for determining if the Facelet needs to be refreshed.

@param facelet
Facelet that could have expired
@return true if it needs to be refreshed

protected boolean needsToBeRefreshed(DefaultFacelet facelet)
    {
        // if set to 0, constantly reload-- nocache
        if (_refreshPeriod == NO_CACHE_DELAY)
        {
            return true;
        }

        // if set to -1, never reload
        if (_refreshPeriod == INFINITE_DELAY)
        {
            return false;
        }

        long target = facelet.getCreateTime() + _refreshPeriod;
        if (System.currentTimeMillis() > target)
        {
            // Should check for file modification

            URLConnection conn = null;
            try
            {
                conn = facelet.getSource().openConnection();
                long lastModified = ResourceLoaderUtils.getResourceLastModified(conn);

                return lastModified == 0 || lastModified > target;
            }
            catch (IOException e)
            {
                throw new FaceletException("Error Checking Last Modified for " + facelet.getAlias(), e);
            }
            finally
            {
                // finally close input stream when finished, if fails just continue.
                if (conn != null)
                {
                    try
                    {
                        InputStream is = conn.getInputStream();
                        if (is != null)
                        {
                            is.close();
                        }
                    }
                    catch (IOException e)
                    {
                        // Ignore
                    }
                }
            }
        }

        return false;
    }

private void resolveTimeFields() {
        // simplify fields
        if (fieldValues.containsKey(CLOCK_HOUR_OF_DAY)) {
            // lenient allows anything, smart allows 0-24, strict allows 1-24
            long ch = fieldValues.remove(CLOCK_HOUR_OF_DAY);
            if (resolverStyle == ResolverStyle.STRICT || (resolverStyle == ResolverStyle.SMART && ch != 0)) {
                CLOCK_HOUR_OF_DAY.checkValidValue(ch);
            }
            updateCheckConflict(CLOCK_HOUR_OF_DAY, HOUR_OF_DAY, ch == 24 ? 0 : ch);
        }
        if (fieldValues.containsKey(CLOCK_HOUR_OF_AMPM)) {
            // lenient allows anything, smart allows 0-12, strict allows 1-12
            long ch = fieldValues.remove(CLOCK_HOUR_OF_AMPM);
            if (resolverStyle == ResolverStyle.STRICT || (resolverStyle == ResolverStyle.SMART && ch != 0)) {
                CLOCK_HOUR_OF_AMPM.checkValidValue(ch);
            }
            updateCheckConflict(CLOCK_HOUR_OF_AMPM, HOUR_OF_AMPM, ch == 12 ? 0 : ch);
        }
        if (fieldValues.containsKey(AMPM_OF_DAY) && fieldValues.containsKey(HOUR_OF_AMPM)) {
            long ap = fieldValues.remove(AMPM_OF_DAY);
            long hap = fieldValues.remove(HOUR_OF_AMPM);
            if (resolverStyle == ResolverStyle.LENIENT) {
                updateCheckConflict(AMPM_OF_DAY, HOUR_OF_DAY, Math.addExact(Math.multiplyExact(ap, 12), hap));
            } else {  // STRICT or SMART
                AMPM_OF_DAY.checkValidValue(ap);
                HOUR_OF_AMPM.checkValidValue(ap);
                updateCheckConflict(AMPM_OF_DAY, HOUR_OF_DAY, ap * 12 + hap);
            }
        }
        if (fieldValues.containsKey(NANO_OF_DAY)) {
            long nod = fieldValues.remove(NANO_OF_DAY);
            if (resolverStyle != ResolverStyle.LENIENT) {
                NANO_OF_DAY.checkValidValue(nod);
            }
            updateCheckConflict(NANO_OF_DAY, HOUR_OF_DAY, nod / 3600_000_000_000L);
            updateCheckConflict(NANO_OF_DAY, MINUTE_OF_HOUR, (nod / 60_000_000_000L) % 60);
            updateCheckConflict(NANO_OF_DAY, SECOND_OF_MINUTE, (nod / 1_000_000_000L) % 60);
            updateCheckConflict(NANO_OF_DAY, NANO_OF_SECOND, nod % 1_000_000_000L);
        }
        if (fieldValues.containsKey(MICRO_OF_DAY)) {
            long cod = fieldValues.remove(MICRO_OF_DAY);
            if (resolverStyle != ResolverStyle.LENIENT) {
                MICRO_OF_DAY.checkValidValue(cod);
            }
            updateCheckConflict(MICRO_OF_DAY, SECOND_OF_DAY, cod / 1_000_000L);
            updateCheckConflict(MICRO_OF_DAY, MICRO_OF_SECOND, cod % 1_000_000L);
        }
        if (fieldValues.containsKey(MILLI_OF_DAY)) {
            long lod = fieldValues.remove(MILLI_OF_DAY);
            if (resolverStyle != ResolverStyle.LENIENT) {
                MILLI_OF_DAY.checkValidValue(lod);
            }
            updateCheckConflict(MILLI_OF_DAY, SECOND_OF_DAY, lod / 1_000);
            updateCheckConflict(MILLI_OF_DAY, MILLI_OF_SECOND, lod % 1_000);
        }
        if (fieldValues.containsKey(SECOND_OF_DAY)) {
            long sod = fieldValues.remove(SECOND_OF_DAY);
            if (resolverStyle != ResolverStyle.LENIENT) {
                SECOND_OF_DAY.checkValidValue(sod);
            }
            updateCheckConflict(SECOND_OF_DAY, HOUR_OF_DAY, sod / 3600);
            updateCheckConflict(SECOND_OF_DAY, MINUTE_OF_HOUR, (sod / 60) % 60);
            updateCheckConflict(SECOND_OF_DAY, SECOND_OF_MINUTE, sod % 60);
        }
        if (fieldValues.containsKey(MINUTE_OF_DAY)) {
            long mod = fieldValues.remove(MINUTE_OF_DAY);
            if (resolverStyle != ResolverStyle.LENIENT) {
                MINUTE_OF_DAY.checkValidValue(mod);
            }
            updateCheckConflict(MINUTE_OF_DAY, HOUR_OF_DAY, mod / 60);
            updateCheckConflict(MINUTE_OF_DAY, MINUTE_OF_HOUR, mod % 60);
        }

        // combine partial second fields strictly, leaving lenient expansion to later
        if (fieldValues.containsKey(NANO_OF_SECOND)) {
            long nos = fieldValues.get(NANO_OF_SECOND);
            if (resolverStyle != ResolverStyle.LENIENT) {
                NANO_OF_SECOND.checkValidValue(nos);
            }
            if (fieldValues.containsKey(MICRO_OF_SECOND)) {
                long cos = fieldValues.remove(MICRO_OF_SECOND);
                if (resolverStyle != ResolverStyle.LENIENT) {
                    MICRO_OF_SECOND.checkValidValue(cos);
                }
                nos = cos * 1000 + (nos % 1000);
                updateCheckConflict(MICRO_OF_SECOND, NANO_OF_SECOND, nos);
            }
            if (fieldValues.containsKey(MILLI_OF_SECOND)) {
                long los = fieldValues.remove(MILLI_OF_SECOND);
                if (resolverStyle != ResolverStyle.LENIENT) {
                    MILLI_OF_SECOND.checkValidValue(los);
                }
                updateCheckConflict(MILLI_OF_SECOND, NANO_OF_SECOND, los * 1_000_000L + (nos % 1_000_000L));
            }
        }

        // convert to time if all four fields available (optimization)
        if (fieldValues.containsKey(HOUR_OF_DAY) && fieldValues.containsKey(MINUTE_OF_HOUR) &&
                fieldValues.containsKey(SECOND_OF_MINUTE) && fieldValues.containsKey(NANO_OF_SECOND)) {
            long hod = fieldValues.remove(HOUR_OF_DAY);
            long moh = fieldValues.remove(MINUTE_OF_HOUR);
            long som = fieldValues.remove(SECOND_OF_MINUTE);
            long nos = fieldValues.remove(NANO_OF_SECOND);
            resolveTime(hod, moh, som, nos);
        }
    }

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


Question:
recursively create a pattern, prepending parent "representant"(i.e: "show") pattern
this parent pattern is modified to replace {id} with {<name>Id}, and remove {_format} if needed

@return string

public function generate(Config $config)
    {
        $parts = array();
        if ($config->parent) {
            $parts[] = str_replace(
                array('{id}', '.{_format}'),
                array(sprintf('{%sId}', $this->getPrefix($config->parent)), ''),
                $this->generate($config->parent)
            );
        }
        $parts[] = $this->getPrefix($config);

        $prefix = implode('/', array_filter($parts));
        $pattern = $this->getPattern($config);

        if (isset($pattern[0]) && '/' !== $pattern[0] && '.' !== $pattern[0]) {
            return rtrim($prefix, '/').'/'.$pattern;
        }

        return $prefix.$pattern;
    }

def find_path(self, test_function=None, on_targets=False):

        assert self.has_referential_domain(), "need context set"

        if not test_function:
            test_function = lambda x, y: True

        def find_path_inner(part, prefix):
            name, structure = part
            if test_function(name, structure):
                yield prefix + [name]
            if isinstance(structure, DictCell):
                for sub_structure in structure:
                    for prefix2 in find_path_inner(sub_structure,\
                            prefix[:] + [name]):
                        yield prefix2

        prefix = []
        if on_targets:
            # apply search to the first target
            results = []
            for _, instance in self.iter_singleton_referents():
                for part in instance:
                    for entry in find_path_inner(part, prefix[:]):
                        results.append(['target'] + entry)
                while results:
                    yield results.pop()
                break # only use first instance
        else:
            # apply search to self
            for part in self:
                for entry in find_path_inner(part, prefix[:]):
                    yield entry

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


Question:
// NewCalendar creates a new Calendar with no holidays defined
// and work days of Monday through Friday.

func NewCalendar() *Calendar {
	c := &Calendar{}
	for i := range c.holidays {
		c.holidays[i] = make([]Holiday, 0, 2)
	}
	c.workday[time.Monday] = true
	c.workday[time.Tuesday] = true
	c.workday[time.Wednesday] = true
	c.workday[time.Thursday] = true
	c.workday[time.Friday] = true
	return c
}

public function setFilterDate(
        string $field,
        string $string = '',
        bool $active = true,
        string $format = null,
        string $class = '',
        string $style = '',
        string $placeholder = ''
    ): ColumnInterface {
        $this->setDateActive($active);
        if ($format) {
            $this->setDateFormat($format);
        }

        return $this->setFilter($field, $string, self::FILTER_TYPE_DATE, [], $class, $style, $placeholder);
    }

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


Question: // Decode reads the RSS document from the reader.

func Decode(r io.Reader) (*RSS, error) {
	dec := xml.NewDecoder(r)
	dec.CharsetReader = utils.CharsetReader
	rss := &RSS{}
	if err := dec.Decode(rss); err != nil {
		return nil, err
	}
	return rss, nil
}

def parse_resource(self, response):

        self._raise_if_bad_http_status_and_method(response)
        if not self._is_empty(response):
            self.resource = self._deserialize(response)
        else:
            self.resource = None

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


Question:
Get EC2 account health metrics

        Give some basic stats on the health of our EC2 account

        This method gives output: ``v1/health.json#``

        This method is ``experimental``

async def getHealth(self, *args, **kwargs):

        return await self._makeApiCall(self.funcinfo["getHealth"], *args, **kwargs)

func (p *defaultProvisioner) ProvisionStatus(paths Paths) (s ProvisionStatus, err error) {
	// Open the file
	var f *os.File
	s.Electron = make(map[string]*ProvisionStatusPackage)
	if f, err = os.Open(paths.ProvisionStatus()); err != nil {
		if !os.IsNotExist(err) {
			err = errors.Wrapf(err, "opening file %s failed", paths.ProvisionStatus())
		} else {
			err = nil
		}
		return
	}
	defer f.Close()

	// Unmarshal
	if errLocal := json.NewDecoder(f).Decode(&s); errLocal != nil {
		// For backward compatibility purposes, if there's an unmarshal error we delete the status file and make the
		// assumption that provisioning has to be done all over again
		astilog.Error(errors.Wrapf(errLocal, "json decoding from %s failed", paths.ProvisionStatus()))
		astilog.Debugf("Removing %s", f.Name())
		if errLocal = os.RemoveAll(f.Name()); errLocal != nil {
			astilog.Error(errors.Wrapf(errLocal, "removing %s failed", f.Name()))
		}
		return
	}
	return
}

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


Question: Print out timespans to be cut followed by the line number in the srt.

def demo_supercut(composition, padding):
    """"""
    for i, c in enumerate(composition):
        line = c['line']
        start = c['start']
        end = c['end']
        if i > 0 and composition[i - 1]['file'] == c['file'] and start < composition[i - 1]['end']:
            start = start + padding
        print("{1} to {2}:\t{0}".format(line, start, end))

def QA_util_get_real_datelist(start, end):

    real_start = QA_util_get_real_date(start, trade_date_sse, 1)
    real_end = QA_util_get_real_date(end, trade_date_sse, -1)
    if trade_date_sse.index(real_start) > trade_date_sse.index(real_end):
        return None, None
    else:
        return (real_start, real_end)

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


Question: start of code borrowed from OAuth in Action

function (auth) {
      var clientCredentials = Buffer.from(auth.slice('basic '.length), 'base64').toString().split(':')
      var clientId = querystring.unescape(clientCredentials[0])
      var clientSecret = querystring.unescape(clientCredentials[1])
      return { id: clientId, secret: clientSecret }
    }

public void authenticate() {
    if (mAccount == null) {
      // Create account also performs authentication.
      createAccount();
    } else {
      mAccess = mAccount.authenticate();
      if (mRegion != null) {
        mAccess.setPreferredRegion(mRegion);
      }
    }
  }

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


Question: Concatenate a sequence of pandas or numpy objects into one entity.

def concat(x, y, axis=0):
    """"""
    if all([isinstance(df, (pd.DataFrame, pd.Series)) for df in [x, y]]):
        return pd.concat([x, y], axis=axis)
    else:
        if axis == 0:
            return np.concatenate([x, y])
        else:
            return np.column_stack([x, y])

def get_data_with_timestamps(self):

        result = []
        for t, d in zip(self.timestamps, self.data_points):
            result.append(t, round(d, self.lr))
        return result

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


Question:
Return the next event that is safe for delivery or null
if there are no safe objects to deliver.

Null response could mean no events, or could mean all events
are scheduled for the future.

@param systemCurrentTimeMillis The current time.

@Override
    public T next(long systemCurrentTimeMillis) {
        // drain all the waiting messages from the source (up to 10k)
        while (delayed.size() < 10000) {
            T event = source.next(systemCurrentTimeMillis);
            if (event == null) {
                break;
            }
            transformAndQueue(event, systemCurrentTimeMillis);
        }

        return delayed.nextReady(systemCurrentTimeMillis);
    }

function () {
        var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;

        self.$el = $(self.getEl());
        self.state.set('rendered', true);

        // Bind on<event> settings
        for (name in settings) {
          if (name.indexOf("on") === 0) {
            self.on(name.substr(2), settings[name]);
          }
        }

        if (self._eventsRoot) {
          for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) {
            parentEventsRoot = parent._eventsRoot;
          }

          if (parentEventsRoot) {
            for (name in parentEventsRoot._nativeEvents) {
              self._nativeEvents[name] = true;
            }
          }
        }

        bindPendingEvents(self);

        if (settings.style) {
          elm = self.getEl();
          if (elm) {
            elm.setAttribute('style', settings.style);
            elm.style.cssText = settings.style;
          }
        }

        if (self.settings.border) {
          box = self.borderBox;
          self.$el.css({
            'border-top-width': box.top,
            'border-right-width': box.right,
            'border-bottom-width': box.bottom,
            'border-left-width': box.left
          });
        }

        // Add instance to lookup
        var root = self.getRoot();
        if (!root.controlIdLookup) {
          root.controlIdLookup = {};
        }

        root.controlIdLookup[self._id] = self;

        for (var key in self._aria) {
          self.aria(key, self._aria[key]);
        }

        if (self.state.get('visible') === false) {
          self.getEl().style.display = 'none';
        }

        self.bindStates();

        self.state.on('change:visible', function (e) {
          var state = e.value, parentCtrl;

          if (self.state.get('rendered')) {
            self.getEl().style.display = state === false ? 'none' : '';

            // Need to force a reflow here on IE 8
            self.getEl().getBoundingClientRect();
          }

          // Parent container needs to reflow
          parentCtrl = self.parent();
          if (parentCtrl) {
            parentCtrl._lastRect = null;
          }

          self.fire(state ? 'show' : 'hide');

          ReflowQueue.add(self);
        });

        self.fire('postrender', {}, false);
      }

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


Question:
Converts timestamp to carbon instance

@param Carbon\Carbon $timestamp

public static function fromMilliseconds($timestamp = null)
    {
        if (! $timestamp) {
            return null;
        }

        return Carbon::createFromTimestamp(self::toSeconds($timestamp));
    }

func SendCloudFormationResponse(lambdaCtx *awsLambdaCtx.LambdaContext,
	event *CloudFormationLambdaEvent,
	results map[string]interface{},
	responseErr error,
	logger *logrus.Logger) error {

	status := "FAILED"
	if nil == responseErr {
		status = "SUCCESS"
	}
	// Env vars:
	// https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html
	logGroupName := os.Getenv("AWS_LAMBDA_LOG_GROUP_NAME")
	logStreamName := os.Getenv("AWS_LAMBDA_LOG_STREAM_NAME")
	reasonText := ""
	if nil != responseErr {
		reasonText = fmt.Sprintf("%s. Details in CloudWatch Logs: %s : %s",
			responseErr.Error(),
			logGroupName,
			logStreamName)
	} else {
		reasonText = fmt.Sprintf("Details in CloudWatch Logs: %s : %s",
			logGroupName,
			logStreamName)
	}
	// PhysicalResourceId
	// This value should be an identifier unique to the custom resource vendor,
	// and can be up to 1 Kb in size. The value must be a non-empty string and
	// must be identical for all responses for the same resource.
	// Ref: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref-requesttypes-create.html
	physicalResourceID := fmt.Sprintf("LogStreamName: %s", logStreamName)
	responseData := map[string]interface{}{
		"Status":             status,
		"Reason":             reasonText,
		"PhysicalResourceId": physicalResourceID,
		"StackId":            event.StackID,
		"RequestId":          event.RequestID,
		"LogicalResourceId":  event.LogicalResourceID,
	}
	if nil != responseErr {
		responseData["Data"] = map[string]interface{}{
			"Error": responseErr,
		}
	} else if nil != results {
		responseData["Data"] = results
	} else {
		responseData["Data"] = map[string]interface{}{}
	}

	logger.WithFields(logrus.Fields{
		"ResponsePayload": responseData,
	}).Debug("Response Info")

	jsonData, jsonError := json.Marshal(responseData)
	if nil != jsonError {
		return errors.Wrap(jsonError, "Attempting to marshal Cloudformation response")
	}

	responseBuffer := strings.NewReader(string(jsonData))
	req, httpErr := http.NewRequest("PUT",
		event.ResponseURL,
		responseBuffer)

	if nil != httpErr {
		return httpErr
	}
	// Need to use the Opaque field b/c Go will parse inline encoded values
	// which are supposed to be roundtripped to AWS.
	// Ref: https://tools.ietf.org/html/rfc3986#section-2.2
	// Ref: https://golang.org/pkg/net/url/#URL
	// Ref: https://github.com/aws/aws-sdk-go/issues/337
	// parsedURL, parsedURLErr := url.ParseRequestURI(event.ResponseURL)

	// https://en.wikipedia.org/wiki/Percent-encoding
	mapReplace := map[string]string{
		":": "%3A",
		"|": "%7C",
	}
	req.URL.Opaque = req.URL.Path
	for eachKey, eachValue := range mapReplace {
		req.URL.Opaque = strings.Replace(req.URL.Opaque, eachKey, eachValue, -1)
	}
	req.URL.Path = ""
	req.URL.RawPath = ""

	logger.WithFields(logrus.Fields{
		"RawURL": event.ResponseURL,
		"URL":    req.URL,
		"Body":   responseData,
	}).Debug("Created URL response")

	// Although it seems reasonable to set the Content-Type to "application/json" - don't.
	// The Content-Type must be an empty string in order for the
	// AWS Signature checker to pass.
	// Ref: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html
	req.Header.Set("content-type", "")

	client := &http.Client{}
	resp, httpErr := client.Do(req)
	if httpErr != nil {
		return errors.Wrapf(httpErr, "Sending CloudFormation response")
	}
	logger.WithFields(logrus.Fields{
		"LogicalResourceId":  event.LogicalResourceID,
		"Result":             responseData["Status"],
		"ResponseStatusCode": resp.StatusCode,
	}).Debug("Sent CloudFormation response")

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		body, bodyErr := ioutil.ReadAll(resp.Body)
		if bodyErr != nil {
			logger.Warn("Unable to read body: " + bodyErr.Error())
			body = []byte{}
		}
		return errors.Errorf("Error sending response: %d. Data: %s", resp.StatusCode, string(body))
	}
	defer resp.Body.Close()
	return nil
}

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


Question: Adds this loss to the MARKED_LOSSES collection.

def mark_as_required(self):
    """"""
    if self not in tf.get_collection(bookkeeper.GraphKeys.MARKED_LOSSES):
      tf.add_to_collection(bookkeeper.GraphKeys.MARKED_LOSSES, self)

def from_toplosses(cls, learn, n_imgs=None, **kwargs):
        ""
        train_ds, train_idxs = cls.get_toplosses_idxs(learn, n_imgs, **kwargs)
        return train_ds, train_idxs

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


Question: Send a formatted message to the ADB server

def send(self, data):
        """"""
        self._send_data(int_to_hex(len(data)))

        self._send_data(data)

void bindField(AbstractField<?> field, String property) {

        m_group.bind(field, property);

        field.setCaption(CmsVaadinUtils.getMessageText("label." + property));
        field.setDescription(CmsVaadinUtils.getMessageText("label." + property + ".help"));
    }

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


Question: // ValidatePodBinding tests if required fields in the pod binding are legal.

func ValidatePodBinding(binding *core.Binding) field.ErrorList {
	allErrs := field.ErrorList{}

	if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
		// TODO: When validation becomes versioned, this gets more complicated.
		allErrs = append(allErrs, field.NotSupported(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", "<empty>"}))
	}
	if len(binding.Target.Name) == 0 {
		// TODO: When validation becomes versioned, this gets more complicated.
		allErrs = append(allErrs, field.Required(field.NewPath("target", "name"), ""))
	}

	return allErrs
}

def is_in(property_name, set_values, *, present_optional=False, message=None):
    """"""
    def check(val):
      """Checks that a value is contained within a scope-enclosed set."""
      if val is None:
        return present_optional
      else:
        return val in set_values

    return Validation(check, property_name, message)

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