Question:
if true, start the job
if false, just update the dialog box

private void updateEstimate(boolean startJob) {
        try {
            if (cache_east != null &&
                    cache_west != null &&
                    cache_north != null &&
                    cache_south != null &&
                    zoom_max != null &&
                    zoom_min != null &&
                    cache_output!=null) {
                double n = Double.parseDouble(cache_north.getText().toString());
                double s = Double.parseDouble(cache_south.getText().toString());
                double e = Double.parseDouble(cache_east.getText().toString());
                double w = Double.parseDouble(cache_west.getText().toString());
                if (startJob) {
                    String outputName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "osmdroid" + File.separator + cache_output.getText().toString();
                    writer=new SqliteArchiveTileWriter(outputName);
                    try {
                        mgr = new CacheManager(mMapView, writer);
                    } catch (TileSourcePolicyException ex) {
                        Log.e(TAG, ex.getMessage());
                        return;
                    }
                } else {
                    if (mgr==null) {
                        try {
                            mgr = new CacheManager(mMapView);
                        } catch (TileSourcePolicyException ex) {
                            Log.e(TAG, ex.getMessage());
                            return;
                        }
                    }
                }
                int zoommin = zoom_min.getProgress();
                int zoommax = zoom_max.getProgress();
                //nesw
                BoundingBox bb= new BoundingBox(n, e, s, w);
                int tilecount = mgr.possibleTilesInArea(bb, zoommin, zoommax);
                cache_estimate.setText(tilecount + " tiles");
                if (startJob)
                {
                    if ( downloadPrompt!=null) {
                        downloadPrompt.dismiss();
                        downloadPrompt=null;
                    }

                    //this triggers the download
                    mgr.downloadAreaAsync(getActivity(), bb, zoommin, zoommax, new CacheManager.CacheManagerCallback() {
                        @Override
                        public void onTaskComplete() {
                            Toast.makeText(getActivity(), "Download complete!", Toast.LENGTH_LONG).show();
                            if (writer!=null)
                                writer.onDetach();
                        }

                        @Override
                        public void onTaskFailed(int errors) {
                            Toast.makeText(getActivity(), "Download complete with " + errors + " errors", Toast.LENGTH_LONG).show();
                            if (writer!=null)
                                writer.onDetach();
                        }

                        @Override
                        public void updateProgress(int progress, int currentZoomLevel, int zoomMin, int zoomMax) {
                            //NOOP since we are using the build in UI
                        }

                        @Override
                        public void downloadStarted() {
                            //NOOP since we are using the build in UI
                        }

                        @Override
                        public void setPossibleTilesInArea(int total) {
                            //NOOP since we are using the build in UI
                        }
                    });
                }

            }
        }catch (Exception ex){
            //TODO something better?
            ex.printStackTrace();
        }
    }

function(l) {
			if (l.type === gui.LIFE_ENTER) {
				if (!this.spirit.life.rendered) { // spirit did a manual run?
					this.run.apply(this, this._arguments || []);
				}
				this.spirit.life.remove(l.type, this);
				this._arguments = null;
			}
		}

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


Question:
Route handler that returns system information
/ccm/api/v1/site/trees

public function trees(StandardSitemapProvider $provider, TreeCollectionTransformer $transformer)
    {
        // Extract the tree from the sitemap provider
        $tree = $provider->getTreeCollection();

        // Return a resource
        return $this->app->make(Item::class, [$tree, $transformer]);
    }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question:
处理关联关系

@param mixed $relation
可以是:
*** '本表字段'
*** '本表字段=关联表字段'
***    array('本表字段'=>'关联表字段')
***    array('本表字段','关联表字段')
@param $database string 数据库类型,当前只支持MYSQL
@return array(<本表字段>,<关联表字段>)

protected function relation($relation, string $database = 'mysql'): array
    {
        // 处理数据形式
        if (is_array($relation)) {
            foreach ($relation as $k => $v) {
                if (is_numeric($k)) {
                    return $v;
                }
                return [$k, $v];
            }
        }

        // 字符串形式
        if (!is_string($relation)) {
            trigger_error('关联关系格式错误:'.json($relation),E_USER_ERROR);
        }

        // 分解关联键
        $matches = explode('=', $relation);

        // 如果只指明了一个字段,默认后一个字段为_id/id(表的主键)
        if (count($matches) == 1) {
            return [$relation, $database == 'mongo' ? '_id' : 'id'];
        }

        // 返回两个关联键
        return $matches;
    }

public function equals(Database $database) {
        $prefix = '';
        $thisTables = $this->getTables();
        $databaseTables = $database->getTables();
        $errors = [];

        foreach($thisTables as $database) {
            if(array_key_exists($database->getName(), $databaseTables)) {
                $errors = array_merge($errors, $database->equals($databaseTables[$database->getName()], $prefix));
            }
        }

        $thisTableNames = array_keys($thisTables);
        $databaseTableNames = array_keys($databaseTables);
        $diff = array_diff($databaseTableNames, $thisTableNames);
        if(!empty($diff)) {
            $errors[] = $prefix . 'Extra Tables: ' . "\n" . implode("\n", $diff);
        }
        $diff = array_diff($thisTableNames, $databaseTableNames);
        if(!empty($diff)) {
            $errors[] = $prefix . 'Missing Tables: ' . "\n" . implode("\n", $diff);
        }
        return $errors;
    }

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


Question:
Helper function that pushes the provided slice onto the slices array.
@param {Slice} slice The slice to be added to the slices array.

function(slice) {
      this.haveTopLevelSlicesBeenBuilt = false;
      slice.parentContainer = this.parentContainer_;
      this.slices.push(slice);
      return slice;
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question: Get the paths to the relevant db files to back up

def get_state_paths(cls, impl, working_dir):

        return super(BlockstackDB, cls).get_state_paths(impl, working_dir) + [
                os.path.join(working_dir, 'atlas.db'),
                os.path.join(working_dir, 'subdomains.db'),
                os.path.join(working_dir, 'subdomains.db.queue')
            ]

public function getDatabase($alias, $target = Database::TARGET_MASTER)
    {
        $database = isset($this->_databases[$alias]) ? $this->_databases[$alias] : null;
        if ($target === Database::TARGET_SLAVE) {
            $database = $database->pickSlave();
        }
        return $database;
    }

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


Question: // SetNextToken sets the NextToken field's value.

func (s *ListUserPoolsOutput) SetNextToken(v string) *ListUserPoolsOutput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question: // WithComment returns the WaitDelay comment

func (wd *WaitDelay) WithComment(comment string) TransitionState {
	wd.comment = comment
	return wd
}

func (d *GrovePiDriver) WriteAnalog(pin byte, val byte) error {
	buf := []byte{CommandWriteAnalog, pin, val, 0}
	_, err := d.connection.Write(buf)

	time.Sleep(2 * time.Millisecond)

	data := make([]byte, 1)
	_, err = d.connection.Read(data)

	return err
}

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


Question:
// pinOp creates a pin instance from the input lease name,
// then sends it on the input channel.

func (b *boundManager) pinOp(leaseName string, entity string, ch chan pin) error {
	return errors.Trace(pin{
		leaseKey: b.leaseKey(leaseName),
		entity:   entity,
		response: make(chan error),
		stop:     b.manager.catacomb.Dying(),
	}.invoke(ch))
}

def init_vpc_entries(nexus_ip, vpc_list):

    LOG.debug("init_vpc_entries() called")

    if not vpc_list:
        return
    session = bc.get_writer_session()

    for vpc in vpc_list:
        vpc_alloc = nexus_models_v2.NexusVPCAlloc(
            switch_ip=nexus_ip,
            vpc_id=vpc,
            learned=False,
            active=False)
        session.add(vpc_alloc)
    session.flush()

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


Question: // WatchSinkChanges returns a new ClientConfigChangerSink that wraps a sink with auth/endpoint changes from distconf

func WatchSinkChanges(sink sfxclient.Sink, Conf *ClientConfig, logger log.Logger) sfxclient.Sink {
	httpSink, ok := sink.(*sfxclient.HTTPSink)
	if !ok {
		return sink
	}
	return WatchHTTPSinkChange(httpSink, Conf, logger)
}

def cli(ctx):

    ctx.obj = Wio()
    cur_dir = os.path.abspath(os.path.expanduser("~/.wio"))
    if not os.path.exists(cur_dir):
        text = {"email":"", "token":""}
        os.mkdir(cur_dir)
        open("%s/config.json"%cur_dir,"w").write(json.dumps(text))
    db_file_path = '%s/config.json' % cur_dir
    config = json.load(open(db_file_path))
    ctx.obj.config = config

    signal.signal(signal.SIGINT, sigint_handler)

    if not verify:
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

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


Question:
Cancels the specified subnet.

        :param int subnet_id: The ID of the subnet to be cancelled.

def cancel_subnet(self, subnet_id):

        subnet = self.get_subnet(subnet_id, mask='id, billingItem.id')
        if "billingItem" not in subnet:
            raise exceptions.SoftLayerError("subnet %s can not be cancelled"
                                            " " % subnet_id)
        billing_id = subnet['billingItem']['id']
        return self.client['Billing_Item'].cancelService(id=billing_id)

def _netstat_route_sunos():
    '''

    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    cmd = 'netstat -f inet6 -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    return ret

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


Question:
Replace RouteKeyName dummy.

@param string $stub
@param array  $fields

@return $this

protected function replaceRouteKeyName(&$stub, $route_key_name){

        if($route_key_name=='id')
            $replace = "";
        else{
            $replace = "public function getRouteKeyName(){ return \"{$route_key_name}\"; }";
        }

        $stub = str_replace('DummyRouteKeyName', $replace, $stub);

        return $this;
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question: // Returns the form

func (r *GoRequest) GetForm() (url.Values, error) {
	if !r.FormParsed {
		if e := r.Original.ParseForm(); e != nil {
			return nil, e
		}
		r.FormParsed = true
	}

	return r.Original.Form, nil
}

protected function definition_inner($mform) {
        $mform->addElement('advcheckbox', 'shuffleanswers',
                get_string('shuffle', 'qtype_match'), null, null, array(0, 1));
        $mform->addHelpButton('shuffleanswers', 'shuffle', 'qtype_match');
        $mform->setDefault('shuffleanswers', 1);

        $this->add_per_answer_fields($mform, get_string('questionno', 'question', '{no}'), 0);

        $this->add_combined_feedback_fields(true);
        $this->add_interactive_settings(true, true);
    }

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


Question:
Binds element's properties to state changes from the Redux store.

@example
const update = bind(el, props) // set bindings
update(state) // manual update

@private
@param {HTMLElement} element
@param {Object} properties
@return {Function} Update function.

function bind(element, properties) {
    var bindings = Object.keys(properties).filter(function (name) {
      var property = properties[name];
      if (Object.prototype.hasOwnProperty.call(property, 'statePath')) {
        if (!property.readOnly && property.notify) {
          console.warn('PolymerRedux: <' + element.constructor.is + '>.' + name + ' has "notify" enabled, two-way bindings goes against Redux\'s paradigm');
        }
        return true;
      }
      return false;
    });

    /**
     * Updates an element's properties with the given state.
     *
     * @private
     * @param {Object} state
     */
    var update = function update(state) {
      var propertiesChanged = false;
      bindings.forEach(function (name) {
        // Perhaps .reduce() to a boolean?
        var statePath = properties[name].statePath;

        var value = typeof statePath === 'function' ? statePath.call(element, state) : (0, _path.get)(state, statePath);

        var changed = element._setPendingPropertyOrPath(name, value, true);
        propertiesChanged = propertiesChanged || changed;
      });
      if (propertiesChanged) {
        element._invalidateProperties();
      }
    };

    // Redux listener
    var unsubscribe = store.subscribe(function () {
      var detail = store.getState();
      update(detail);

      element.dispatchEvent(new window.CustomEvent('state-changed', { detail: detail }));
    });

    subscribers.set(element, unsubscribe);

    return update(store.getState());
  }

function parse (buffer, doc, options, key) {
  switch (doc.type) {
    case 'text':
      return [...buffer, doc.content]
    case 'tag': {
      let children = reactify(doc.children, options, key)
      if (!children.length) {
        children = null
      }
      if (doc.name.startsWith(COMMENT_TAG)) {
        return [...buffer, ...children]
      }
      const tag = options.mappings[doc.name] || DEFAULT_TAG
      if (tag.fromMarkup) {
        doc.attrs = tag.fromMarkup(doc.attrs)
      }
      if (tag === DEFAULT_TAG && !doc.attrs.as) {
        doc.attrs.as = doc.name
      }
      if (doc.attrs.class) {
        // Rename class to className for React compatibility
        doc.attrs.className = doc.attrs.class
        delete doc.attrs.class
      }
      return [...buffer, createElement(tag, { key, ...doc.attrs }, children)]
    }
    default:
      return buffer
  }
}

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


Question:
Filter by page

@param pageNumber    the page number to retrieve.
@param amountPerPage the amount of items per page to retrieve.
@return this filter instance

public QueryFilter withPage(int pageNumber, int amountPerPage) {
        parameters.put("page", pageNumber);
        parameters.put("per_page", amountPerPage);
        return this;
    }

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_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:
Get all questions by user

@param string $value
@param string $what

public function getAllQuestionByUser($value, $what)
    {
        $result = [];

        $sqlBuilder = new module_report_sql($this->app, $this);

        $filter = $sqlBuilder->getFilters()->getReportFilter();
        $params = array_merge([':main_value' => $value], $filter['params']);

        $sql = "
            SELECT DATE_FORMAT(log_search.date,'%Y-%m-%d %H:%i:%S') AS date ,
            log_search.search ,log_search.results
            FROM (log_search)
                INNER JOIN log FORCE INDEX (date_site) ON (log.id = log_search.log_id)
                INNER JOIN log_colls FORCE INDEX (couple) ON (log.id = log_colls.log_id)
            WHERE (" . $filter['sql'] . ")
            AND log.`" . $what . "` = :main_value
            ORDER BY date ";

        $stmt = $sqlBuilder->getConnBas()->prepare($sql);
        $stmt->execute($params);
        $sqlBuilder->setTotalrows($stmt->rowCount());
        $stmt->closeCursor();

        $sql .= $sqlBuilder->getFilters()->getLimitFilter();

        $stmt = $sqlBuilder->getConnBas()->prepare($sql);
        $stmt->execute($params);
        $rs = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        $this->setChamp($rs);
        $this->initDefaultConfigColumn($this->champ);
        $i = 0;

        foreach ($rs as $row) {
            foreach ($this->champ as $value) {
                $result[$i][$value] = $row[$value];
            }
            $i++;
        }

        $this->title = $this->app->trans('report:: questions');
        $this->setResult($result);

        return $this->result;
    }

def fetch_data(self, **var):
        """"""
        varstr = ','.join(name + self._convert_indices(ind)
                          for name, ind in var.items())
        query = self.query().add_query_parameter(req='data', var=varstr)
        return self._fetch(query)

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


Question: Service for interacting with RESTful services.

function Resource(url, params, actions, options$$1) {

    var self = this || {}, resource = {};

    actions = assign({},
        Resource.actions,
        actions
    );

    each(actions, function (action, name) {

        action = merge({url: url, params: assign({}, params)}, options$$1, action);

        resource[name] = function () {
            return (self.$http || Http)(opts(action, arguments));
        };
    });

    return resource;
}

func (s *Server) RegisterEndpoint(name string, handler interface{}) error {
	s.logger.Printf("[WARN] consul: endpoint injected; this should only be used for testing")
	return s.rpcServer.RegisterName(name, handler)
}

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


Question:
@param Request $request
@param Entity  $entity

@return Response

protected function renderEntity(Request $request, Entity $entity)
    {
        $params = $this->getImplicitParams($entity);

        return $this->getRenderer()->render($entity, $request, $params);
    }

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

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

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

            HttpClient httpClient = provider.getClient();

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

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

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

            HttpResponse response = null;
            int retryCount = 0;

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

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

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

        }
    }

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


Question: Iterator that yields decompressed ``IDAT`` strings.

def idatdecomp(self, lenient=False, max_length=0):
        """"""
        # Currently, with no max_length paramter to decompress, this
        # routine will do one yield per IDAT chunk.  So not very
        # incremental.
        d = zlib.decompressobj()
        # Each IDAT chunk is passed to the decompressor, then any
        # remaining state is decompressed out.
        for data in self.idat(lenient):
            # :todo: add a max_length argument here to limit output
            # size.
            yield bytearray(d.decompress(data))
        yield bytearray(d.flush())

def retrieve(run_id, det_id, outfile=None):
    """"""
    try:
        det_id = int(det_id)
    except ValueError:
        pass
    path = irods_filepath(det_id, run_id)
    suffix = '' if outfile is None else outfile
    os.system("iget -Pv {0} {1}".format(path, suffix))

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


Question:
Creates the "meta.xml" file under the root folder

@return FileSystemHelper
@throws \Box\Spout\Common\Exception\IOException If unable to create the file

protected function createMetaFile()
    {
        $appName = self::APP_NAME;
        $createdDate = (new \DateTime())->format(\DateTime::W3C);

        $metaXmlFileContents = <<<EOD
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<office:document-meta office:version="1.2" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xlink">
    <office:meta>
        <dc:creator>$appName</dc:creator>
        <meta:creation-date>$createdDate</meta:creation-date>
        <dc:date>$createdDate</dc:date>
    </office:meta>
</office:document-meta>
EOD;

        $this->createFileWithContents($this->rootFolder, self::META_XML_FILE_NAME, $metaXmlFileContents);

        return $this;
    }

protected HtmlTree getTreeHeader() {
        String title = configuration.getText("doclet.Window_Class_Hierarchy");
        HtmlTree bodyTree = getBody(true, getWindowTitle(title));
        HtmlTree htmlTree = (configuration.allowTag(HtmlTag.HEADER))
                ? HtmlTree.HEADER()
                : bodyTree;
        addTop(htmlTree);
        addNavLinks(true, htmlTree);
        if (configuration.allowTag(HtmlTag.HEADER)) {
            bodyTree.addContent(htmlTree);
        }
        return bodyTree;
    }

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


Question: Tells the models which fields to expect.

protected function loadFields()
    {
        $forResp  = $this->_('for respondents');
        $forStaff = $this->_('for staff');

        $this->addField('tokens')
                ->setLabel($this->_('Activated surveys'))
                ->setToCount("gto_id_token");

        $tUtil = $this->util->getTokenData();
        foreach ($this->statiUsed as $key) {
            $this->addField('stat_' . $key)
                    ->setLabel([$tUtil->getStatusIcon($key), ' ', $tUtil->getStatusDescription($key)])
                    ->setToSumWhen($tUtil->getStatusExpressionFor($key));
        }
    }

public function generate($type)
    {
        return function ($row, $control, $templates = []) use ($type) {
            $data = $this->buildFieldByType($type, $row, $control);
            return $this->render($templates, $data);
        };
    }

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


Question:
Attributes to set on the generated XML element

@return A Map of attribute keys to values

protected Map<String, String> getElementAttributes() {
        // Preserve order of attributes
        Map<String, String> attrs = new HashMap<>();

        if (this.getInputs() != null) {
            attrs.put("input", this.getInputsAsString());
        }
        if (this.getAction() != null) {
            attrs.put("action", this.getAction().toString());
        }
        if (this.getMethod() != null) {
            attrs.put("method", this.getMethod().toString());
        }
        if (this.getTimeout() != null) {
            attrs.put("timeout", this.getTimeout().toString());
        }
        if (this.getSpeechTimeout() != null) {
            attrs.put("speechTimeout", this.getSpeechTimeout());
        }
        if (this.getMaxSpeechTime() != null) {
            attrs.put("maxSpeechTime", this.getMaxSpeechTime().toString());
        }
        if (this.isProfanityFilter() != null) {
            attrs.put("profanityFilter", this.isProfanityFilter().toString());
        }
        if (this.getFinishOnKey() != null) {
            attrs.put("finishOnKey", this.getFinishOnKey());
        }
        if (this.getNumDigits() != null) {
            attrs.put("numDigits", this.getNumDigits().toString());
        }
        if (this.getPartialResultCallback() != null) {
            attrs.put("partialResultCallback", this.getPartialResultCallback().toString());
        }
        if (this.getPartialResultCallbackMethod() != null) {
            attrs.put("partialResultCallbackMethod", this.getPartialResultCallbackMethod().toString());
        }
        if (this.getLanguage() != null) {
            attrs.put("language", this.getLanguage().toString());
        }
        if (this.getHints() != null) {
            attrs.put("hints", this.getHints());
        }
        if (this.isBargeIn() != null) {
            attrs.put("bargeIn", this.isBargeIn().toString());
        }
        if (this.isDebug() != null) {
            attrs.put("debug", this.isDebug().toString());
        }
        if (this.isActionOnEmptyResult() != null) {
            attrs.put("actionOnEmptyResult", this.isActionOnEmptyResult().toString());
        }

        return attrs;
    }

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

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

        $generator->startList('Tag');

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

        $generator->endList('Tag');

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

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


Question:
List all assets in a book
Assets are file not ignored and not a page

@param {Book} book
@param {List<String>} pages
@param

function listAssets(book, pages) {
    var fs = book.getContentFS();

    var summary = book.getSummary();
    var summaryFile = summary.getFile().getPath();

    var glossary = book.getGlossary();
    var glossaryFile = glossary.getFile().getPath();

    var langs = book.getLanguages();
    var langsFile = langs.getFile().getPath();

    var config = book.getConfig();
    var configFile = config.getFile().getPath();

    function filterFile(file) {
        return !(
            file === summaryFile ||
            file === glossaryFile ||
            file === langsFile ||
            file === configFile ||
            book.isContentFileIgnored(file) ||
            pages.has(file)
        );
    }

    return timing.measure(
        'parse.listAssets',
        fs.listAllFiles('.', filterFile)
    );
}

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: Prints out an SSH key to the screen.

def cli(env, identifier, out_file):
    """"""

    mgr = SoftLayer.SshKeyManager(env.client)

    key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey')

    key = mgr.get_key(key_id)

    if out_file:
        with open(path.expanduser(out_file), 'w') as pub_file:
            pub_file.write(key['key'])

    table = formatting.KeyValueTable(['name', 'value'])
    table.add_row(['id', key['id']])
    table.add_row(['label', key.get('label')])
    table.add_row(['notes', key.get('notes', '-')])
    env.fout(table)

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

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


Question:
Returns bundle id if provided path is matched with any bundle base directory.

@param string $path

@return string

public function getBundleIdByBaseDir($path)
    {
        $bundleId = null;
        foreach ($this->bundleInfos as $id => $data) {
            if (0 === strpos($path, $data['base_dir'])) {
                $bundleId = $id;
                break;
            }
        }

        return $bundleId;
    }

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

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

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


Question: // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NetNamespaceList.

func (in *NetNamespaceList) DeepCopy() *NetNamespaceList {
	if in == nil {
		return nil
	}
	out := new(NetNamespaceList)
	in.DeepCopyInto(out)
	return out
}

def organize_objects(self):
        """"""

        def _render_children(obj):
            for child in obj.children_strings:
                child_object = self.objects.get(child)
                if child_object:
                    obj.item_map[child_object.plural].append(child_object)
                    obj.children.append(child_object)

            for key in obj.item_map:
                obj.item_map[key].sort()

        def _recurse_ns(obj):
            if not obj:
                return
            namespace = obj.top_namespace
            if namespace is not None:
                ns_obj = self.top_namespaces.get(namespace)
                if ns_obj is None or not isinstance(ns_obj, DotNetNamespace):
                    for ns_obj in self.create_class(
                        {"uid": namespace, "type": "namespace"}
                    ):
                        self.top_namespaces[ns_obj.id] = ns_obj
                if obj not in ns_obj.children and namespace != obj.id:
                    ns_obj.children.append(obj)

        for obj in self.objects.values():
            _render_children(obj)
            _recurse_ns(obj)

        # Clean out dead namespaces
        for key, ns in self.top_namespaces.copy().items():
            if not ns.children:
                del self.top_namespaces[key]

        for key, ns in self.namespaces.items():
            if not ns.children:
                del self.namespaces[key]

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


Question:
Sets the default named output (Tuple format) specs. By using this method one can use an arbitrary number of named outputs
without pre-defining them beforehand.

public void setDefaultNamedOutput(Schema outputSchema) throws TupleMRException {
  	Output output = new Output(true, "DEFAULT", new TupleOutputFormat(outputSchema),
        ITuple.class, NullWritable.class, null);
    namedOutputs.add(output);
  }

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question:
Used to populate Map with given annotations

@param annotations initial value for annotations

private void populateAnnotations(Collection<Annotation> annotations) {
        for (Annotation each : annotations) {
            this.annotations.put(each.annotationType(), each);
        }
    }

protected Parameter[] createDefaultParameters(Class[] parameters) {
		Parameter[] componentParameters = new Parameter[parameters.length];
		for (int i = 0; i < parameters.length; i++) {
			componentParameters[i] = ComponentParameter.DEFAULT;
		}
		return componentParameters;
	}

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


Question:
分析表达式的数据引用

@param {Object} expr 要分析的表达式
@return {Array}

function analyseExprDataHotspot(expr, accessorMeanDynamic) {
    var refs = [];
    var isDynamic;

    function analyseExprs(exprs, accessorMeanDynamic) {
        for (var i = 0, l = exprs.length; i < l; i++) {
            refs = refs.concat(analyseExprDataHotspot(exprs[i], accessorMeanDynamic));
            isDynamic = isDynamic || exprs[i].dynamic;
        }
    }

    switch (expr.type) {
        case ExprType.ACCESSOR:
            isDynamic = accessorMeanDynamic;

            var paths = expr.paths;
            refs.push(paths[0].value);

            if (paths.length > 1) {
                refs.push(paths[0].value + '.' + (paths[1].value || '*'));
            }

            analyseExprs(paths.slice(1), 1);
            break;

        case ExprType.UNARY:
            refs = analyseExprDataHotspot(expr.expr, accessorMeanDynamic);
            isDynamic = expr.expr.dynamic;
            break;

        case ExprType.TEXT:
        case ExprType.BINARY:
        case ExprType.TERTIARY:
            analyseExprs(expr.segs, accessorMeanDynamic);
            break;

        case ExprType.INTERP:
            refs = analyseExprDataHotspot(expr.expr);
            isDynamic = expr.expr.dynamic;

            each(expr.filters, function (filter) {
                analyseExprs(filter.name.paths);
                analyseExprs(filter.args);
            });

            break;

        case ExprType.ARRAY:
        case ExprType.OBJECT:
            for (var i = 0; i < expr.items.length; i++) {
                refs = refs.concat(analyseExprDataHotspot(expr.items[i].expr));
                isDynamic = isDynamic || expr.items[i].expr.dynamic;
            }
            break;
    }

    isDynamic && (expr.dynamic = true);
    return refs;
}

protected function getFacetParameters() {
        $facetParameters = [];
        $facetParameters['facet'] = 'true';
        $facetParameters['facet.mincount'] = $this->getMinCount();
        $facetParameters['facet.limit'] = $this->getLimit();
        $facetParameters['facet.field'] = $this->getFields();

        foreach ($this->getAdditionalParameters() as $additionalParameterKey => $additionalParameterValue) {
            $facetParameters[$additionalParameterKey] = $additionalParameterValue;
        }

        if ($facetParameters['json.facet']) {
            $facetParameters['json.facet'] = json_encode($facetParameters['json.facet']);
        }

        $facetParameters = $this->applySorting($facetParameters);
        return $facetParameters;
    }

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


Question:
Initializes the options for the object

Called from {@link __construct()} as a first step of object instantiation.

@param  KObjectConfig $config An optional ObjectConfig object with configuration options

protected function _initialize(KObjectConfig $config)
    {
        $config->append(array(
            'debug'        => false,
            'cache'        => false,
            'cache_path'   => '',
            'cache_reload' => true,
            'template'     => 'default',
            'functions'    => array(
                'object'    => array($this, 'getObject'),
                'translate' => array($this->getObject('translator'), 'translate'),
                'json'      => 'json_encode',
                'format'    => 'sprintf',
                'replace'   => 'strtr',
            ),
        ));

        parent::_initialize($config);
    }

protected function process(array $config, ContainerBuilder $container)
    {
        $container->setParameter('qcm_core.website_name', $config['website_name']);
        $container->setParameter('qcm.model.user.class', $config['user_class']);
        $container->setParameter('qcm.configuration', $config['configuration']);
        $container->setParameter('qcm_core.statistics.class', $config['service']['statistics']['class']);
        $container->setParameter('qcm_core.template.class', $config['service']['statistics']['template']);

        $container->setAlias('qcm.configuration', $config['service']['configuration']);
        $container->setAlias('qcm.user_session_configuration', $config['service']['user_session_configuration']);

        return $config;
    }

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


Question:
// SetCookiesHandler sets the query key/value pairs as cookies
// in the response and returns a 302 redirect to /cookies.

func SetCookiesHandler(w http.ResponseWriter, r *http.Request) {
	for k := range r.URL.Query() {
		v := r.URL.Query().Get(k)
		http.SetCookie(w, &http.Cookie{
			Name:  k,
			Value: v,
			Path:  "/",
		})
	}
	w.Header().Set("Location", "/cookies")
	w.WriteHeader(http.StatusFound)
}

private void setHeaders(HttpMessage message, Map<String, String> headers) {
		message.setHeader(RequestHeaderKey.ACCEPT, RequestHeaderValue.Accept.ALL);
		message.setHeader(RequestHeaderKey.CONNECTION, RequestHeaderValue.Connection.KEEP_ALIVE);
		message.setHeader(RequestHeaderKey.USER_AGENT, this.config.getUserAgent());

		if (headers != null) {
			for (String headerKey : headers.keySet()) {
				message.setHeader(headerKey, headers.get(headerKey));
			}
		}
	}

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


Question:
Returns an option combined with its sole/first permission

@param string $id_option
@param string $type
@param bool $force
@return array|bool

public function get(string $id_option = null, string $type = 'page', bool $force = false): ?array
  {
    /*
    if ( $all = $this->get_all($id_option, $type) ){
      $r = [];
      foreach ( $all as $a ){
        if ( $this->has($a['id'], '', $force) ){
          $r[] = $a;
        }
      }
      return $r;
    }
    */
    if (
      ($id_option = $this->_get_id_option($id_option, $type)) &&
      $this->has($id_option, $type, $force)
    ){
      return $this->pref->option($id_option);
    }
    return null;
  }

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

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


Question: Returns true if the filename has an image extension.

def IsImage(self, filename):
		""""""
		mimetype =  mimetypes.guess_type(filename)[0]
		if not mimetype:
			return False
		return mimetype.startswith("image/")

public function assertStringEqualsFile($expectedFile, $canonicalize = false, $ignoreCase = false) {
        $this->callAssertMethod(__FUNCTION__, [
            'expected' => $expectedFile,
            'additionalParams' => [
                $canonicalize,
                $ignoreCase,
            ],
        ]);
    }

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


Question:
Raises an ``UnallowedMethodCallError`` with a useful message.

        :raise: ``UnallowedMethodCallError``

def _raise_exception(self, args, kwargs):

        error_message = (
            "Received unexpected call to '{}' on {!r}.  The supplied arguments "
            "{} do not match any available allowances."
        )

        raise UnallowedMethodCallError(
            error_message.format(
                self._method_name,
                self._target.obj,
                build_argument_repr_string(args, kwargs)
            )
        )

func (c *Call) matches(args []interface{}) error {
	if !c.methodType.IsVariadic() {
		if len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}

		for i, m := range c.args {
			if !m.Matches(args[i]) {
				return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
					c.origin, strconv.Itoa(i), args[i], m)
			}
		}
	} else {
		if len(c.args) < c.methodType.NumIn()-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
				c.origin, len(c.args), c.methodType.NumIn()-1)
		}
		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}
		if len(args) < len(c.args)-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
				c.origin, len(args), len(c.args)-1)
		}

		for i, m := range c.args {
			if i < c.methodType.NumIn()-1 {
				// Non-variadic args
				if !m.Matches(args[i]) {
					return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
						c.origin, strconv.Itoa(i), args[i], m)
				}
				continue
			}
			// The last arg has a possibility of a variadic argument, so let it branch

			// sample: Foo(a int, b int, c ...int)
			if i < len(c.args) && i < len(args) {
				if m.Matches(args[i]) {
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
					// Got Foo(a, b) want Foo(matcherA, matcherB)
					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
					continue
				}
			}

			// The number of actual args don't match the number of matchers,
			// or the last matcher is a slice and the last arg is not.
			// If this function still matches it is because the last matcher
			// matches all the remaining arguments or the lack of any.
			// Convert the remaining arguments, if any, into a slice of the
			// expected type.
			vargsType := c.methodType.In(c.methodType.NumIn() - 1)
			vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
			for _, arg := range args[i:] {
				vargs = reflect.Append(vargs, reflect.ValueOf(arg))
			}
			if m.Matches(vargs.Interface()) {
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
				break
			}
			// Wrong number of matchers or not match. Fail.
			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
			return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
				c.origin, strconv.Itoa(i), args[i:], c.args[i])

		}
	}

	// Check that all prerequisite calls have been satisfied.
	for _, preReqCall := range c.preReqs {
		if !preReqCall.satisfied() {
			return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
				c.origin, preReqCall, c)
		}
	}

	// Check that the call is not exhausted.
	if c.exhausted() {
		return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
	}

	return nil
}

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


Question:
// Add an event listener channel to the list that will be notified on
// major state change events. Channels must be buffered by at least 1
// or they will block. Channels must be ready to receive input.

func (state *ServicesState) AddListener(listener Listener) {
	if listener.Chan() == nil {
		log.Errorf("Refusing to add listener %s with nil channel!", listener.Name())
		return
	}

	if cap(listener.Chan()) < 1 {
		log.Errorf("Refusing to add blocking channel as listener: %s", listener.Name())
		return
	}
	state.Lock()
	defer state.Unlock()

	state.listeners[listener.Name()] = listener
	log.Debugf("AddListener(): added %s, new count %d", listener.Name(), len(state.listeners))
}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question:
Generic handler that will write to both SSH and telnet channel.

        :param out_data: data to be written to the channel
        :type out_data: str (can be either unicode/byte string)

def write_channel(self, out_data):

        self._lock_netmiko_session()
        try:
            self._write_channel(out_data)
        finally:
            # Always unlock the SSH channel, even on exception.
            self._unlock_netmiko_session()

def __type2str(type_, buf, _, tbl):

    del buf[:]
    if type_ in tbl:
        buf.extend(tbl[type_].encode('ascii'))
    else:
        buf.extend('0x{0:x}'.format(type_).encode('ascii'))
    return buf

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


Question: Return the unit name to the unit 'unit_id'

def get_unit_name(unit_id):

    attribute = 'cn'
    response = LDAP_search(
        pattern_search='(uniqueIdentifier={})'.format(unit_id),
        attribute=attribute
    )
    try:
        unit_name = get_attribute(response, attribute)
    except Exception:
        raise EpflLdapException("The unit with id '{}' was not found".format(unit_id))

    return unit_name

protected function getCountry($countryId)
    {
        $entityManager = $this->getEntityManager();

        /** @var \Rcm\Repository\Country $countryRepo */
        $countryRepo = $entityManager->getRepository(\Rcm\Entity\Country::class);

        $country = $countryRepo->find(
            $countryId
        );

        if (!$country instanceof Country) {
            throw new \Exception("Country {$countryId} could not be found.");
        }

        return $country;
    }

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


Question:
Return the API ID.

        :return: API ID
        :rtype: str

def get_api_id(self):

        logger.debug('Connecting to AWS apigateway API')
        conn = client('apigateway')
        apis = conn.get_rest_apis()
        api_id = None
        for api in apis['items']:
            if api['name'] == self.config.func_name:
                api_id = api['id']
                logger.debug('Found API id: %s', api_id)
                break
        if api_id is None:
            raise Exception('Unable to find ReST API named %s' %
                            self.config.func_name)
        return api_id

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

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


Question:
Communicates the result to the User.

@param OutputInterface $output
@param string[]        $wrongfullyChangedFiles

private function publishFindingsToUser(OutputInterface $output, array $wrongfullyChangedFiles)
    {
        if (empty($wrongfullyChangedFiles)) {
            $output->writeln('All good!');
        } else {
            $output->writeln(
                'The following files violate change constraints: ' . PHP_EOL
                . implode(PHP_EOL, $wrongfullyChangedFiles)
            );
        }
    }

func (p *Engine) ExecuteWriter(out io.Writer, name string, binding interface{}, options ...map[string]interface{}) error {
	if tmpl := p.fromCache(name); tmpl != nil {
		return tmpl.ExecuteWriter(getPongoContext(binding), out)
	}

	return fmt.Errorf("[IRIS TEMPLATES] Template with name %s doesn't exists in the dir", name)
}

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


def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

private function swapTypes( $typesSet )
	{
		$this->context->typesBackup = &$this->context->types;

		$this->context->types = new XBRL_Types();
		$this->context->types->fromArray( $typesSet );
	}

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


Question:
Print a parameter as a String.

@param parameterName the name of the parameter to print
@param parameterValue the value of the parameter to print
@return the printed parameter
@since 7.4.5
@since 8.2RC1

public String print(String parameterName, String parameterValue)
    {
        // escape meaningfull strings
        String value = this.escaped.matcher(parameterValue).replaceAll(this.replacement);

        return parameterName + "=" + QUOTE + value + QUOTE;
    }

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: // Opens the output of NewPerUserKeyPrev

func openPerUserKeyPrev(sbox PerUserKeyPrev, symmetricKey NaclSecretBoxKey) (PerUserKeySeed, error) {
	var res PerUserKeySeed

	// decode b64
	msgpacked, err := base64.StdEncoding.DecodeString(string(sbox))
	if err != nil {
		return res, err
	}

	// decode msgpack
	mh := codec.MsgpackHandle{WriteExt: true}
	dec := codec.NewDecoderBytes(msgpacked, &mh)
	var parts struct {
		Version int
		Nonce   []byte
		Sealed  []byte
	}
	err = dec.Decode(&parts)
	if err != nil {
		return res, err
	}

	// check parts
	if parts.Version != 1 {
		return res, fmt.Errorf("per user key secret box version %v != 1", parts.Version)
	}

	if len(parts.Nonce) != NaclDHNonceSize {
		return res, fmt.Errorf("per user key secret box nonce length %v != %v",
			len(parts.Nonce), NaclDHNonceSize)
	}
	var nonce [NaclDHNonceSize]byte
	copy(nonce[:], parts.Nonce)

	expectedSealedLength := PerUserKeySeedSize + secretbox.Overhead
	if len(parts.Sealed) != expectedSealedLength {
		return res, fmt.Errorf("per user key secret box sealed length %v != %v", len(parts.Sealed), expectedSealedLength)
	}

	// open secretbox
	var symmetricKey2 [NaclSecretBoxKeySize]byte = symmetricKey
	contents, ok := secretbox.Open(nil, parts.Sealed, &nonce, &symmetricKey2)
	if !ok {
		return res, errors.New("per user key secret box open failed")
	}
	if len(contents) != PerUserKeySeedSize {
		return res, fmt.Errorf("per user key seed length %v != %v", len(contents), PerUserKeySeedSize)
	}
	return MakeByte32(contents), nil
}

public boolean checkError() {
        if (out != null) {
            flush();
        }
        if (out instanceof java.io.PrintWriter) {
            PrintWriter pw = (PrintWriter) out;
            return pw.checkError();
        } else if (psOut != null) {
            return psOut.checkError();
        }
        return trouble;
    }

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


Question: Marshall the given parameter object.

public void marshall(DescribeVpcPeeringAuthorizationsRequest describeVpcPeeringAuthorizationsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Get the content of the given element.

@param element
The element to get the content for.
@param defaultStr
The default to return when there is no content.
@return The content of the element or the default.
@throws Exception
the exception

private static String getElementContent(Element element, String defaultStr)
    {
        if (element == null)
        {
            return defaultStr;
        }

        NodeList children = element.getChildNodes();
        StringBuilder result = new StringBuilder("");
        for (int i = 0; i < children.getLength(); i++)
        {
            if (children.item(i).getNodeType() == Node.TEXT_NODE
                    || children.item(i).getNodeType() == Node.CDATA_SECTION_NODE)
            {
                result.append(children.item(i).getNodeValue());
            }
        }
        return result.toString().trim();
    }

public E buildTextComponent() {
        final E textComponent = createTextComponent();

        textComponent.setRequired(required);
        textComponent.setImmediate(immediate);
        textComponent.setReadOnly(readOnly);
        textComponent.setEnabled(enabled);

        if (!StringUtils.isEmpty(caption)) {
            textComponent.setCaption(caption);
        }

        if (!StringUtils.isEmpty(style)) {
            textComponent.setStyleName(style);
        }

        if (!StringUtils.isEmpty(styleName)) {
            textComponent.addStyleName(styleName);
        }
        if (!StringUtils.isEmpty(prompt)) {
            textComponent.setInputPrompt(prompt);
        }

        if (maxLengthAllowed > 0) {
            textComponent.setMaxLength(maxLengthAllowed);
        }

        if (!StringUtils.isEmpty(id)) {
            textComponent.setId(id);
        }

        if (!validators.isEmpty()) {
            validators.forEach(textComponent::addValidator);
        }

        textComponent.setNullRepresentation("");

        return textComponent;
    }

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


Question:
// runImpl sets up a localized system where a generator generates tasks and
// dispatches them to the supplied work channel.
//
// After all tasks have been written to the work channel, then is called.

func runImpl(gen func(chan<- func() error), workC chan<- WorkItem, then func()) <-chan error {
	errC := make(chan error)
	taskC := make(chan func() error)

	// Execute our generator method.
	go func() {
		defer close(taskC)
		gen(taskC)
	}()

	// Read tasks from taskC and dispatch actual work.
	go func() {
		if then != nil {
			defer then()
		}

		// Use a counter to track the number of active jobs.
		//
		// Add one implicit job for the outer task loop. This will ensure that if
		// we will never hit 0 until all of our tasks have dispatched.
		count := int32(1)
		finish := func() {
			if atomic.AddInt32(&count, -1) == 0 {
				close(errC)
			}
		}
		defer finish()

		// Dispatch the tasks in the task channel.
		for task := range taskC {
			atomic.AddInt32(&count, 1)
			workC <- WorkItem{
				F:     task,
				ErrC:  errC,
				After: finish,
			}
		}
	}()

	return errC
}

void _emitJcc(INST_CODE code, Label label, final int hint) {
        if (hint == 0) {
            emitX86(code, label);
        } else {
            emitX86(code, label, Immediate.imm(hint));
        }
    }

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


Question:
{@inheritDoc}

@see jp.co.future.uroborosql.parser.SqlTokenizer#skipWhitespace()

@Override
	public String skipWhitespace() {
		int index = skipWhitespace(position);
		token = sql.substring(position, index);
		position = index;
		return token;
	}

def new_select
      quant_list = [ :ALL, :DISTINCT ]
      select_list = [ :ASTERISK, :STRING ]

      select_tok = Tree::Select.new(basic_options)

      # handle an optional set quantifier (ALL or DISTINCT)
      if quant_list.include? peek_token.token
        select_tok.set_quantifier = read_token.token
      end

      # handle a select list (ASTERISK or search terms)
      if select_list.include? peek_token.token

        # read in all search terms from the query:
        while peek_token.token == :STRING
          select_tok.add_search_term(read_token.lexeme)
          read_token if peek_token.token == :COMMA
        end

      else
        raise SyntaxError "No valid select list given (#{error_location})"
      end

      select_tok
    end

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


Question: Adds a sampling to the calculations.

def sample( s )
      @sum += s
      @sumsq += s * s
      if @num == 0
        @min = @max = s
      else
        @min = s if @min > s
        @max = s if @max < s
      end
      @num += 1
      @last = s
    end

protected function setComponent(float $value, float $scale): float
    {
        return ($scale < 0) ? (1 - $value / -$scale) : ($value / $scale);
    }

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


Question: // GetClient loads the client by id (client_id)

func (s *storage) GetClient(id string) (osin.Client, error) {
	c, err := s.client.Get(id, metav1.GetOptions{})
	if err != nil {
		if kerrors.IsNotFound(err) {
			return nil, nil
		}
		return nil, err
	}
	return &clientWrapper{id, c}, nil
}

func (s *AcceptPortfolioShareInput) SetPortfolioId(v string) *AcceptPortfolioShareInput {
	s.PortfolioId = &v
	return s
}

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


Question:
Returns the total duration outside normal working hours, i.e.
        evenings/nights, weekends (and Bank Holidays).

def duration_outside_nwh(
            self,
            starttime: datetime.time = datetime.time(NORMAL_DAY_START_H),
            endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \
            -> datetime.timedelta:

        total = datetime.timedelta()
        for interval in self.intervals:
            total += interval.duration_outside_nwh(starttime, endtime)
        return total

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

        schedules = {}

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

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

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

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

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

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

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

        _LOGGER.info("Backup completed.")

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


Question:
Setup the default pagination params.

@return void

protected function _setupPagination()
    {
        if (!($this->_paginationEnabled = $this->_isPaginationEnabled())) {
            return;
        }

        $this->defaultLimit = $this->controller->limits[$this->action]['default'];
        $this->limits = $this->controller->limits[$this->action]['limits'];
    }

public function create(Page &$page)
    {
        $data = $page->exportData();
        $endpoint= '/admin/pages.json';
        $response = $this->request(
            $endpoint, 'POST', array(
            'page' => $data
            )
        );
        $page->setData($response['page']);
    }

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


Question: Add proxy method for equals

private void addEquals(TypeSpec.Builder classBuilder) {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("equals")
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ClassName.get(Object.class), "obj")
                .returns(boolean.class)
                .addAnnotation(Override.class)
                .addStatement("return (obj instanceof " + getRemoterInterfaceClassName() + ClassBuilder.PROXY_SUFFIX + ") && obj.hashCode() == hashCode()");
        classBuilder.addMethod(methodBuilder.build());
    }

protected void appendFacetOption(StringBuffer query, final String name, final String value) {

        query.append(" facet.").append(name).append("=").append(value);
    }

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


Question:
Calculate hash chain output hash.

@param level
hash chain level
@return hash chain result

public final ChainResult calculateOutputHash(long level) throws KSIException {
        // TODO task KSIJAVAAPI-207 If the aggregation hash chain component contains the `input data' field, hash the value part of the field
        // using the hash algorithm specified by the first octet of the `input hash' field and verify that the result of
        // hashing `input data' equals `input hash'; terminate with a consistency error if they do not match.(spec. 4.1.1.2)

        // TODO task KSIJAVAAPI-207 if current aggregation hash chain isn't the first component of the hash chain and the chain
        // contains 'input data' field then terminate with a format error. (spec 4.1.1.2)

        DataHash lastHash = inputHash;
        long currentLevel = level;
        for (AggregationChainLink aggregationChainLink : chain) {
            ChainResult step = aggregationChainLink.calculateChainStep(lastHash.getImprint(), currentLevel, aggregationAlgorithm);
            lastHash = step.getOutputHash();
            currentLevel = step.getLevel();
        }
        this.outputHash = lastHash;
        return new InMemoryChainResult(lastHash, currentLevel);
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('BulkOperationResponse');
        $visitor->setHeader('Content-Type', $generator->getMediaType('BulkOperationResponse'));
        $visitor->setStatus(Response::HTTP_OK);

        $generator->startHashElement('operations');

        foreach ($data->operations as $operationId => $operation) {
            $generator->startObjectElement($operationId, 'OperationResponse');

            $generator->startValueElement('statusCode', $operation->statusCode);
            $generator->endValueElement('statusCode');

            $generator->startHashElement('headers');

            foreach ($operation->headers as $name => $header) {
                $generator->startValueElement($name, $header[0]);
                $generator->endValueElement($name);
            }
            $generator->endHashElement('headers');

            $generator->startValueElement('content', $operation->content);
            $generator->endValueElement('content');

            $generator->endObjectElement($operationId);
        }
        $generator->endHashElement('operations');
        $generator->endObjectElement('BulkOperationResponse');
    }

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


Question: // WriteTo implements the io.WriterTo interface.

func (r *Reader) WriteTo(w io.Writer) (n int64, err error) {
	r.prevRune = -1
	if r.i >= int64(len(r.s)) {
		return 0, nil
	}
	b := r.s[r.i:]
	m, err := w.Write(b)
	if m > len(b) {
		panic("bytes.Reader.WriteTo: invalid Write count")
	}
	r.i += int64(m)
	n = int64(m)
	if m != len(b) && err == nil {
		err = io.ErrShortWrite
	}
	return
}

@Nonnull
	public static <T> LOiToLongFunction<T> oiToLongFunctionFrom(Consumer<LOiToLongFunctionBuilder<T>> buildingFunction) {
		LOiToLongFunctionBuilder builder = new LOiToLongFunctionBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

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


Question:
@param \Generated\Shared\Transfer\ComputopApiInquireResponseTransfer $computopApiResponseTransfer

@return bool

protected function isAuthLast(ComputopApiInquireResponseTransfer $computopApiResponseTransfer): bool
    {
        return $computopApiResponseTransfer->getAmountAuth() !== static::EMPTY_AMOUNT &&
            $computopApiResponseTransfer->getAmountCap() === static::EMPTY_AMOUNT &&
            $computopApiResponseTransfer->getAmountCred() === static::EMPTY_AMOUNT;
    }

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: // UpdateAge updates the age statistic based on the current time.

func (c *Cache) UpdateAge() {
	c.mu.RLock()
	defer c.mu.RUnlock()
	c.tracker.SetAge(time.Since(c.lastSnapshot))
}

protected function doSetSkillId(Lineage $model, $relatedId) {
		if ($model->getSkillId() !== $relatedId) {
			$model->setSkillId($relatedId);

			return true;
		}

		return false;
	}

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


Question:
Generates a bar
@param int $percent the percentage of the bar
@param string $label , optional, the label to display at the bar
@param array $options the HTML attributes of the bar
@return string the rendering result.

protected function renderBar($percent, $label = '', $options = [])
    {
        $options = array_merge($options, [
            'role' => 'progressbar',
            'aria-valuenow' => $percent,
            'aria-valuemin' => 0,
            'aria-valuemax' => 100
        ]);
        Html::addCssClass($options, ['widget' => 'progress-bar']);
        Html::addCssStyle($options, ['width' => $this->app->formatter->asPercent($percent / 100)], true);

        return Html::tag('div', $label, $options);
    }

protected function parseView($view)
	{
		if (is_string($view)) return [$view, null, null];

		// If the given view is an array with numeric keys, we will just assume that
		// both a "pretty" and "plain" view were provided, so we will return this
		// array as is, since must should contain both views with numeric keys.
		if (is_array($view) && isset($view[0]))
		{
			return [$view[0], $view[1], null];
		}

		// If the view is an array, but doesn't contain numeric keys, we will assume
		// the the views are being explicitly specified and will extract them via
		// named keys instead, allowing the developers to use one or the other.
		elseif (is_array($view))
		{
			return [
				array_get($view, 'html'),
				array_get($view, 'text'),
				array_get($view, 'raw'),
			];
		}

		throw new InvalidArgumentException("Invalid view.");
	}

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


Question:
Get Bearer Token

NOTE:
This middleware assumes parseAuthorizationHeader has been invoked upstream.

function getBearerToken (req, res, next) {
  // check for access token in the authorization header
  if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) {
    req.bearer = req.authorization.credentials
  }

  // check for access token in the query params
  if (req.query && req.query.access_token) {
    if (req.bearer) {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Multiple authentication methods',
        statusCode: 400
      }))
    }

    req.bearer = req.query.access_token
  }

  // check for access token in the request body
  if (req.body && req.body.access_token) {
    if (req.bearer) {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Multiple authentication methods',
        statusCode: 400
      }))
    }

    if (req.headers &&
      req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
      return next(new UnauthorizedError({
        error: 'invalid_request',
        error_description: 'Invalid content-type',
        statusCode: 400
      }))
    }

    req.bearer = req.body.access_token
  }

  next()
}

def parse_header_links(self):
        """"""
        for linktype, linkinfo in self.url_connection.links.items():
            url = linkinfo["url"]
            name = u"Link: header %s" % linktype
            self.add_url(url, name=name)
        if 'Refresh' in self.headers:
            from ..htmlutil.linkparse import refresh_re
            value = self.headers['Refresh'].strip()
            mo = refresh_re.match(value)
            if mo:
                url = unicode_safe(mo.group("url"))
                name = u"Refresh: header"
                self.add_url(url, name=name)
        if 'Content-Location' in self.headers:
            url = self.headers['Content-Location'].strip()
            name = u"Content-Location: header"
            self.add_url(url, name=name)

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


Question:
Return an array of tie break rules and an array of tie break orders (+1 for asc, -1 for desc).
 The first and most important method is always "score", the last and least important is always "name".

def tie_break_data
      # Construct the arrays and hashes to be returned.
      methods, order, data = Array.new, Hash.new, Hash.new

      # Score is always the most important.
      methods << :score
      order[:score] = -1

      # Add the configured methods.
      tie_breaks.each do |m|
        methods << m
        order[m] = m == :name ? 1 : -1
      end

      # Name is included as the last and least important tie breaker unless it's already been added.
      unless methods.include?(:name)
        methods << :name
        order[:name] = 1
      end

      # We'll need the number of rounds.
      rounds = last_round

      # Pre-calculate some scores that are not in themselves tie break scores
      # but are needed in the calculation of some of the actual tie-break scores.
      pre_calculated = Array.new
      pre_calculated << :opp_score  # sum scores where a non-played games counts 0.5
      pre_calculated.each do |m|
        data[m] = Hash.new
        @player.values.each { |p| data[m][p.num] = tie_break_score(data, m, p, rounds) }
      end

      # Now calculate all the other scores.
      methods.each do |m|
        next if pre_calculated.include?(m)
        data[m] = Hash.new
        @player.values.each { |p| data[m][p.num] = tie_break_score(data, m, p, rounds) }
      end

      # Finally, return what we calculated.
      [methods, order, data]
    end

def _do_document(self, node):
        ''''''

        self.documentOrder = _LesserElement
        for child in node.childNodes:
            if child.nodeType == Node.ELEMENT_NODE:
                self.documentOrder = _Element        # At document element
                self._do_element(child)
                self.documentOrder = _GreaterElement # After document element
            elif child.nodeType == Node.PROCESSING_INSTRUCTION_NODE:
                self._do_pi(child)
            elif child.nodeType == Node.COMMENT_NODE:
                self._do_comment(child)
            elif child.nodeType == Node.DOCUMENT_TYPE_NODE:
                pass
            else:
                raise TypeError, str(child)

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


Question: Return true if two symbols are the same.

public static function same_symbol(PHP_ParserGenerator_Symbol $a, PHP_ParserGenerator_Symbol $b)
    {
        if ($a === $b) return 1;
        if ($a->type != self::MULTITERMINAL) return 0;
        if ($b->type != self::MULTITERMINAL) return 0;
        if ($a->nsubsym != $b->nsubsym) return 0;
        for ($i = 0; $i < $a->nsubsym; $i++) {
            if ($a->subsym[$i] != $b->subsym[$i]) return 0;
        }
        return 1;
    }

static function assertLooselyIdenticalIterable(iterable $expected, $actual, bool $canonicalizeKeys = false, string $message = '')
    {
        static::assertThat($actual, static::looselyIdenticalIterable($expected, $canonicalizeKeys), $message);
    }

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


Question:
Returns a ``string`` of the winning team's name, such as 'Houston
        Astros'.

def winning_name(self):

        if self.winner == HOME:
            return self._home_name.text()
        return self._away_name.text()

public void getResult (ResultListener<T> rl)
    {
        if (_error != null) {
            rl.requestFailed(_error);
        } else if (_list == null) { // _list == null when we have a result
            rl.requestCompleted(_result);
        } else {
            _list.add(rl);
        }
    }

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


Question: Internal method to check that a given cert meets basic constraints.

private void checkBasicConstraints(X509Certificate currCert)
        throws CertPathValidatorException
    {
        String msg = "basic constraints";
        if (debug != null) {
            debug.println("---checking " + msg + "...");
            debug.println("i = " + i +
                        ", maxPathLength = " + maxPathLength);
        }

        /* check if intermediate cert */
        if (i < certPathLength) {
            // RFC5280: If certificate i is a version 3 certificate, verify
            // that the basicConstraints extension is present and that cA is
            // set to TRUE.  (If certificate i is a version 1 or version 2
            // certificate, then the application MUST either verify that
            // certificate i is a CA certificate through out-of-band means
            // or reject the certificate.  Conforming implementations may
            // choose to reject all version 1 and version 2 intermediate
            // certificates.)
            //
            // We choose to reject all version 1 and version 2 intermediate
            // certificates except that it is self issued by the trust
            // anchor in order to support key rollover or changes in
            // certificate policies.
            int pathLenConstraint = -1;
            if (currCert.getVersion() < 3) {    // version 1 or version 2
                if (i == 1) {                   // issued by a trust anchor
                    if (X509CertImpl.isSelfIssued(currCert)) {
                        pathLenConstraint = Integer.MAX_VALUE;
                    }
                }
            } else {
                pathLenConstraint = currCert.getBasicConstraints();
            }

            if (pathLenConstraint == -1) {
                throw new CertPathValidatorException
                    (msg + " check failed: this is not a CA certificate",
                     null, null, -1, PKIXReason.NOT_CA_CERT);
            }

            if (!X509CertImpl.isSelfIssued(currCert)) {
                if (maxPathLength <= 0) {
                   throw new CertPathValidatorException
                        (msg + " check failed: pathLenConstraint violated - "
                         + "this cert must be the last cert in the "
                         + "certification path", null, null, -1,
                         PKIXReason.PATH_TOO_LONG);
                }
                maxPathLength--;
            }
            if (pathLenConstraint < maxPathLength)
                maxPathLength = pathLenConstraint;
        }

        if (debug != null) {
            debug.println("after processing, maxPathLength = " + maxPathLength);
            debug.println(msg + " verified.");
        }
    }

func Convert_security_SecurityContextConstraintsList_To_v1_SecurityContextConstraintsList(in *security.SecurityContextConstraintsList, out *v1.SecurityContextConstraintsList, s conversion.Scope) error {
	return autoConvert_security_SecurityContextConstraintsList_To_v1_SecurityContextConstraintsList(in, out, s)
}

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


Question: Delete a portlet entity, removes it from the request, session and persistent stores

protected void deletePortletEntity(
            HttpServletRequest request, IPortletEntity portletEntity, boolean cacheOnly) {
        final IPortletEntityId portletEntityId = portletEntity.getPortletEntityId();

        // Remove from request cache
        final PortletEntityCache<IPortletEntity> portletEntityMap =
                this.getPortletEntityMap(request);
        portletEntityMap.removeEntity(portletEntityId);

        // Remove from session cache
        final PortletEntityCache<PortletEntityData> portletEntityDataMap =
                this.getPortletEntityDataMap(request);
        portletEntityDataMap.removeEntity(portletEntityId);

        if (!cacheOnly && portletEntity instanceof PersistentPortletEntityWrapper) {
            final IPortletEntity persistentEntity =
                    ((PersistentPortletEntityWrapper) portletEntity).getPersistentEntity();

            try {
                this.portletEntityDao.deletePortletEntity(persistentEntity);
            } catch (HibernateOptimisticLockingFailureException e) {
                this.logger.warn(
                        "This persistent portlet has already been deleted: "
                                + persistentEntity
                                + ", trying to find and delete by layout node and user.");
                final IPortletEntity existingPersistentEntity =
                        this.portletEntityDao.getPortletEntity(
                                persistentEntity.getLayoutNodeId(), persistentEntity.getUserId());
                if (existingPersistentEntity != null) {
                    this.portletEntityDao.deletePortletEntity(existingPersistentEntity);
                }
            }
        }
    }

protected final PrcSeSrvSpecEmbFlDel<RS>
    lazyGetPrcSeSrvSpecEmbFlDel(
      final Map<String, Object> pAddParam) throws Exception {
    String beanName = PrcSeSrvSpecEmbFlDel.class.getSimpleName();
    @SuppressWarnings("unchecked")
    PrcSeSrvSpecEmbFlDel<RS> proc = (PrcSeSrvSpecEmbFlDel<RS>)
      this.processorsMap.get(beanName);
    if (proc == null) {
      proc = new PrcSeSrvSpecEmbFlDel<RS>();
      proc.setSrvOrm(getSrvOrm());
      proc.setFindSeSeller(getFindSeSeller());
      proc.setWebAppPath(getWebAppPath());
      proc.setUploadDirectory(getUploadDirectory());
      //assigning fully initialized object:
      this.processorsMap.put(beanName, proc);
      this.logger.info(null, FctBnSeSelEntityProcs.class,
        beanName + " has been created.");
    }
    return proc;
  }

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


Question:
Returns the total count of dbdeploy sql files in self::CACHE_DELTAS_PATH
@return int

private static function getTotalDataFile()
    {
        $docRoot = self::docRoot();
        $dbDeployPath = $docRoot . '/dbdeploy/data/';
        if (!file_exists($dbDeployPath)) {
            return 0;
        }
        $files = glob($dbDeployPath . '*.sql');

        return count($files);
    }

public function execute() {
        global $CFG;

        // The directories hosting the candidate stale temp files eventually are $CFG->tempdir and $CFG->backuptempdir.

        // Do the job on each of the directories above.
        // Let's start with $CFG->tempdir.
        $this->execute_on($CFG->tempdir);

        // Run on $CFG->backuptempdir too, if different from the default one, '$CFG->tempdir/backup'.
        if (realpath(dirname($CFG->backuptempdir)) !== realpath($CFG->tempdir)) {
            // The $CFG->backuptempdir setting is different from the default '$CFG->tempdir/backup'.
            $this->execute_on($CFG->backuptempdir);
        }
    }

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


Question:
Add the created action message for the key 'success.delete_doc_from_index' with parameters.
<pre>
message: Started a process to delete the document from index.
</pre>
@param property The property name for the message. (NotNull)
@return this. (NotNull)

public FessMessages addSuccessDeleteDocFromIndex(String property) {
        assertPropertyNotNull(property);
        add(property, new UserMessage(SUCCESS_delete_doc_from_index));
        return this;
    }

public C4Document update(byte[] body, int flags) throws LiteCoreException {
        return new C4Document(update(handle, body, flags));
    }

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


Question:
Calculate the weight of the tag

@param \Jb\Bundle\TagCloudBundle\Model\TagCloud $cloud

public function process(\Jb\Bundle\TagCloudBundle\Model\TagCloud $cloud)
    {
        foreach ($cloud as $tag) {
            $this->setPercentSize($tag, $cloud->getMax());
        }
    }

public void configure(OStorage iStorage, int iId, String iClusterName, String iLocation, int iDataSegmentId,
      Object... iParameters) throws IOException {
    id = iId;
    name = iClusterName;
    dataSegmentId = iDataSegmentId;
  }

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


Question:
Gets the filename from the given url object.

@param url
the url
@return the filename
@throws UnsupportedEncodingException
the unsupported encoding exception

public static String getFilename(final URL url) throws UnsupportedEncodingException
	{
		if (isJar(url) || isEar(url))
		{
			String fileName = URLDecoder.decode(url.getFile(), "UTF-8");
			fileName = fileName.substring(5, fileName.indexOf("!"));
			return fileName;
		}
		return URLDecoder.decode(url.getFile(), "UTF-8");
	}

private static void renameTmpFile(FileSystem hdfs, String targetTmpPath, String tmpSuffix)
    {
        String basePath = extractBasePath(targetTmpPath, tmpSuffix);

        boolean isFileExists = true;

        try
        {
            isFileExists = hdfs.exists(new Path(basePath));
        }
        catch (IOException ioex)
        {
            String logFormat = "Failed to search target file exists. Skip file rename. : TargetUri={0}";
            String logMessage = MessageFormat.format(logFormat, basePath);
            logger.warn(logMessage, ioex);
            return;
        }

        if (isFileExists)
        {
            String logFormat = "File exists renamed target. Skip file rename. : BeforeUri={0} , AfterUri={1}";
            String logMessage = MessageFormat.format(logFormat, targetTmpPath, basePath);
            logger.warn(logMessage);
        }
        else
        {
            try
            {
                hdfs.rename(new Path(targetTmpPath), new Path(basePath));
            }
            catch (IOException ioex)
            {
                String logFormat = "Failed to HDFS file rename. Skip rename file and continue preprocess. : BeforeUri={0} , AfterUri={1}";
                String logMessage = MessageFormat.format(logFormat, targetTmpPath, basePath);
                logger.warn(logMessage, ioex);
            }
        }
    }

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