Question: // Remove stops the service in the Supervisor tree and remove from it.

func (s *Supervisor) Remove(name string) {
	s.prepare()

	s.mu.Lock()
	defer s.mu.Unlock()
	if _, ok := s.services[name]; !ok {
		return
	}

	delete(s.services, name)

	for i, n := range s.svcorder {
		if name == n {
			s.svcorder = append(s.svcorder[:i], s.svcorder[i+1:]...)
			break
		}
	}

	if c, ok := s.terminations[name]; ok {
		delete(s.terminations, name)
		c()
	}

	if _, ok := s.cancelations[name]; ok {
		delete(s.cancelations, name)
	}
}

protected void onRemoved() {
        List<AnalyzerChangeListener> listeners = getAllListeners();
        for (AnalyzerChangeListener listener : listeners) {
            listener.onRemove(this);
        }
    }

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


Question:
getAllProjects.

@return a {@link java.util.Vector} object.

public Vector<Object> getAllProjects()
    {
        try
        {
            List<Project> projects = service.getAllProjects();

            log.debug( "Retrieved All Projects number: " + projects.size() );
            return XmlRpcDataMarshaller.toXmlRpcProjectsParameters( projects );
        }
        catch (Exception e)
        {
            return errorAsVector( e, RETRIEVE_PROJECTS );
        }
    }

protected OutputsModel toOutputsModel(Output[] outputs, KnowledgeNamespace knowledgeNamespace) {
        OutputsModel outputsModel = null;
        if (outputs != null) {
            for (Output output : outputs) {
                if (output != null) {
                    OutputModel outputModel = new V1OutputModel(knowledgeNamespace.uri());
                    String from = output.from();
                    if (!UNDEFINED.equals(from)) {
                        outputModel.setFrom(from);
                    }
                    String to = output.to();
                    if (!UNDEFINED.equals(to)) {
                        outputModel.setTo(to);
                    }
                    if (outputsModel == null) {
                        outputsModel = new V1OutputsModel(knowledgeNamespace.uri());
                    }
                    outputsModel.addOutput(outputModel);
                }
            }
        }
        return outputsModel;
    }

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


Question:
Returns formatted voucher discount

@deprecated in v4.8/5.1 on 2013-10-14; for formatting use oxPrice smarty plugin

@return string | bool

public function getFVoucherDiscountValue()
    {
        if ($oVoucherDiscount = $this->getVoucherDiscount()) {
            if ($oVoucherDiscount->getBruttoPrice()) {
                return \OxidEsales\Eshop\Core\Registry::getLang()->formatCurrency($oVoucherDiscount->getBruttoPrice(), $this->getBasketCurrency());
            }
        }

        return false;
    }

def query_coupon(self, coupon_id, user_id,
                     op_user_id=None, device_info=None):

        data = {
            'coupon_id': coupon_id,
            'openid': user_id,
            'appid': self.appid,
            'op_user_id': op_user_id,
            'device_info': device_info,
            'version': '1.0',
            'type': 'XML',
        }
        return self._post('promotion/query_coupon', data=data)

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


Question:
Note that if file starts with 'classpath:' the resource is looked
up on the classpath instead.

public static Configuration load(String file)
    throws IOException, SAXException {
    ConfigurationImpl cfg = new ConfigurationImpl();

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(new ConfigHandler(cfg, file));
    if (file.startsWith("classpath:")) {
      String resource = file.substring("classpath:".length());
      ClassLoader cloader = Thread.currentThread().getContextClassLoader();
      InputStream istream = cloader.getResourceAsStream(resource);
      parser.parse(new InputSource(istream));
    } else
      parser.parse(file);

    return cfg;
  }

public java.lang.String getStaticFile() {
    java.lang.Object ref = staticFile_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      staticFile_ = s;
      return s;
    }
  }

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


protected void hookPreparedMessage(Postcard postcard, final SMailPostingMessage message) {
        if (SMailCallbackContext.isExistPreparedMessageHookOnThread()) {
            final SMailCallbackContext context = SMailCallbackContext.getCallbackContextOnThread();
            final SMailPreparedMessageHook hook = context.getPreparedMessageHook();
            hook.hookPreparedMessage(postcard, message);
        }
    }

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


Question: Set various flags to control video output behavior.

function( value ) {
		this.output.setGrayscale( value & 0x1 );
		this.output.setIntensity( value & 0x20, value & 0x40, value & 0x80 );

		this.sprites.toggle( value & 0x10 );
		this.sprites.toggleLeft( value & 0x4 );

		this.background.toggle( value & 0x8 );
		this.background.toggleLeft( value & 0x2 );

		this.enabled = ( this.sprites.enabled || this.background.enabled );
	}

def _notify_media_transport_available(self, path, transport):

        self.source = BTAudioSource(dev_path=path)
        self.state = self.source.State
        self.source.add_signal_receiver(self._property_change_event_handler,
                                        BTAudioSource.SIGNAL_PROPERTY_CHANGED,  # noqa
                                        transport)

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


Question:
Converts a list of tasks to a list of string representations.

  Args:
    tasks: A list of the tasks to convert.
  Returns:
    A list of string formatted tasks.

def format_tasks(tasks):

  return ['%d : %s (%s)' % (task.key.id(),
                            task.description,
                            ('done' if task.done
                             else 'created %s' % task.created))
          for task in tasks]

func TextProducer() Producer {
	return ProducerFunc(func(writer io.Writer, data interface{}) error {
		if writer == nil {
			return errors.New("TextProducer requires a writer") // early exit
		}

		if data == nil {
			return errors.New("no data given to produce text from")
		}

		if tm, ok := data.(encoding.TextMarshaler); ok {
			txt, err := tm.MarshalText()
			if err != nil {
				return fmt.Errorf("text producer: %v", err)
			}
			_, err = writer.Write(txt)
			return err
		}

		if str, ok := data.(error); ok {
			_, err := writer.Write([]byte(str.Error()))
			return err
		}

		if str, ok := data.(fmt.Stringer); ok {
			_, err := writer.Write([]byte(str.String()))
			return err
		}

		v := reflect.Indirect(reflect.ValueOf(data))
		if t := v.Type(); t.Kind() == reflect.Struct || t.Kind() == reflect.Slice {
			b, err := swag.WriteJSON(data)
			if err != nil {
				return err
			}
			_, err = writer.Write(b)
			return err
		}
		if v.Kind() != reflect.String {
			return fmt.Errorf("%T is not a supported type by the TextProducer", data)
		}

		_, err := writer.Write([]byte(v.String()))
		return err
	})
}

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


Question:
Set up the doc header properly here

@param ViewInterface $view
@return void

protected function initializeView(ViewInterface $view)
    {
        parent::initializeView($view);

        /* @var ModuleTemplate $module */ // holds the state of chosen tab
        $module = GeneralUtility::makeInstance(ModuleTemplate::class);
        $coreOptimizationTabs = $module->getDynamicTabMenu([], 'coreOptimization');
        $this->view->assign('tabs', $coreOptimizationTabs);
    }

func (v *printVisitor) VisitComment(node *CommentStatement) interface{} {
	v.line("{{! '" + node.Value + "' }}")

	return nil
}

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


Question:
Creates new migration for the given tables.
@param string $table Table names separated by commas.
@return int
@throws DbException

public function actionCreate(string $table): int
    {
        $tables = [$table];
        if (strpos($table, ',') !== false) {
            $tables = explode(',', $table);
        }

        $migrationsGenerated = 0;
        foreach ($tables as $name) {
            $this->stdout(" > Generating create migration for table '{$name}' ...", Console::FG_YELLOW);

            $className = 'm' . gmdate('ymd_His') . '_create_table_' . $name;
            $file = Yii::getAlias($this->workingPath . DIRECTORY_SEPARATOR . $className . '.php');

            $generator = new Generator([
                'db' => $this->db,
                'view' => $this->view,
                'useTablePrefix' => $this->useTablePrefix,
                'templateFile' => $this->templateFile,
                'tableName' => $name,
                'className' => $className,
                'namespace' => $this->migrationNamespace,
                'generalSchema' => $this->generalSchema,
                'tableOptionsInit' => $this->tableOptionsInit,
                'tableOptions' => $this->tableOptions,
            ]);

            if ($generator->tableSchema === null) {
                $this->stdout("ERROR!\n > Table '{$name}' does not exist!\n\n", Console::FG_RED);

                return ExitCode::DATAERR;
            }

            if ($this->generateFile($file, $generator->generateMigration()) === false) {
                $this->stdout("ERROR!\n > Migration file for table '{$name}' can not be generated!\n\n", Console::FG_RED);

                return ExitCode::SOFTWARE;
            }

            $migrationsGenerated++;

            $this->stdout("DONE!\n", Console::FG_GREEN);
            $this->stdout(" > Saved as '{$file}'\n");

            if ($this->fixHistory) {
                if ($this->db->schema->getTableSchema($this->migrationTable, true) === null) {
                    $this->createMigrationHistoryTable();
                }

                $this->addMigrationHistory($className, $this->migrationNamespace);
            }

            $this->stdout("\n");
        }

        if ($migrationsGenerated) {
            $this->stdout(" Generated $migrationsGenerated file(s).\n", Console::FG_YELLOW);
            $this->stdout(" (!) Remember to verify files before applying migration.\n\n", Console::FG_YELLOW);
        } else {
            $this->stdout(" No files generated.\n\n", Console::FG_YELLOW);
        }

        return ExitCode::OK;
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question:
Template variable getter. Returns media files of current product.

@return array

public function getMediaFiles()
    {
        if ($this->_aMediaFiles === null) {
            $aMediaFiles = $this->getProduct()->getMediaUrls();
            $this->_aMediaFiles = count($aMediaFiles) ? $aMediaFiles : false;
        }

        return $this->_aMediaFiles;
    }

public static function renderTemplate($file, $args = [])
    {
        if (!empty($file)) {
            self::setFile($file);
            extract($args, EXTR_SKIP);
            if (file_exists(self::$file)) {
                ob_start();
                require_once self::$file;
            } else {
                throw new \Exception("Sorry, view file {$file} not exists", 404);
            }
        } else {
            throw new \Exception('Sorry, file much be provided', 404);
        }
    }

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


Question: // MarshalJSON returns a JSON representation of Column.

func (rr *RoutingRule) MarshalJSON() ([]byte, error) {
	if rr.Error != nil {
		return json.Marshal(rr.Error.Error())
	}
	tables := make([]string, 0, len(rr.Tables))
	for _, t := range rr.Tables {
		tables = append(tables, t.Keyspace.Name+"."+t.Name.String())
	}
	return json.Marshal(tables)
}

public static MappingColumn getMappingColumn(final Class<?> entityType, final String camelColumnName) {
		return getMappingColumn(entityType, SqlKind.NONE, camelColumnName);
	}

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


Question:
log an informational message
@param $message

public function logInfo($message, $object = null)
    {
        $this->doLog(LogHelper::LOG_LEVEL_INFO, $message, $object);
    }

protected String getInfoMessage() {
		try {
			return (String) APICallContext.getCallContext().getCurrentSession().getAttribute("infoMessage");
		}catch(Exception any){
			return null;
		}
	}

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


Question:
Calls smart_assert, but creates its own assertion closure using
        the expected and provided values with the '!=' operator

def assert_not_equal(self, actual_val, unexpected_val, failure_message='Expected values to differ: "{}" and "{}"'):

        assertion = lambda: unexpected_val != actual_val
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_val))

def conditions_hash_validations
      conditions.each do |comparator, mappings|
        errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
        errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
      end
    end

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


Question: For UTF-8, a replacement character for each buffered byte of a (partial) character needs to be added to the output.

function utf8End(buf) {
  var r = buf && buf.length ? this.write(buf) : '';
  if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
  return r;
}

protected function buildLocator()
    {
        $this
            ->resetLocatorBuffer()
            ->getReferenceBuffer()
            ->reset();
        $state = self::STATE_POINTER_PART;
        while (true) {
            switch ($state) {
                case self::STATE_POINTER_PART:
                    // Expecting part of a pointer or end of text.
                    $state = $this->processPointerPartState();
                    break;

                case self::STATE_REFERENCE_PART:
                    // Expecting reference token part.
                    $state = $this->processReferencePartState();
                    break;

                case self::STATE_FINISH:
                    // End of text is found, parsing is finished successfully.
                    break 2;

                default:
                    throw new DomainException("Invalid parser state: {$state}");
            }
        }
        $this->locator = $this->getLocatorBuffer();
        return $this
            ->resetLocatorBuffer();
    }

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


Question:
人性化相对时间
@param int $sTime 目标时间戳
@param string $format 时间格式
@return string

public static function friendlyDate(int $sTime = 0, string $format = 'Y-m-d H:i'): string {
		$dTime = time() - $sTime;
		$state = $dTime > 0 ? '前' : '后';
		$dTime = abs($dTime);
		if ($dTime < 60) {
			return $dTime . ' 秒' . $state;
		}
		elseif ($dTime < 3600) {
			return intval($dTime / 60) . ' 分钟' . $state;
		}
		elseif ($dTime < 3600 * 24) {
			return intval($dTime / 3600) . ' 小时' . $state;
		}
		elseif ($dTime < 3600 * 24 * 7) {
			return intval($dTime / (3600 * 24)) . ' 天' . $state;
		}
		elseif ($dTime < 3600 * 24 * 30) {
			return intval($dTime / (3600 * 24 * 7)) . ' 周' . $state;
		}
		elseif ($dTime < 3600 * 24 * 30 * 12) {
			return intval($dTime / (3600 * 24 * 30)) . ' 月' . $state;
		}
		else
			return date($format, $sTime);
	}

def _wrap_callback_parse_time_info(subscription, on_data, message):

    if message.type == message.REPLY:
        time_response = web_pb2.TimeSubscriptionResponse()
        time_response.ParseFromString(message.reply.data)
        time = parse_isostring(time_response.timeInfo.currentTimeUTC)
        #pylint: disable=protected-access
        subscription._process(time)
        if on_data:
            on_data(time)
    elif message.type == message.DATA:
        if message.data.type == yamcs_pb2.TIME_INFO:
            time_message = getattr(message.data, 'timeInfo')
            time = parse_isostring(time_message.currentTimeUTC)
            #pylint: disable=protected-access
            subscription._process(time)
            if on_data:
                on_data(time)

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


Question: Use this API to fetch autoscalepolicy_binding resource of given name .

public static autoscalepolicy_binding get(nitro_service service, String name) throws Exception{
		autoscalepolicy_binding obj = new autoscalepolicy_binding();
		obj.set_name(name);
		autoscalepolicy_binding response = (autoscalepolicy_binding) obj.get_resource(service);
		return response;
	}

def _get_provisioning_state(self, response):

        if self._is_empty(response):
            return None
        body = response.json()
        return body.get("properties", {}).get("provisioningState")

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


Question: Sends the request and initializes the response.

private void getConnInput() throws IOException
  {
    if (_didGet)
      return;

    try {
      getConnInputImpl();
    } catch (IOException e) {
      _isKeepalive = false;
      throw e;
    } catch (RuntimeException e) {
      _isKeepalive = false;
      throw e;
    }
  }

public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
		this.doProcess(req, res);
	}

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


Question:
Create snapshot of servers groups

@param expirationDays expiration days (must be between 1 and 10)
@param groups groups references list
@return OperationFuture wrapper for Server list

public OperationFuture<List<Server>> createSnapshot(Integer expirationDays, Group... groups) {
        return serverService().createSnapshot(
            expirationDays,
            getServerSearchCriteria(groups)
        );
    }

def _perform_request(self, request, parser=None, parser_args=None, operation_context=None):
        '''

        '''
        operation_context = operation_context or _OperationContext()
        retry_context = RetryContext()
        retry_context.is_emulated = self.is_emulated

        # Apply the appropriate host based on the location mode
        self._apply_host(request, operation_context, retry_context)

        # Apply common settings to the request
        _update_request(request, self._X_MS_VERSION, self._USER_AGENT_STRING)
        client_request_id_prefix = str.format("Client-Request-ID={0}", request.headers['x-ms-client-request-id'])

        while True:
            try:
                try:
                    # Execute the request callback
                    if self.request_callback:
                        self.request_callback(request)

                    # Add date and auth after the callback so date doesn't get too old and
                    # authentication is still correct if signed headers are added in the request
                    # callback. This also ensures retry policies with long back offs
                    # will work as it resets the time sensitive headers.
                    _add_date_header(request)
                    self.authentication.sign_request(request)

                    # Set the request context
                    retry_context.request = request

                    # Log the request before it goes out
                    logger.info("%s Outgoing request: Method=%s, Path=%s, Query=%s, Headers=%s.",
                                client_request_id_prefix,
                                request.method,
                                request.path,
                                request.query,
                                str(request.headers).replace('\n', ''))

                    # Perform the request
                    response = self._httpclient.perform_request(request)

                    # Execute the response callback
                    if self.response_callback:
                        self.response_callback(response)

                    # Set the response context
                    retry_context.response = response

                    # Log the response when it comes back
                    logger.info("%s Receiving Response: "
                                "%s, HTTP Status Code=%s, Message=%s, Headers=%s.",
                                client_request_id_prefix,
                                self.extract_date_and_request_id(retry_context),
                                response.status,
                                response.message,
                                str(request.headers).replace('\n', ''))

                    # Parse and wrap HTTP errors in AzureHttpError which inherits from AzureException
                    if response.status >= 300:
                        # This exception will be caught by the general error handler
                        # and raised as an azure http exception
                        _http_error_handler(
                            HTTPError(response.status, response.message, response.headers, response.body))

                    # Parse the response
                    if parser:
                        if parser_args:
                            args = [response]
                            args.extend(parser_args)
                            return parser(*args)
                        else:
                            return parser(response)
                    else:
                        return
                except AzureException as ex:
                    retry_context.exception = ex
                    raise ex
                except Exception as ex:
                    retry_context.exception = ex
                    if sys.version_info >= (3,):
                        # Automatic chaining in Python 3 means we keep the trace
                        raise AzureException(ex.args[0])
                    else:
                        # There isn't a good solution in 2 for keeping the stack trace
                        # in general, or that will not result in an error in 3
                        # However, we can keep the previous error type and message
                        # TODO: In the future we will log the trace
                        msg = ""
                        if len(ex.args) > 0:
                            msg = ex.args[0]
                        raise AzureException('{}: {}'.format(ex.__class__.__name__, msg))

            except AzureException as ex:
                # only parse the strings used for logging if logging is at least enabled for CRITICAL
                if logger.isEnabledFor(logging.CRITICAL):
                    exception_str_in_one_line = str(ex).replace('\n', '')
                    status_code = retry_context.response.status if retry_context.response is not None else 'Unknown'
                    timestamp_and_request_id = self.extract_date_and_request_id(retry_context)

                logger.info("%s Operation failed: checking if the operation should be retried. "
                            "Current retry count=%s, %s, HTTP status code=%s, Exception=%s.",
                            client_request_id_prefix,
                            retry_context.count if hasattr(retry_context, 'count') else 0,
                            timestamp_and_request_id,
                            status_code,
                            exception_str_in_one_line)

                # Decryption failures (invalid objects, invalid algorithms, data unencrypted in strict mode, etc)
                # will not be resolved with retries.
                if str(ex) == _ERROR_DECRYPTION_FAILURE:
                    logger.error("%s Encountered decryption failure: this cannot be retried. "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex

                # Determine whether a retry should be performed and if so, how
                # long to wait before performing retry.
                retry_interval = self.retry(retry_context)
                if retry_interval is not None:
                    # Execute the callback
                    if self.retry_callback:
                        self.retry_callback(retry_context)

                    logger.info(
                        "%s Retry policy is allowing a retry: Retry count=%s, Interval=%s.",
                        client_request_id_prefix,
                        retry_context.count,
                        retry_interval)

                    # Sleep for the desired retry interval
                    sleep(retry_interval)
                else:
                    logger.error("%s Retry policy did not allow for a retry: "
                                 "%s, HTTP status code=%s, Exception=%s.",
                                 client_request_id_prefix,
                                 timestamp_and_request_id,
                                 status_code,
                                 exception_str_in_one_line)
                    raise ex
            finally:
                # If this is a location locked operation and the location is not set,
                # this is the first request of that operation. Set the location to
                # be used for subsequent requests in the operation.
                if operation_context.location_lock and not operation_context.host_location:
                    # note: to cover the emulator scenario, the host_location is grabbed
                    # from request.host_locations(which includes the dev account name)
                    # instead of request.host(which at this point no longer includes the dev account name)
                    operation_context.host_location = {retry_context.location_mode: request.host_locations[retry_context.location_mode]}

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


Question: URL that can be used to view the color map at colorbrewer2.org.

def colorbrewer2_url(self):

        url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}'
        return url.format(self.type.lower(), self.name, self.number)

def _create_netmap_config(self):

        netmap_path = os.path.join(self.working_dir, "NETMAP")
        try:
            with open(netmap_path, "w", encoding="utf-8") as f:
                for bay in range(0, 16):
                    for unit in range(0, 4):
                        f.write("{ubridge_id}:{bay}/{unit}{iou_id:>5d}:{bay}/{unit}\n".format(ubridge_id=str(self.application_id + 512),
                                                                                bay=bay,
                                                                                unit=unit,
                                                                                iou_id=self.application_id))
            log.info("IOU {name} [id={id}]: NETMAP file created".format(name=self._name,
                                                                        id=self._id))
        except OSError as e:
            raise IOUError("Could not create {}: {}".format(netmap_path, e))

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


Question: // CallOneway implements middleware.OnewayOutbound.

func (m *Middleware) CallOneway(ctx context.Context, req *transport.Request, out transport.OnewayOutbound) (transport.Ack, error) {
	call := m.graph.begin(ctx, transport.Oneway, _directionOutbound, req)
	ack, err := out.CallOneway(ctx, req)
	call.End(err)
	return ack, err
}

public static GrayF32 median(GrayF32 input, @Nullable GrayF32 output, int radius) {

		if( radius <= 0 )
			throw new IllegalArgumentException("Radius must be > 0");

		output = InputSanityCheck.checkDeclare(input,output);

		boolean processed = BOverrideBlurImageOps.invokeNativeMedian(input, output, radius);

		if( !processed ) {
			ImplMedianSortNaive.process(input, output, radius, null);
		}
		return output;
	}

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


Question: // newHTTPGetter constructs a valid http/https client as Getter

func newHTTPGetter(URL, CertFile, KeyFile, CAFile string) (Getter, error) {
	return NewHTTPGetter(URL, CertFile, KeyFile, CAFile)
}

public final TcpClient host(String host) {
		Objects.requireNonNull(host, "host");
		return bootstrap(b -> TcpUtils.updateHost(b, host));
	}

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


Question: // recoverSubscriptions recovers subscriptions state for this store.

func (ss *FileSubStore) recoverSubscriptions() error {
	var err error
	var recType recordType

	recSize := 0
	offset := int64(4)

	// Create a buffered reader to speed-up recovery
	br := bufio.NewReaderSize(ss.file.handle, defaultBufSize)

	for {
		ss.tmpSubBuf, recSize, recType, err = readRecord(br, ss.tmpSubBuf, true, ss.crcTable, ss.opts.DoCRC)
		if err != nil {
			switch err {
			case io.EOF:
				// We are done, reset err
				err = nil
			case errNeedRewind:
				err = ss.fm.truncateFile(ss.file, offset)
			default:
				err = ss.fstore.handleUnexpectedEOF(err, ss.file, offset, true)
			}
			if err == nil {
				break
			}
			return err
		}
		readBytes := int64(recSize + recordHeaderSize)
		offset += readBytes
		ss.fileSize += readBytes
		// Based on record type...
		switch recType {
		case subRecNew:
			newSub := &spb.SubState{}
			if err := newSub.Unmarshal(ss.tmpSubBuf[:recSize]); err != nil {
				return err
			}
			sub := &subscription{
				sub:    newSub,
				seqnos: make(map[uint64]struct{}),
			}
			ss.subs[newSub.ID] = sub
			// Keep track of max subscription ID found.
			if newSub.ID > ss.maxSubID {
				ss.maxSubID = newSub.ID
			}
			ss.numRecs++
		case subRecUpdate:
			modifiedSub := &spb.SubState{}
			if err := modifiedSub.Unmarshal(ss.tmpSubBuf[:recSize]); err != nil {
				return err
			}
			// Search if the create has been recovered.
			subi, exists := ss.subs[modifiedSub.ID]
			if exists {
				sub := subi.(*subscription)
				sub.sub = modifiedSub
				// An update means that the previous version is free space.
				ss.delRecs++
			} else {
				sub := &subscription{
					sub:    modifiedSub,
					seqnos: make(map[uint64]struct{}),
				}
				ss.subs[modifiedSub.ID] = sub
			}
			// Keep track of max subscription ID found.
			if modifiedSub.ID > ss.maxSubID {
				ss.maxSubID = modifiedSub.ID
			}
			ss.numRecs++
		case subRecDel:
			delSub := spb.SubStateDelete{}
			if err := delSub.Unmarshal(ss.tmpSubBuf[:recSize]); err != nil {
				return err
			}
			if si, exists := ss.subs[delSub.ID]; exists {
				s := si.(*subscription)
				delete(ss.subs, delSub.ID)
				// Delete and count all non-ack'ed messages free space.
				ss.delRecs++
				ss.delRecs += len(s.seqnos)
			}
			// Keep track of max subscription ID found.
			if delSub.ID > ss.maxSubID {
				ss.maxSubID = delSub.ID
			}
		case subRecMsg:
			updateSub := spb.SubStateUpdate{}
			if err := updateSub.Unmarshal(ss.tmpSubBuf[:recSize]); err != nil {
				return err
			}
			if subi, exists := ss.subs[updateSub.ID]; exists {
				sub := subi.(*subscription)
				seqno := updateSub.Seqno
				// Same seqno/ack can appear several times for the same sub.
				// See queue subscribers redelivery.
				if seqno > sub.sub.LastSent {
					sub.sub.LastSent = seqno
				}
				sub.seqnos[seqno] = struct{}{}
				ss.numRecs++
			}
		case subRecAck:
			updateSub := spb.SubStateUpdate{}
			if err := updateSub.Unmarshal(ss.tmpSubBuf[:recSize]); err != nil {
				return err
			}
			if subi, exists := ss.subs[updateSub.ID]; exists {
				sub := subi.(*subscription)
				delete(sub.seqnos, updateSub.Seqno)
				// A message is ack'ed
				ss.delRecs++
			}
		default:
			return fmt.Errorf("unexpected record type: %v", recType)
		}
	}
	return nil
}

def get_recent_linkbacks(number=5,
                         template='zinnia/tags/linkbacks_recent.html'):

    entry_published_pks = map(smart_text,
                              Entry.published.values_list('id', flat=True))
    content_type = ContentType.objects.get_for_model(Entry)

    linkbacks = get_comment_model().objects.filter(
        content_type=content_type,
        object_pk__in=entry_published_pks,
        flags__flag__in=[PINGBACK, TRACKBACK],
        is_public=True).order_by('-pk')[:number]

    linkbacks = linkbacks.prefetch_related('content_object')

    return {'template': template,
            'linkbacks': linkbacks}

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


Question:
Create a form week field.

@param  string  $name
@param  string  $value
@param  array   $options
@return string

public function week($name, $value = null, $options = array())
    {
		return $this->input('week', $name, $value, $options);
    }

public function format(ParameterBag $trackingParameters)
    {
        $cu = null;

        if (
            $trackingParameters->has('c')
            && $trackingParameters->has('u')
        ) {
            $cu = sprintf(
                '%s~%s',
                $trackingParameters->get('c'),
                $trackingParameters->get('u')
            );
        }

        return [
            'cu' => $cu,
        ];
    }

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


Question:
LinksCollectorTrait::createLink

@param string      $label
@param string|null $href

public function createLink($label, $href = null)
    {
        $link = new Link($label, $href);

        if ( ! $this->links instanceof ArrayIterator) {
            $this->links = new ArrayIterator();
        }

        $this->links->push($link);
    }

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:
Generate file path by template

@param string $attribute The attribute name
@param ActiveRecord $file The file model
@return string The file path

private function templatePath($attribute, $file = null)
    {
        $value = $this->owner->{$attribute};

        $saveFilePath = $this->fileOption($attribute, 'saveFilePathInAttribute');
        $isFilledPath = $saveFilePath && !empty($value);

        $saveFileId = $this->fileOption($attribute, 'saveFileIdInAttribute');
        $isFilledId = $saveFileId && is_numeric($value) && $value;

        if (($isFilledPath || $isFilledId) && $file === null) {
            $file = $this->file($attribute);
        }

        if ($file !== null) {
            $handlerTemplatePath = $this->fileOption($attribute, 'templatePath');
            return $handlerTemplatePath($file);
        }
        return $value;
    }

def iter_doc_filepaths(self, **kwargs):

        for shard in self._shards:
            for doc_id, blob in shard.iter_doc_filepaths(**kwargs):
                yield doc_id, blob

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


Question: public $params = null;

public function init()
    {
        if (!$this->data instanceof CModel) {
            throw new CException('Property "data" should be of CModel class.');
        }

        //set bootstrap css
        if(yii::app()->editable->form === EditableConfig::FORM_BOOTSTRAP) {
            $this->htmlOptions = array('class'=> 'table table-bordered table-striped table-hover');
            //disable loading Yii's css for bootstrap
            $this->cssFile = false;
        }

        parent::init();
    }

private function getJobs()
    {
        if ($this->hasParameter('profile')) {
            $this->fetchJobs($this->getParameter('profile'));

            return;
        }

        $this->buildJobs([$this->getParameter('job')]);
    }

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


Question:
Returns a new {@link Service} decorator that logs {@link Request}s and {@link Response}s at the given
{@link LogLevel}.

@deprecated Use {@link LoggingServiceBuilder}.

@Deprecated
    public static <I extends Request, O extends Response>
    Function<Service<I, O>, LoggingService<I, O>> newDecorator(LogLevel level) {
        return delegate -> new LoggingService<>(delegate, level);
    }

public function onActivityDetails(Model $model)
    {
        $this->onActivity();
        Breadcrumbs::register('logger-activity-details', function($breadcrumbs) use($model) {
            $breadcrumbs->parent('logger-activity');
            $breadcrumbs->push('Show Activity Log #' . $model->id, handles('antares::logger/activity/show/' . $model->id));
        });

        view()->share('breadcrumbs', Breadcrumbs::render('logger-activity-details'));
    }

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


Question: Watch dependencies for changes and invalidate the cache when needed

function() {
              bundle.browserify.pipeline.get('deps').push(through.obj(function(row, enc, next) {
                var file = row.expose ? bundle.browserify._expose[row.id] : row.file;

                if (self.cache) {
                  bundle.browserifyOptions.cache[file] = {
                    source: row.source,
                    deps: xtend({}, row.deps)
                  };
                }

                this.push(row);
                next();
              }));
            }

func (c *CordonHelper) UpdateIfRequired(desired bool) bool {
	c.desired = desired
	if c.node.Spec.Unschedulable == c.desired {
		return false
	}
	return true
}

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


Question:
Transforms a BCNumber into unsigned char*.

@param string $dec BCNumber
@param string

private static function bcdecuc($dec) {
        $last = bcmod($dec, 256);
        $remain = bcdiv(bcsub($dec, $last), 256, 0);

        if ($remain == 0) {
            return pack('C', $last);
        } else {
            return self::bcdecuc($remain) . pack('C', $last);
        }
    }

func (_class PBDClass) Create(sessionID SessionRef, args PBDRecord) (_retval PBDRef, _err error) {
	_method := "PBD.create"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_argsArg, _err := convertPBDRecordToXen(fmt.Sprintf("%s(%s)", _method, "args"), args)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _argsArg)
	if _err != nil {
		return
	}
	_retval, _err = convertPBDRefToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
Encrypt the given bytes using HMAC.

@param bytes
Bytes to encrypt
@return Encrypted bytes
@throws IOException
for all unexpected exceptions

private byte[] encrypt(final byte[] bytes) throws IOException {
        try (Formatter formatter = new Formatter()) {
            for (final byte byt : this.create().doFinal(bytes)) {
                formatter.format("%02x", byt);
            }
            return formatter.toString().getBytes(Charset.defaultCharset());
        }
    }

public void marshall(RecoveryPointByResource recoveryPointByResource, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(recoveryPointByResource.getRecoveryPointArn(), RECOVERYPOINTARN_BINDING);
            protocolMarshaller.marshall(recoveryPointByResource.getCreationDate(), CREATIONDATE_BINDING);
            protocolMarshaller.marshall(recoveryPointByResource.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(recoveryPointByResource.getEncryptionKeyArn(), ENCRYPTIONKEYARN_BINDING);
            protocolMarshaller.marshall(recoveryPointByResource.getBackupSizeBytes(), BACKUPSIZEBYTES_BINDING);
            protocolMarshaller.marshall(recoveryPointByResource.getBackupVaultName(), BACKUPVAULTNAME_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: // Convert_v1alpha1_WebhookAdmission_To_webhookadmission_WebhookAdmission is an autogenerated conversion function.

func Convert_v1alpha1_WebhookAdmission_To_webhookadmission_WebhookAdmission(in *WebhookAdmission, out *webhookadmission.WebhookAdmission, s conversion.Scope) error {
	return autoConvert_v1alpha1_WebhookAdmission_To_webhookadmission_WebhookAdmission(in, out, s)
}

def apply_environment!(hook_context, env)
      skipped_hooks = "#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}".split(/[:, ]/)
      only_hooks = env.fetch('ONLY') { '' }.split(/[:, ]/)
      hook_type = hook_context.hook_class_name

      if only_hooks.any? || skipped_hooks.include?('all') || skipped_hooks.include?('ALL')
        @hash[hook_type]['ALL']['skip'] = true
      end

      only_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                 map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                 each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = false
      end

      skipped_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                    map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                    each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = true
      end
    end

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


Question:
// Reserve is blocking until it returns an available tree
// it reuses free trees or creates a new one if size is not reached
// TODO: should use a context here

func (p *TreePool) reserve() *tree {
	p.lock.Lock()
	defer p.lock.Unlock()
	var t *tree
	if p.count == p.Capacity {
		return <-p.c
	}
	select {
	case t = <-p.c:
	default:
		t = newTree(p.SegmentSize, p.Depth, p.hasher)
		p.count++
	}
	return t
}

def _clean(self):
        """"""
        found_ids = {}
        nodes = [self._nodes[_node.Root.ID]]
        while nodes:
            node = nodes.pop()
            found_ids[node.id] = None
            nodes = nodes + node.children

        for node_id in self._nodes:
            if node_id in found_ids:
                continue
            logger.error('Dangling node: %s', node_id)

        for node_id in found_ids:
            if node_id in self._nodes:
                continue
            logger.error('Unregistered node: %s', node_id)

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


Question:
Fetch the metadata for the given identifier.

@param  string $ident The metadata identifier to load.
@throws InvalidArgumentException If the identifier is not a string.
@return array

public function loadMetadataByKey($ident)
    {
        if (!is_string($ident)) {
            throw new InvalidArgumentException(
                'Metadata identifier must be a string'
            );
        }

        $lineage  = $this->hierarchy($ident);
        $metadata = [];
        foreach ($lineage as $metaKey) {
            $data = $this->loadMetadataFromSource($metaKey);
            if (is_array($data)) {
                $metadata = array_replace_recursive($metadata, $data);
            }
        }

        return $metadata;
    }

func AsPartialObjectMetadata(m metav1.Object) *metav1beta1.PartialObjectMetadata {
	switch t := m.(type) {
	case *metav1.ObjectMeta:
		return &metav1beta1.PartialObjectMetadata{ObjectMeta: *t}
	default:
		return &metav1beta1.PartialObjectMetadata{
			ObjectMeta: metav1.ObjectMeta{
				Name:                       m.GetName(),
				GenerateName:               m.GetGenerateName(),
				Namespace:                  m.GetNamespace(),
				SelfLink:                   m.GetSelfLink(),
				UID:                        m.GetUID(),
				ResourceVersion:            m.GetResourceVersion(),
				Generation:                 m.GetGeneration(),
				CreationTimestamp:          m.GetCreationTimestamp(),
				DeletionTimestamp:          m.GetDeletionTimestamp(),
				DeletionGracePeriodSeconds: m.GetDeletionGracePeriodSeconds(),
				Labels:                     m.GetLabels(),
				Annotations:                m.GetAnnotations(),
				OwnerReferences:            m.GetOwnerReferences(),
				Finalizers:                 m.GetFinalizers(),
				ClusterName:                m.GetClusterName(),
				Initializers:               m.GetInitializers(),
				ManagedFields:              m.GetManagedFields(),
			},
		}
	}
}

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


Question:
Register the service provider.

@return void

public function register()
    {
        $this->app->singleton('Essentials', function ($app) {
            return new Essentials($app);
        });

        $this->app->alias('Essentials', Facade::class);
    }

protected function queueRecallerCookie(AuthenticatableContract $user)
    {
        $this->getCookieJar()->queue($this->createRecaller(
            $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword()
        ));
    }

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


Question: // UnmarshalJSON sets the object from the provided JSON representation

func (l *CloudFrontDistributionViewerCertificateList) UnmarshalJSON(buf []byte) error {
	// Cloudformation allows a single object when a list of objects is expected
	item := CloudFrontDistributionViewerCertificate{}
	if err := json.Unmarshal(buf, &item); err == nil {
		*l = CloudFrontDistributionViewerCertificateList{item}
		return nil
	}
	list := []CloudFrontDistributionViewerCertificate{}
	err := json.Unmarshal(buf, &list)
	if err == nil {
		*l = CloudFrontDistributionViewerCertificateList(list)
		return nil
	}
	return err
}

public WebhookData parseWebhookData(String webhook) {
        if (webhook == null || webhook.trim()
                .length() <= 0) {
            return null;
        }
        webhook = LEFT_QUOTATION.matcher(webhook)
                .replaceAll("{");
        webhook = RIGHT_QUOTATION.matcher(webhook)
                .replaceAll("}");
        webhook = BACKLASH_QUOTATION.matcher(webhook)
                .replaceAll("\"");

        return FastjsonDecoder.decodeAsBean(webhook, WebhookData.class);
    }

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


Question:
Operation list All

List PaymentSources

@param  PageRequest $page_request  (optional)

@throws \\ApiException on non-2xx response
@throws \InvalidArgumentException
@return \\Resources\page[PaymentSource]

public static function findAll($page_request = null)
    {
        if($page_request != null){
            return self::listAllPaymentSources(['page' => $page_request->getPageNumber(), 'size' => $page_request->getSize() ]);
        }else {
            return self::listAllPaymentSources();
        }
    }

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

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


Question:
// SetGauge sets the named gauge to the specified value
// Usage:
//     SetGauge([]string{"my","namespace"}, 2.0)

func SetGauge(key []string, val float32) {
	normalizeKeys(key)

	GetMetrics().SetGauge(key, val)
}

public function AddConstant(
        \Peg\Lib\Definitions\Element\Constant $constant,
        $namespace = "\\"
    )
    {
        $this->CreateNamespace($namespace);

        $constant->header =& $this;
        $constant->namespace =& $this->namespaces[$namespace];

        $this->namespaces[$namespace]->constants[$constant->name] = $constant;
    }

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


Question:
After delete remove also the language folder.

@param int $id

@return string

public function destroy($id)
    {
        $language = Language::find($id);
        $destroyResult = parent::destroy($id);

        if ($destroyResult) {
            \File::deleteDirectory(resource_path('lang/'.$language->abbr));
        }

        return $destroyResult;
    }

function destroyLocalVariablesList()
    {
        array_pop( $this->LocalVariablesNamesStack );

        if ( $this->LocalVariablesNamesStack )
            $this->CurrentLocalVariablesNames =& $this->LocalVariablesNamesStack[ count( $this->LocalVariablesNamesStack ) - 1];
        else
            unset( $this->CurrentLocalVariablesNames );
    }

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


Question:
Get FctBnCnvIbnToColumnValues in lazy mode.

@return FctBnCnvIbnToColumnValues - FctBnCnvIbnToColumnValues
@throws Exception - an exception

public final FctBnCnvIbnToColumnValues
    lazyGetFctBnCnvIbnToColumnValues() throws Exception {
    String beanName = getFctBnCnvIbnToColumnValuesName();
    FctBnCnvIbnToColumnValues fctBnCnvIbnToColumnValues =
      (FctBnCnvIbnToColumnValues) this.beansMap.get(beanName);
    if (fctBnCnvIbnToColumnValues == null) {
      fctBnCnvIbnToColumnValues = new FctBnCnvIbnToColumnValues();
      fctBnCnvIbnToColumnValues.setUtlReflection(lazyGetUtlReflection());
      fctBnCnvIbnToColumnValues.setFieldsRapiHolder(lazyGetHolderRapiFields());
      fctBnCnvIbnToColumnValues
        .setGettersRapiHolder(lazyGetHolderRapiGetters());
      fctBnCnvIbnToColumnValues.setIsNeedsToSqlEscape(getIsNeedsToSqlEscape());
      fctBnCnvIbnToColumnValues.setSrvSqlEscape(lazyGetSrvSqlEscape());
      this.beansMap.put(beanName, fctBnCnvIbnToColumnValues);
      lazyGetLogger().info(null, AFactoryAppBeans.class, beanName
        + " has been created.");
    }
    return fctBnCnvIbnToColumnValues;
  }

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Set the repository's path

@param   string $repository_path
@param   bool $createNew
@param   bool $_init
@return  void
@throws  \Exception

public function setRepositoryPath($repository_path, $createNew = false, $_init = true)
    {
        if (is_string($repository_path)) {
            if ($new_path = realpath($repository_path)) {
                $repository_path = $new_path;
                if (is_dir($repository_path)) {
                    if (file_exists($repository_path."/.git") && is_dir($repository_path."/.git")) {
                        $this->repository_path = $repository_path;
                    } else {
                        if ($createNew) {
                            $this->repository_path = $repository_path;
                            if ($_init) {
                                $this->run('init');
                            }
                        } else {
                            throw new \Exception(
                                sprintf('"%s" is not a git repository!', $repository_path)
                            );
                        }
                    }
                } else {
                    throw new \Exception(
                        sprintf('"%s" is not a directory', $repository_path)
                    );
                }
            } else {
                if ($createNew) {
                    if ($parent = realpath(dirname($repository_path))) {
                        mkdir($repository_path);
                        $this->repository_path = $repository_path;
                        if ($_init) {
                            $this->run('init');
                        }
                    } else {
                        throw new \Exception('Cannot create repository in non-existent directory');
                    }
                } else {
                    throw new \Exception(
                        sprintf('"%s" does not exist', $repository_path)
                    );
                }
            }
        }
    }

public function build($projectId, $branch = '')
    {
        /* @var \PHPCI\Model\Project $project */
        $project = $this->projectStore->getById($projectId);

        if (empty($project)) {
            throw new NotFoundException(Lang::get('project_x_not_found', $projectId));
        }

        if ($branch === '' && filter_input(INPUT_GET, 'branch') !== null) {
            $branch = filter_input(INPUT_GET, 'branch');
        }

        if (empty($branch)) {
            $branch = $project->getBranch();
        }

        $email = $_SESSION['phpci_user']->getEmail();
        $build = $this->buildService->createBuild($project, null, urldecode($branch), $email);

        if ($this->buildService->queueError) {
            $_SESSION['global_error'] = Lang::get('add_to_queue_failed');
        }

        $response = new b8\Http\Response\RedirectResponse();
        $response->setHeader('Location', PHPCI_URL.'build/view/' . $build->getId());
        return $response;
    }

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


Question: // DeleteRange deletes range of items

func (s *Reporter) DeleteRange(ctx context.Context, startKey []byte, endKey []byte) error {
	start := s.Clock().Now()
	err := s.Backend.DeleteRange(ctx, startKey, endKey)
	batchWriteLatencies.WithLabelValues(s.Component).Observe(time.Since(start).Seconds())
	batchWriteRequests.WithLabelValues(s.Component).Inc()
	if err != nil && !trace.IsNotFound(err) {
		batchWriteRequestsFailed.WithLabelValues(s.Component).Inc()
	}
	s.trackRequest(OpDelete, startKey, endKey)
	return err
}

function(toDelete, evtStck) {
    let len = toDelete.length
    for (let i = 0; len > i; len--) {
      evtStck.splice(toDelete[len - 1], 1)
    }
  }

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


Question:
Args:
      lookup: the tagged route table name, should be unique
      default: the optional value to return if lookup failed; returns None if not set
    Returns:
      the ID of the route table, or default if no match/multiple matches found

def ec2_route_table_tagged_route_table_id(self, lookup, default=None):

    route_table = EFAwsResolver.__CLIENTS["ec2"].describe_route_tables(Filters=[
      {'Name': 'tag-key', 'Values': ['Name']},
      {'Name': 'tag-value', 'Values': [lookup]}
    ])
    if len(route_table["RouteTables"]) is not 1:
      return default
    return route_table["RouteTables"][0]["RouteTableId"]

public static function route(Http\Request $request)
    {
        $path = $request->REQUEST_URI;
        $key = $request->getMethod().'@'.$path;
        $keyAny = 'ANY@'.$path;

        $matchedRoute = null;
        $matchedScore = 0;

        if (isset(self::$routes[$key])) {
            $matchedRoute = self::$routes[$key];
        } elseif (isset(self::$routes[$keyAny])) {
            $matchedRoute = self::$routes[$keyAny];
        } else {
            foreach (self::$routes as $key2 => $route) {
                if ($route->getMethod() != 'ANY' && $route->getMethod() != $request->getMethod()) {
                    continue;
                }

                $score = $route->getScore($path, $request->getMethod());
                if ($score > $matchedScore) {
                    $matchedRoute = $route;
                    $matchedScore = $score;
                }
            }
        }

        if ($matchedRoute) {
            $matchedRoute->setUrl($path);
        } elseif (self::$_404route) {
            $matchedRoute = self::$_404route;
        } else {
            throw new Exceptions\RouteException('Route not found');
        }
        return $matchedRoute;
    }

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


Question:
Retrieve the current version available remotely.

@param Updater $updater
@return string|bool

public function getCurrentRemoteVersion(Updater $updater)
    {
        $releasesUrl = sprintf(
            self::URL_RELEASES,
            urlencode($this->repositoryOwner),
            urlencode($this->repositoryName)
        );
        $releasesJson = $this->getJsonResource($releasesUrl);
        $releases = json_decode($releasesJson, true);

        if (null === $releases || json_last_error() !== JSON_ERROR_NONE) {
            throw new JsonParsingException(sprintf('Error parsing JSON release data: %s', json_last_error_msg()));
        }

        $indexedReleases = array_combine(array_column($releases, 'tag_name'), $releases);
        $indexedPharReleases = array_filter(
            $indexedReleases,
            function (array $release) {
                if ($release['draft']) {
                    return false;
                }

                $pharAssets = array_filter(
                    $release['assets'],
                    function (array $asset) {
                        return $asset['name'] === $this->releasePharName;
                    }
                );
                $hasPharAsset = count($pharAssets) > 0;

                return $hasPharAsset;
            }
        );

        if (count($indexedPharReleases) === 0) {
            return false;
        }

        $tagNames = array_keys($indexedPharReleases);
        $versionParser = new VersionParser($tagNames);

        if ($this->allowUnstable) {
            $this->remoteVersion = $versionParser->getMostRecentAll();
        } else {
            $this->remoteVersion = $versionParser->getMostRecentStable();
        }

        if (!$this->remoteVersion) {
            return $this->remoteVersion;
        }

        $release = $indexedPharReleases[$this->remoteVersion];
        $pharAssets = array_filter(
            $release['assets'],
            function (array $asset) {
                return $asset['name'] === $this->releasePharName;
            }
        );

        $this->remoteUrl = $pharAssets[0]['url'];

        return $this->remoteVersion;
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $configurationPath = $input->getOption('configurationPath');
        $deploymentName = $input->getArgument('deploymentName');
        $deployment = $this->factory->getDeployment($deploymentName, $configurationPath);
        $workflow = $deployment->getWorkflow();

        if (! $deployment instanceof FailedDeployment) {
            $output->writeln('<success>Deployment ' . $deployment->getName() . '</success>');
            $output->writeln('');
            $output->writeln('Workflow: <success>' . $workflow->getName() . '</success>');

            if ($workflow instanceof SimpleWorkflow) {
                $value = $workflow->isEnableRollback() ? 'true' : 'false';
                $output->writeln('    <comment>Rollback enabled:</comment> <info>' . $value . '</info>');
            }

            $output->writeln('');

            $this->printNodes($deployment->getNodes());

            $this->printApplications($deployment->getApplications(), $deployment->getWorkflow());
        }
    }

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


Question:
Иницилазия

@return void
@throws Exception\AnnotationReaderException

protected function init()
    {
        try {
            AnnotationRegistry::registerLoader(function ($class) {
                return (bool) class_exists($class);
            });
        } catch (\Exception $e) {
            throw new Exception\AnnotationReaderException($e->getMessage(), $e->getCode(), $e);
        }
    }

public static List<String> extractResponseDescription(JavadocComment jdoc){
		List<String> list = new ArrayList<>();
		list.addAll(extractDocAnnotation(DOC_RESPONSE_DESCRIPTION,jdoc));

		return list;
	}

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


Question: Reset the masked area - should be done after you've finished rendering

public static void resetMask() {
		GL.glDepthMask(true);
		GL.glClearDepth(0);
		GL.glClear(SGL.GL_DEPTH_BUFFER_BIT);
		GL.glDepthMask(false);

		GL.glDisable(SGL.GL_DEPTH_TEST);
	}

def clear_deadline(self):

        # Implemented from template for osid.assessment.AssessmentOfferedForm.clear_start_time_template
        if (self.get_deadline_metadata().is_read_only() or
                self.get_deadline_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['deadline'] = self._deadline_default

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


Question:
Check if the database structure is ok (with the good version), if no : build it

@throws Zend_Cache_Exception
@return boolean True if ok

private function _checkAndBuildStructure()
    {
        if (!($this->_structureChecked)) {
            if (!$this->_checkStructureVersion()) {
                $this->_buildStructure();
                if (!$this->_checkStructureVersion()) {
                    Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']);
                }
            }
            $this->_structureChecked = true;
        }
        return true;
    }

public static function queryByBaseId( $baseId, $config = [] ) {

		$type	= isset( $config[ 'type' ] ) ? $config[ 'type' ] : self::TYPE_COMMENT;
		$status	= isset( $config[ 'status' ] ) ? $config[ 'status' ] : self::STATUS_APPROVED;

		return self::find()->where( [ 'baseId' => $baseId, 'type' => $type, 'status' => $status ] );
	}

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


Question:
Return the Round Changed event name for this round

@param int $roundId
@return \Gems_Event_RoundChangedEventInterface event instance or null

public function getRoundChangedEvent($roundId)
    {
        $this->_ensureRounds();

        if (isset($this->_rounds[$roundId]['gro_changed_event']) && $this->_rounds[$roundId]['gro_changed_event']) {
            return $this->events->loadRoundChangedEvent($this->_rounds[$roundId]['gro_changed_event']);
        }
    }

function validateEventStorage(storage) {
	if (!storage) throw new TypeError('storage argument required');
	if (typeof storage !== 'object') throw new TypeError('storage argument must be an Object');
	if (typeof storage.commitEvents !== 'function') throw new TypeError('storage.commitEvents must be a Function');
	if (typeof storage.getEvents !== 'function') throw new TypeError('storage.getEvents must be a Function');
	if (typeof storage.getAggregateEvents !== 'function') throw new TypeError('storage.getAggregateEvents must be a Function');
	if (typeof storage.getSagaEvents !== 'function') throw new TypeError('storage.getSagaEvents must be a Function');
	if (typeof storage.getNewId !== 'function') throw new TypeError('storage.getNewId must be a Function');
}

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


Question:
Add the requested post parameters to the Request.

@param request Request to add post params to

private void addPostParams(final Request request) {
        if (friendlyName != null) {
            request.addPostParam("FriendlyName", friendlyName);
        }

        if (domainName != null) {
            request.addPostParam("DomainName", domainName);
        }

        if (disasterRecoveryUrl != null) {
            request.addPostParam("DisasterRecoveryUrl", disasterRecoveryUrl.toString());
        }

        if (disasterRecoveryMethod != null) {
            request.addPostParam("DisasterRecoveryMethod", disasterRecoveryMethod.toString());
        }

        if (recording != null) {
            request.addPostParam("Recording", recording.toString());
        }

        if (secure != null) {
            request.addPostParam("Secure", secure.toString());
        }

        if (cnamLookupEnabled != null) {
            request.addPostParam("CnamLookupEnabled", cnamLookupEnabled.toString());
        }
    }

private function prepareRequestArguments(array $data = null, string $method = null): array
    {
        $data   = $data ?? [];
        $method = $method ?? 'GET';

        // Removes null entries.
        $data = array_filter($data, function ($val) {
            return (null !== $val);
        });

        $headers = [
            'Content-Type' => 'application/json',
            'X-Auth-Email' => $this->email,
            'X-Auth-Key'   => $this->auth_key,
        ];

        $args = [
            'body'    => wp_json_encode($data),
            'headers' => $headers,
            'method'  => strtoupper($method),
            'timeout' => 15,
        ];

        return $args;
    }

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


Question:
获取本地下载的路径DIR, 通过参数判断是否是临时路径

@throws Exception

private String getLocalDownloadDirPath() throws Exception {

        String localUrl = localDownloadDir;

        if (!new File(localUrl).exists()) {
            new File(localUrl).mkdirs();
        }

        return localUrl;
    }

def capture_working_directory(self):

        workdir = os.path.join(self._path, "tmp", "captures")
        if not self._deleted:
            try:
                os.makedirs(workdir, exist_ok=True)
            except OSError as e:
                raise aiohttp.web.HTTPInternalServerError(text="Could not create the capture working directory: {}".format(e))
        return workdir

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


Question:
Sort an collection by key

@param int $options Sorting type flags
@param bool $desc In reverse order
@return static

public function sortKeys( int $options = SORT_REGULAR, bool $desc = false )
	{
		$items = $this->items;
		$desc ? krsort($items, $options) : ksort($items, $options);
		return new static($items);
	}

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:
Return true if the agent has a symptom with the name symptomName and the
same level of symptomLevel or if the agent doesn't have the symptome and
symptomLeve == "NONE", in another case it returns false;

@param agent
@return

@Override
    public boolean simpleEvaluation(Agent currentAgent) {
        Agent agent = currentAgent;
        if (bodyId != null) {
            agent = agent.getAgentsAppState().getAgent(bodyId);
        }
        if (agent instanceof HumanAgent) {
            DiseaseManager dm = ((HumanAgent)agent).getDiseaseManager();
            if (dm != null) {
                Symptom s = dm.getSymptom(symptomName);
                if (s != null) {
                    if (s.getCurrentLevel().equals(Symptom.Level.valueOf(symptomLevel))) {
                        return true;
                    }
                } else {
                    logger.log(Level.WARNING, "Agent {0} hasn't got symptom {1}!", new Object[]{agent.getId(), symptomName});
                    return symptomLevel.equals(Symptom.Level.NONE.name());
                }
            } else {
                logger.log(Level.WARNING, "Agent {0} hasn't got DiseaseManager", new Object[]{agent.getId()});
                return symptomLevel.equals(Symptom.Level.NONE.name());
            }
        }

        return false;
    }

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

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


Question:
Set time limit on operating system process

@param object
@param function

@return timeoutObject

function _setTimeLimit(options, done) {
        if (options && options.timeLimit && options.pidFile) {
          var timeout = setTimeout(function() {
                var kill = 'kill $(cat ' + options.pidFile + ')';
                if (logLevel === 'trace') logger.warn('process', kill);
                childProcess.exec(kill, function(err, stdout, stderr) {
                    if (err) {
                      if (logLevel === 'trace') logger.error('process', 'timeout', err);
                    }
                    if (stderr) {
                      if (logLevel === 'trace') logger.warn('process', 'timeout', stderr);
                    }
                    if (stdout) {
                      if (logLevel === 'trace') logger.info('process', 'timeout', stdout);
                    }
                    options.returnNow = 'Sorry, that file took too long to process';
                  });
                }, options.timeLimit);
          done(timeout);
        }
        else {
          done(false);
        }
      }

def _validate_args(env, args):
    """"""

    if all([args['cpu'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-c | --cpu] not allowed with [-f | --flavor]')

    if all([args['memory'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-m | --memory] not allowed with [-f | --flavor]')

    if all([args['dedicated'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-d | --dedicated] not allowed with [-f | --flavor]')

    if all([args['host_id'], args['flavor']]):
        raise exceptions.ArgumentError(
            '[-h | --host-id] not allowed with [-f | --flavor]')

    if all([args['userdata'], args['userfile']]):
        raise exceptions.ArgumentError(
            '[-u | --userdata] not allowed with [-F | --userfile]')

    image_args = [args['os'], args['image']]
    if all(image_args):
        raise exceptions.ArgumentError(
            '[-o | --os] not allowed with [--image]')

    while not any([args['os'], args['image']]):
        args['os'] = env.input("Operating System Code", default="", show_default=False)
        if not args['os']:
            args['image'] = env.input("Image", default="", show_default=False)

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


Question:
Calls {@link #getUriForFile(Context, String, File)} using the correct authority for Telescope
screenshots.

public static Uri getUriForFile(Context context, File file) {
    return getUriForFile(context, context.getPackageName() + ".telescope.fileprovider", file);
  }

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

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

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


Question:
This tag call _delegate.setAttributes, so the returned MetaRuleset
should ignore attributes that are not supposed to be there like
"binding" and "event"

@Override
    public MetaRuleset createMetaRuleset(Class type)
    {
        MetaRuleset ruleset = new MetaRulesetImpl(_delegate.getTag(), type);
        ruleset.ignore("binding");
        ruleset.ignore("event");
        return ruleset;
    }

def assert_datasource_protocol(event):
    """"""

    assert event.type in DATASOURCE_TYPE

    # Done packets have no dt.
    if not event.type == DATASOURCE_TYPE.DONE:
        assert isinstance(event.dt, datetime)
        assert event.dt.tzinfo == pytz.utc

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


Question: nextKey(key) >= key

def nextKey(self, key):
        """"""
        ans = self.nextNode(key)
        return (ans.key
                if ans is not None
                else None)

@Override
    public boolean hasNext() {
        try {
            return hasNextValue();
        } catch (JsonMappingException e) {
            throw new RuntimeJsonMappingException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

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


Question: Add a routing rule to the routing table. The $endpoint must be either a callback accepting $request, $response, or a class that extends the \Fubber\Reactor\Controller.

public function addRoute($pattern, $endpoint) {
        if(is_object($endpoint) && $endpoint instanceof \Fubber\Reactor\EndpointInterface) {
            // All is fine and dandy
        } elseif (is_callable($endpoint)) {
            // Make a CallbackController
            return $this->addRoute($pattern, new CallbackController($endpoint));
        } else {
            $this->notice('Host::addRoute(): Expects a callback or a controller');
            return FALSE;
        }

        $count = substr_count($pattern, '*');

        if ($count === 0) {
            // This is merely a direct route
            $this->extraRoutes[$pattern] = $this->routes[$pattern] = $endpoint;
        } else {
            // Add this route to the $this->searchRoutes and sort it again
            $this->extraRoutes[$pattern] = $endpoint;
            $this->searchRoutes[] = array($pattern, $endpoint);
        }
    }

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Change the geo reference of a list or numeric array of points to
        be this reference.(The reference used for this object)
        If the points do not have a geo ref, assume 'absolute' values

def change_points_geo_ref(self, points, points_geo_ref=None):

        import copy

        # remember if we got a list
        is_list = isinstance(points, list)

        points = ensure_numeric(points, num.float)

        # sanity checks
        if len(points.shape) == 1:
            #One point has been passed
            msg = 'Single point must have two elements'
            assert len(points) == 2, msg
            points = num.reshape(points, (1,2))

        msg = 'Points array must be two dimensional.\n'
        msg += 'I got %d dimensions' %len(points.shape)
        assert len(points.shape) == 2, msg

        msg = 'Input must be an N x 2 array or list of (x,y) values. '
        msg += 'I got an %d x %d array' %points.shape
        assert points.shape[1] == 2, msg

        # FIXME (Ole): Could also check if zone, xllcorner, yllcorner
        # are identical in the two geo refs.
        if points_geo_ref is not self:
            # If georeferences are different
            points = copy.copy(points) # Don't destroy input
            if not points_geo_ref is None:
                # Convert points to absolute coordinates
                points[:,0] += points_geo_ref.xllcorner
                points[:,1] += points_geo_ref.yllcorner

            # Make points relative to primary geo reference
            points[:,0] -= self.xllcorner
            points[:,1] -= self.yllcorner

        if is_list:
            points = points.tolist()

        return points

def set_probe_position(self, new_probe_position):

        if new_probe_position is not None:
            # convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes.
            new_probe_position = Geometry.FloatPoint.make(new_probe_position)
            new_probe_position = Geometry.FloatPoint(y=max(min(new_probe_position.y, 1.0), 0.0),
                                                     x=max(min(new_probe_position.x, 1.0), 0.0))
        old_probe_position = self.__probe_position_value.value
        if ((old_probe_position is None) != (new_probe_position is None)) or (old_probe_position != new_probe_position):
            # this path is only taken if set_probe_position is not called as a result of the probe_position model
            # value changing.
            self.__probe_position_value.value = new_probe_position
        # update the probe position for listeners and also explicitly update for probe_graphic_connections.
        self.probe_state_changed_event.fire(self.probe_state, self.probe_position)

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


Question: push configuration references at configure time

function applyTemplateContent(inst, node, nodeInfo) {
  if (nodeInfo.templateInfo) {
    node._templateInfo = nodeInfo.templateInfo;
  }
}

public function setOption($name, $value) {
		$this->validateName($name);
		$this->config[$name] = $value;
	}

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


Question:
Return the direction like 'NE' based on the first tracksegment of the instruction. If
Instruction does not contain enough coordinate points, an empty string will be returned.

public String calcDirection(Instruction nextI) {
        double azimuth = calcAzimuth(nextI);
        if (Double.isNaN(azimuth))
            return "";

        return AC.azimuth2compassPoint(azimuth);
    }

def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords

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


Question: Resets the algorithm into its original state

public void reset() {
		tracker.reset();
		keyToWorld.reset();
		currToKey.reset();
		first = true;
		tick = 0;
	}

def clean_previous_run(self):

        # Execute the base class treatment...
        super(Alignak, self).clean_previous_run()

        # Clean all lists
        self.pollers.clear()
        self.reactionners.clear()
        self.brokers.clear()

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


Question: /* ########## Begin module implementation ##########

function initModule(forge) {

forge.mgf = forge.mgf || {};
forge.mgf.mgf1 = forge.mgf1;

}

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

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


Question:
Records which arguments are guaranteed to be non-null if the method completes without
exception. For example, if {@code checkNotNull(foo, message)} completes successfully, then
{@code foo} is not null.

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

func (m *message) String() string {
	var b stringBuilder
	b.WriteString("Message{")
	b.field("address", m.address, isEmpty)
	b.field("durable", m.durable, isZero)
	// Priority has weird default
	b.field("priority", m.priority, func(v interface{}) bool { return v.(uint8) == 4 })
	b.field("ttl", m.ttl, isZero)
	b.field("first-acquirer", m.firstAcquirer, isZero)
	b.field("delivery-count", m.deliveryCount, isZero)
	b.field("message-id", m.messageId, isNil)
	b.field("user-id", m.userId, isEmpty)
	b.field("subject", m.subject, isEmpty)
	b.field("reply-to", m.replyTo, isEmpty)
	b.field("correlation-id", m.correlationId, isNil)
	b.field("content-type", m.contentType, isEmpty)
	b.field("content-encoding", m.contentEncoding, isEmpty)
	b.field("expiry-time", m.expiryTime, isZero)
	b.field("creation-time", m.creationTime, isZero)
	b.field("group-id", m.groupId, isEmpty)
	b.field("group-sequence", m.groupSequence, isZero)
	b.field("reply-to-group-id", m.replyToGroupId, isEmpty)
	b.field("inferred", m.inferred, isZero)
	b.field("delivery-annotations", m.deliveryAnnotations, isEmpty)
	b.field("message-annotations", m.messageAnnotations, isEmpty)
	b.field("application-properties", m.applicationProperties, isEmpty)
	b.field("body", m.body, isNil)
	b.WriteString("}")
	return b.String()
}

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


Question: Clears the Caches for all model elements

def clear_caches(self):

        for element_name in dir(self.components):
            element = getattr(self.components, element_name)
            if hasattr(element, 'cache_val'):
                delattr(element, 'cache_val')

public function reset()
    {
        $this->pathRegistered = false;

        if ($this->renderer instanceof PhpRenderer) {
            $this->renderer->reset();
        }

        $this->renderer->setPaths(new PriorityQueue());

        return $this;
    }

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


Question:
Cancel all defer actions for the current stack depth.

@since 1.0

@Weight(value = Weight.Unit.VARIABLE, comment = "Depends on the current call stack depth")
  public static void cancelDeferredActions() {
    final int stackDepth = ThreadUtils.stackDepth();

    final List<Deferred> list = REGISTRY.get();
    final Iterator<Deferred> iterator = list.iterator();

    while (iterator.hasNext()) {
      final Deferred deferred = iterator.next();
      if (deferred.getStackDepth() >= stackDepth) {
        iterator.remove();
      }
    }
    if (list.isEmpty()) {
      REGISTRY.remove();
    }
  }

function (opts, cb) {
      var self = this
      opts = opts || {}
      var root = opts.root || RootKey
      var _cb = function (err, doc) {
        if (err) {
          cb(err, ERR.config.FA_LIST_CONFIG)
        } else {
          if (!doc) {
            if (opts.all) return cb(null, {})
            return cb(null, [])
          }
          if (opts.all) {
            for (var key in doc) {
              var _doc = self._parse(doc[key])
              if (_doc.value) {
                doc[key] = _doc.value
              } else {
                delete doc[key]
              }
            }
          }
          cb(null, doc)
        }
      }
      if (opts.all) {
        mq.hgetall(root, _cb)
      } else {
        mq.hkeys(root, _cb)
      }
    }

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


Question:
Returns the parameter values to be bound to the OQL statement.

@return
the parameter values.

public Object[] getParameterValues()
    {
        Object[]  empty = new Object[0];
        if (_paramVlaues == null  ||  _paramVlaues.size() == 0) {
            return empty;
        }

        return _paramVlaues.toArray( empty );
    }

public function contextHasMessages($context_data)
    {
        $qb2 = $this->_em->createQueryBuilder();
        $qb2->select('mc')
              ->from($this->_entityName, 'mc')
              ->where('mc.system = :system')
              ->andWhere('mc.object_name = :object_name')
              ->andWhere('mc.external_id = :external_id')
              ->setParameter("system", $context_data['system'])
              ->setParameter("object_name", $context_data['object_name'])
              ->setParameter("external_id", $context_data['external_id'])
              ->setMaxResults(1);

        $message_context = $qb2->getQuery()->getResult();
        return !empty($message_context);
    }

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


Question:
/*
This method will set the values to human subject supplement details

private void setHumaSubjectSupplementDetails(
			RROtherProjectInfo12Document.RROtherProjectInfo12 rrOtherProjectInfo,
			OrganizationContract organization,
			ProposalSpecialReviewContract proposalSpecialReview) {
		rrOtherProjectInfo.setHumanSubjectsIndicator(YesNoDataType.Y_YES);
		HumanSubjectsSupplement humanSubjectsSupplement = HumanSubjectsSupplement.Factory
				.newInstance();
		HumanSubjectsSupplement.ExemptionNumbers exemptionNumbers = HumanSubjectsSupplement.ExemptionNumbers.Factory
				.newInstance();

		if (proposalSpecialReview.getApprovalType() != null) {
			setExemptions(proposalSpecialReview, humanSubjectsSupplement,
					exemptionNumbers);
			setHumanSubjectIRBReviewIndicator(proposalSpecialReview,
					humanSubjectsSupplement);
		}
		if (organization != null && organization.getHumanSubAssurance() != null) {
			humanSubjectsSupplement.setHumanSubjectAssuranceNumber(organization
					.getHumanSubAssurance().substring(3));
		}
		if (humanSubjectsSupplement != null) {
			rrOtherProjectInfo
					.setHumanSubjectsSupplement(humanSubjectsSupplement);
		}
	}

def get_help_option_names(self, ctx):
        """"""
        all_names = set(ctx.help_option_names)
        for param in self.params:
            all_names.difference_update(param.opts)
            all_names.difference_update(param.secondary_opts)
        return all_names

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


Question: // LatencyAtQuantile sets latency at quantile with microsecond precision

func (h *HDRHistogram) LatencyAtQuantile(q float64) time.Duration {
	return time.Duration(h.ValueAtQuantile(q)) * time.Microsecond
}

private void checkQueueSize() {
        int queueSize = getQueueSize();
        if (SEND_QUEUE_SIZE_WARNING_THRESHOLD > 0 && queueSize >= SEND_QUEUE_SIZE_WARNING_THRESHOLD) {
            logger.warn("The Gerrit send commands queue contains {} items!"
                    + " Something might be stuck, or your system can't process the commands fast enough."
                    + " Try to increase the number of sending worker threads."
                    + " Current thread-pool size: {}",
                    queueSize, executor.getPoolSize());
            logger.info("Nr of active pool-threads: {}", executor.getActiveCount());
        }
    }

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


Question:
获取注册的插件
@param string $name
@return mixed

public static function getPlugin(string $name)
    {
        if (isset(self::$plugins[$name])) {
            return self::$plugins[$name];
        }
        $class = '\\sdopx\\plugin\\' . Utils::toCamel($name) . 'Plugin';
        if (class_exists($class)) {
            self::$plugins[$name] = new $class();
            return self::$plugins[$name];
        }
        return null;
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question: Does a full sort based on an array of criteria, plus the option to set the position of any unmatched items. Can be used with an anymatch-compatible criteria array, or an array of those arrays.

function grouped(array, groups, order) {
  if (!groups) { groups = [returnFalse]; }
  var sorted = [];
  var ordered = [];
  var remaining = array.slice();
  var unmatchedPosition = groups.indexOf('unmatched');
  groups.forEach(function(criteria, index) {
    if (index === unmatchedPosition) { return; }
    var tieBreakers = [];
    if (index !== groups.length - 1) {
      tieBreakers = groups.slice(index + 1);
      if (index < unmatchedPosition) {
        tieBreakers.splice(unmatchedPosition - index - 1, 1);
      }
    }
    var spliced = splice(remaining, criteria, tieBreakers);
    var matched = spliced.matched;
    var unmatched = spliced.unmatched;
    sorted[index] = matched;
    remaining = unmatched;
  });
  if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
  sorted[unmatchedPosition] = remaining;
  if (Array.isArray(order)) {
    order.forEach(function(position, index) {
      ordered[index] = sorted[position];
    });
  } else {
    ordered = sorted;
  }
  return ordered.reduce(function(flat, group) {
    return flat.concat(group);
  }, []);
}

public function load(ContainerBuilder $container, array $config) {
        // Client initializer definition
        $clientInitializerDefinition = new Definition(
            ApiClientAwareInitializer::class,
            [
                $config['apiClient']
            ]
        );
        $clientInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Definition for the array contains comparator
        $comparatorDefinition = new Definition(ArrayContainsComparator::class);

        // Comparator initializer definition
        $comparatorInitializerDefinition = new Definition(
            ArrayContainsComparatorAwareInitializer::class,
            [
                new Reference(self::COMPARATOR_SERVICE_ID)
            ]
        );
        $comparatorInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Add all definitions to the container
        $container->setDefinition(self::APICLIENT_INITIALIZER_SERVICE_ID, $clientInitializerDefinition);
        $container->setDefinition(self::COMPARATOR_SERVICE_ID, $comparatorDefinition);
        $container->setDefinition(self::COMPARATOR_INITIALIZER_SERVICE_ID, $comparatorInitializerDefinition);
    }

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