comment stringlengths 16 255 | code stringlengths 52 3.87M |
|---|---|
Internal: Returns all parents for path
path - String absolute filename or directory
root - String path to stop at (default: system root)
Returns an Array of String paths. | def path_parents(path, root = nil)
root = "#{root}#{File::SEPARATOR}" if root
parents = []
loop do
parent = File.dirname(path)
break if parent == path
break if root && !path.start_with?(root)
parents << path = parent
end
parents
end |
ItemProcFunc for container items
removes items of the children chain from the list of selectable containers
if the element itself already is a container
@param array $params An array containing the items and parameters for the list of items | public function containerItemsProcFunc(array &$params)
{
$this->init($params['row']['pid']);
$possibleContainers = [];
$this->removeItemsFromListOfSelectableContainers($params, $possibleContainers);
if (!empty($possibleContainers)) {
$params['items'] = array_merge($param... |
Creates a text component with content, and optional color.
@param content the plain text content
@param color the color
@return the text component | public static TextComponent of(final @NonNull String content, final @Nullable TextColor color) {
return of(content, color, Collections.emptySet());
} |
Return true if alert severity has changed more than X times in Y seconds | def is_flapping(self, alert, window=1800, count=2):
pipeline = [
{'$match': {
'environment': alert.environment,
'resource': alert.resource,
'event': alert.event,
'customer': alert.customer
}},
{'$unwind'... |
Profile a function. | def profile(fun, *args, **kwargs):
timer_name = kwargs.pop("prof_name", None)
if not timer_name:
module = inspect.getmodule(fun)
c = [module.__name__]
parentclass = labtypes.get_class_that_defined_method(fun)
if parentclass:
c.append(parentclass.__name__)
... |
Convert this variable to a pandas.Index | def to_index(self):
""""""
# n.b. creating a new pandas.Index from an old pandas.Index is
# basically free as pandas.Index objects are immutable
assert self.ndim == 1
index = self._data.array
if isinstance(index, pd.MultiIndex):
# set default names for multi-i... |
进行正则替换 replace中的$1 $9 分别对应group(1-9)
@param str 需要处理的字符串
@param regex 正则表达式
@param replace 替换的字符串
@return 进行正则表达式替换 | public String replace(String str, String regex, String replace) {
if (str == null)
return "";
if (regex == null)
return str;
if(replace == null) replace = "";
return str.replaceAll(regex, replace);
} |
Creates a new HTTP session scope. | private void newHttpSessionScope() {
SessionScopeAdvisor advisor = SessionScopeAdvisor.create(context);
this.sessionScope = new HttpSessionScope(advisor);
setAttribute(SESSION_SCOPE_ATTRIBUTE_NAME, this.sessionScope);
} |
Deletes all requests and responses for the given flows.
Args:
session_ids: A lists of flows to destroy.
request_limit: A limit on the number of requests to delete.
Returns:
A list of requests that were deleted. | def MultiDestroyFlowStates(self, session_ids, request_limit=None):
subjects = [session_id.Add("state") for session_id in session_ids]
to_delete = []
deleted_requests = []
for subject, values in self.MultiResolvePrefix(
subjects, self.FLOW_REQUEST_PREFIX, limit=request_limit):
for _,... |
// Create and return PIDGatherer lazily | func (p *Procstat) getPIDFinder() (PIDFinder, error) {
if p.finder == nil {
f, err := p.createPIDFinder()
if err != nil {
return nil, err
}
p.finder = f
}
return p.finder, nil
} |
Decodes the next value
@returns {string} Next value | function decode() {
var beg = i;
var ch;
var r = "";
// iterate until we reach the end of the string or "~" or ")"
while (i < len && (ch = s[i]) !== "~" && ch !== ")") {
switch (ch) {
case "*":
if (b... |
Sends a custom message. See the docs for all the possible options
@see https://docs.emaildirect.com/#RelaySendCustomEmail | def send(options)
response = EmailDirect.post "/RelaySends/#{category_id}", :body => options.to_json
Hashie::Mash.new(response)
end |
/*Mfi - Money Flow Index
Input = High, Low, Close, Volume
Output = double
Optional Parameters
-------------------
optInTimePeriod:(From 2 to 100000)
Number of period
*/ | func Mfi(high, low, close, volume []float64, timePeriod int32) []float64 {
var outBegIdx C.int
var outNBElement C.int
outReal := make([]float64, len(high))
C.TA_MFI(0, C.int(len(high)-1), (*C.double)(unsafe.Pointer(&high[0])), (*C.double)(unsafe.Pointer(&low[0])), (*C.double)(unsafe.Pointer(&close[0])), (*C.double)... |
创建 ColumnField
@param column
@return | public static ColumnField build(IntrospectedColumn column) {
ColumnField field = new ColumnField();
field.setColumnName(column.getActualColumnName());
field.setJdbcType(column.getJdbcTypeName());
field.setFieldName(column.getJavaProperty());
field.setRemarks(column.getRemarks());... |
End hash element.
@param string $name | public function endHashElement($name)
{
$this->checkEndHashElement($name);
$this->json = $this->json->getParent();
} |
Delete a permission module
@author Steve Montambeault
@link http://stevemo.ca
@param $id
@return \Illuminate\Http\RedirectResponse | public function destroy($id)
{
if ( $this->permissions->delete($id) )
{
return Redirect::route('cpanel.permissions.index')
->with('success', Lang::get('cpanel::permissions.delete_success'));
}
else
{
return Redirect::route('cpanel.permi... |
Create user
REST: POST /cloud/project/{serviceName}/user
@param description [required] User description
@param role [required] Openstack keystone role name
@param serviceName [required] Service name | public OvhUserDetail project_serviceName_user_POST(String serviceName, String description, OvhRoleEnum role) throws IOException {
String qPath = "/cloud/project/{serviceName}/user";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", d... |
This function searches for LaTeX expressions, delimited by $ and $$.
It then adds backticks (``) around the expression, so that is does not
get modifed by Markdown or BBcode.
@param PostWillBeSaved $event | public function findExpressions(PostWillBeSaved $event)
{
// get the text from the post, comment or answer
$text = $event->post->content;
// this is the regular expresssion used. To check what it does use regex101.com
$regex = '/(?<!\\\\)(?: ((?<!\\$)(?<!\\`)(?<!\\`\\n)\\${1,2}(?!\\n... |
Parsing the sent input | private function parse(){
$inputs = explode('&',$this->input);
foreach($inputs as $input){
$exp = explode('=',$input);
if(count($exp)==2)
$this->content[urldecode($exp[0])] = urldecode($exp[1]);
}
} |
Add a Download Feed
@param int $downloadFeedUrl
@return models\Download\Feed\DownloadFeed
@throws \GuzzleHttp\Exception\GuzzleException
@throws \alphayax\freebox\Exception\FreeboxApiException | public function addFeed($downloadFeedUrl)
{
$rest = $this->callService('POST', self::API_DOWNLOAD_FEEDS, [
'url' => $downloadFeedUrl,
]);
return $rest->getModel(models\Download\Feed\DownloadFeed::class);
} |
/*
This function will return all the menu and sub-menu items that can
be directly (the shortcut directly corresponds) and indirectly
(the ALT-enabled char corresponds to the shortcut) associated
with the keyCode. | @SuppressWarnings("deprecation")
void findItemsWithShortcutForKey(List<MenuItem> items, int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Ge... |
Marshall the given parameter object. | public void marshall(RegistrationConfig registrationConfig, ProtocolMarshaller protocolMarshaller) {
if (registrationConfig == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(registrationConfig.getTem... |
Returns all Days of Showtimes by a Movie.
@param Carbon $date
@return TheaterShowtimeDay|null | public function getShowtimeDayByMovie(Carbon $date)
{
$showDay = new TheaterShowtimeDay();
$theaters = $this->parseTheaters();
if (count($theaters) > 0) {
$showDay->setTheaters($theaters);
$showDay->setDate($date);
return $showDay;
}
ret... |
Merges relationships with this instance's relationships.
@param array $toAdd
@return self | private function mergeRelationships(array $toAdd)
{
$this->relationships = array_merge($this->relationships, $toAdd);
ksort($this->relationships);
return $this;
} |
Callback called before any specs processing.
@param array $args The suite arguments array. | public function start($args)
{
parent::start($args);
$this->_dotWidth = max($this->_columns - 11 - strlen($this->_total) * 2, 10);
$this->write("\n");
} |
Form Header.
@param out The html out stream.
@param reg The resources object. | public void printHtmlHeader(PrintWriter out, ResourceBundle reg)
{
String strTitle = this.getProperty("title"); // Menu page
if ((strTitle == null) || (strTitle.length() == 0))
strTitle = ((BasePanel)this.getScreenField()).getTitle();
String strHTMLStart = reg.getS... |
// DEPRECATED: Use EnableAuditWithOptions instead | func (c *Sys) EnableAudit(
path string, auditType string, desc string, opts map[string]string) error {
return c.EnableAuditWithOptions(path, &EnableAuditOptions{
Type: auditType,
Description: desc,
Options: opts,
})
} |
Generates a Dataframe with the predictions for the provided data file.
The data file should contain the text of one observation per row.
@param datasetURI
@return | public Dataframe predict(URI datasetURI) {
//create a dummy dataset map
Map<Object, URI> dataset = new HashMap<>();
dataset.put(null, datasetURI);
TrainingParameters trainingParameters = (TrainingParameters) knowledgeBase.getTrainingParameters();
Dataframe testD... |
Eval.
@param _permissionSet the PermissionSet
@throws EFapsException on error | public static void eval(final PermissionSet _permissionSet)
throws EFapsException
{
Evaluation.LOG.debug("Evaluating PermissionSet {}", _permissionSet);
final Person person = Person.get(_permissionSet.getPersonId());
final Set<Long> ids = new HashSet<>(person.getRoles());
ids... |
// OrElse returns the float64 value or a default value if the value is not present. | func (f Float64) OrElse(v float64) float64 {
if f.Present() {
return *f.value
}
return v
} |
Checks if the class represented by className implements DelegatedFacesServlet.
@param className
@return | private boolean isDelegatedFacesServlet(String className)
{
if (className == null)
{
// The class name can be null if this is e.g., a JSP mapped to
// a servlet.
return false;
}
try
{
Class<?> clazz = Class.forName(className);
... |
Return true if the transport and content negotiators have finished. | public boolean isFullyEstablished() {
boolean result = true;
MediaNegotiator mediaNeg = getMediaNegotiator();
if ((mediaNeg == null) || !mediaNeg.isFullyEstablished()) {
result = false;
}
TransportNegotiator transNeg = getTransportNegotiator();
if ((transNeg... |
Returns the indices that would sort an array.
@param array Array.
@param ascending Ascending order.
@return Array of indices. | public static int[] Argsort(final float[] array, final boolean ascending) {
Integer[] indexes = new Integer[array.length];
for (int i = 0; i < indexes.length; i++) {
indexes[i] = i;
}
Arrays.sort(indexes, new Comparator<Integer>() {
@Override
public in... |
Mark the current job as complete | public function complete()
{
$this->stopped();
$this->setStatus(Job::STATUS_COMPLETE);
$this->redis->zadd(Queue::redisKey($this->queue, 'processed'), time(), $this->payload);
Stats::incr('processed', 1);
Stats::incr('processed', 1, Queue::redisKey($this->queue, 'stats'));
... |
Execute this task.
@throws BuildException Description of the Exception | public function main()
{
if ($this->remove) {
if ($this->name === null || $this->name === "") {
throw new BuildException("The 'name' attribute is required with 'unset'.");
}
$this->removeProperty($this->name);
return;
}
if ($thi... |
Get video params
@return $this | public function getParams()
{
preg_match_all('/https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/', $this->url, $matches);
$id = isset($matches[3][0]) ? $matches[3][0] : false;
$this->params['id'] = $i... |
Looks for handle identifiers in the misc txt of the citation elements
When finding an hdl, creates a new HDL element.
@param citation_elements: (list) elements to process | def look_for_hdl(citation_elements):
for el in list(citation_elements):
matched_hdl = re_hdl.finditer(el['misc_txt'])
for match in reversed(list(matched_hdl)):
hdl_el = {'type': 'HDL',
'hdl_id': match.group('hdl_id'),
'misc_txt': el['misc_... |
Sets a new fault
@param \GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Parts\Fault $fault
@return self | public function setFault(\GoetasWebservices\SoapServices\SoapClient\Envelope\SoapEnvelope12\Parts\Fault $fault)
{
$this->fault = $fault;
return $this;
} |
Remove this remote message filter.
@param messageFilter The message filter to remove.
@param bFreeFilter If true, free the remote filter. | public boolean removeRemoteMessageFilter(BaseMessageFilter messageFilter, boolean bFreeFilter) throws RemoteException
{
BaseTransport transport = this.createProxyTransport(REMOVE_REMOTE_MESSAGE_FILTER);
transport.addParam(FILTER, messageFilter); // Don't use COMMAND
transport.addParam(FREE... |
Set a specific character of the current string.
@param int $offset Offset (can be negative and unbound).
@param string $value Value.
@return self | public function offsetSet($offset, $value)
{
$head = null;
$offset = $this->computeOffset($offset);
if (0 < $offset) {
$head = \mb_substr($this->_string, 0, $offset);
}
$tail = \mb_substr($this->_string, $offset + 1);
$this->_string = $head . $value . $t... |
not publish group action
@param $class
@return boolean | protected function notPublishGroupAction($class)
{
try {
if ( ! $class::whereIn('id', $this->request->id)->update(['is_publish' => false])) {
throw new UpdateException($this->request->id, 'group not not published');
}
event(new $this->events['success']($th... |
Find all snapshots associated with this deployment's lineage | def find_snapshots
unless @lineage
s = @servers.first
kind_params = s.transform_parameters(s.parameters)
@lineage = kind_params['DB_LINEAGE_NAME'].gsub(/text:/, "")
end
snapshots = Ec2EbsSnapshot.find_by_cloud_id(@servers.first.cloud_id).select { |n| n.nickname =~ /#{@lineage}.... |
open file and truncate content
@since 0.9 | public function openWithTruncate()
{
$this->open();
$this->content->truncate(0);
$time = time();
$this->lastAccessed = $time;
$this->lastModified = $time;
} |
Pack a OmemoBundleElement containing our key material.
@param userDevice our OmemoDevice.
@return OmemoBundleElement
@throws CorruptedOmemoKeyException when a key could not be loaded | OmemoBundleElement_VAxolotl packOmemoBundle(OmemoDevice userDevice)
throws CorruptedOmemoKeyException {
int currentSignedPreKeyId = loadCurrentOmemoSignedPreKeyId(userDevice);
T_SigPreKey currentSignedPreKey = loadOmemoSignedPreKeys(userDevice).get(currentSignedPreKeyId);
return ne... |
// Create a backend to be used for L7 load balancing. This L7 pool has backend protocol, L7 members, L7 health monitor and session affinity. L7 pool is associated with L7 policies. | func (r Network_LBaaS_L7Pool) CreateL7Pool(loadBalancerUuid *string, l7Pool *datatypes.Network_LBaaS_L7Pool, l7Members []datatypes.Network_LBaaS_L7Member, l7HealthMonitor *datatypes.Network_LBaaS_L7HealthMonitor, l7SessionAffinity *datatypes.Network_LBaaS_L7SessionAffinity) (resp datatypes.Network_LBaaS_LoadBalancer, e... |
Returns list of annotated methods for given class.
This list will be cached on per-class basis to avoid costly annotations look up. | static List<EventMethod> getMethodsForTarget(@NonNull Object target) {
if (target instanceof Class) {
return getMethodsFromClass((Class<?>) target, true);
} else {
return getMethodsFromClass(target.getClass(), false);
}
} |
A datetime property. | def Datetime(null=True, **kwargs):
""""""
return Property(
types=datetime.datetime,
convert=util.local_timezone,
load=dateutil.parser.parse,
null=null,
**kwargs
) |
Получить значение из запроса | public function fetchValue($sql, $col = null, $values = null, $connection = null)
{
$st = $this->query($sql, $values, $connection);
if (!$row = $st->fetch(\PDO::FETCH_ASSOC)) {
return false;
}
if (!$col) {
return current($row);
}
if (!array_key_exists($col, $row)) {
Except... |
Create a simplified character representation of the data row, which can be pattern matched
with a regex | def picture(self, row):
template = '_Xn'
types = (type(None), binary_type, int)
def guess_type(v):
try:
v = text_type(v).strip()
except ValueError:
v = binary_type(v).strip()
#v = v.decode('ascii', 'replace').str... |
Apply search filters to a SQL query column. Apply collation rules to MySQL.
@param Builder $query
@param Expression|string $field
@param string[] $search_terms | private function whereSearch(Builder $query, $field, array $search_terms): void
{
if ($field instanceof Expression) {
$field = $field->getValue();
}
foreach ($search_terms as $search_term) {
$query->whereContains(DB::raw($field), $search_term);
}
} |
Crumbs
@param array $segments dedd
@return array | public function crumbs($segments)
{
$item = '';
$crumbs = [];
foreach ($segments as $segment):
$item = $item . "/" . $segment;
$crumbs["{$segment}"] = $item;
endforeach;
return $crumbs;
} |
Checks whether the given file is inside the given directory.
@param file the file
@param directory the directory
@return {@literal true} if the file is in the directory (or any subdirectories), {@literal false} otherwise. | public static boolean isInDirectory(File file, File directory) {
try {
return FilenameUtils.directoryContains(directory.getCanonicalPath(), file.getCanonicalPath());
} catch (IOException e) { //NOSONAR
return false;
}
} |
Read - Maps ----- | public function getNameValueMapByType( $parentId, $parentType, $type ) {
$config = [];
$config[ 'conditions' ][ 'parentId' ] = $parentId;
$config[ 'conditions' ][ 'parentType' ] = $parentType;
$config[ 'conditions' ][ 'type' ] = $type;
return $this->getNameValueMap( $config );
} |
Encodes the message into binary format. The resulting binary message is
stored in C{self.rawMessage} | def _marshal(self, newSerial=True, oobFDs=None):
flags = 0
if not self.expectReply:
flags |= 0x1
if not self.autoStart:
flags |= 0x2
# may be overriden below, depending on oobFDs
_headerAttrs = self._headerAttrs
# marshal body before h... |
Double the hash table size and rehash the entries. Assumes total lock. | @SuppressWarnings("unchecked")
void rehash() {
Entry<K,V>[] src = entries;
if (src == null) {
throw new CacheClosedException(cache);
}
int i, sl = src.length, n = sl * 2, _mask = n - 1, idx;
Entry<K,V>[] tab = new Entry[n];
long _count = 0; Entry _next, e;
for (i = 0; i < sl; i++) {
... |
Redirection workaround
See http://www.php.net/manual/ro/function.curl-setopt.php#102121 for more infos.
@return int : redirect count | private function follow()
{
$status = 0;
$redirectCount = 0;
$newurl = $this->url;
$maxRedirect = $this->maxRedirect;
$session = curl_copy_handle($this->session);
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_NOBODY, true);
... |
更新状态
@return array | public function actionUpdateStatus()
{
$ids = \Yii::$app->request->post('ids');
$status = intval(\Yii::$app->request->post('status'));
if ($status != 0) {
$status = 1;
}
foreach (StringHelper::explode($ids, ',', true, true) as $id) {
$obj = DpAdminMenu... |
<p>
Environment Variables for the branch.
</p>
@param environmentVariables
Environment Variables for the branch.
@return Returns a reference to this object so that method calls can be chained together. | public CreateBranchRequest withEnvironmentVariables(java.util.Map<String, String> environmentVariables) {
setEnvironmentVariables(environmentVariables);
return this;
} |
get unique identifier of this container
:return: str | def get_id(self):
if self._id is None:
self._id = graceful_get(self.inspect(refresh=True), "ID")
return self._id |
// NewEndpoint creates a new ipv6 endpoint. | func (p *protocol) NewEndpoint(nicid tcpip.NICID, addr tcpip.Address, linkAddrCache stack.LinkAddressCache, dispatcher stack.TransportDispatcher, linkEP stack.LinkEndpoint) (stack.NetworkEndpoint, *tcpip.Error) {
return &endpoint{
nicid: nicid,
id: stack.NetworkEndpointID{LocalAddress: addr},
... |
Validate the incoming request.
:param request: The incoming :class:`oauth2.web.Request`.
:return: Returns ``True`` if data is valid.
:raises: :class:`oauth2.error.OAuthInvalidError` | def read_validate_params(self, request):
self.refresh_token = request.post_param("refresh_token")
if self.refresh_token is None:
raise OAuthInvalidError(
error="invalid_request",
explanation="Missing refresh_token in request body")
self.clie... |
Assert that key exists in array and it's value not empty.
@param mixed $value
@param string|integer $key
@param string $message
@param string $propertyPath
@return void
@throws Exception | static public function notEmptyKey($value, $key, $message = null, $propertyPath = null)
{
static::keyExists($value, $key, $message, $propertyPath);
static::notEmpty($value[$key], $message, $propertyPath);
} |
Performs lookup on key and returns appropriate replacement string.
@param array $matches Array of 1 el containing key to search for.
@return string Text with which to replace key or value of key if none is found. | private function replaceTokenCallback($matches)
{
$key = $matches[1];
/* Get tokens from tokensource and merge them with the
* tokens given directly via build file. This should be
* done a bit more elegantly
*/
if ($this->_alltokens === null) {
$this->... |
Returns the content to display on course/overview page, formatted and passed through filters
if $options['context'] is not specified, the module context is used
@param array|stdClass $options formatting options, see {@link format_text()}
@return string | public function get_formatted_content($options = array()) {
$this->obtain_view_data();
if (empty($this->content)) {
return '';
}
if ($this->contentisformatted) {
return $this->content;
}
// Improve filter performance by preloading filter setttings... |
对一段文本进行分词,返回list类型的分词结果
Keyword arguments:
lower -- 是否将单词小写(针对英文)
use_stop_words -- 若为True,则利用停止词集合来过滤(去掉停止词)
use_speech_tags_filter -- 是否基于词性进行过滤。若为True,则使用self.default_speech_tag_filter过滤。否则,不过滤。 | def segment(self, text, lower=True, use_stop_words=True, use_speech_tags_filter=False):
jieba_result = cut_for_search(text)
jieba_result = [w for w in jieba_result]
# 去除特殊符号
word_list = [w.strip() for w in jieba_result]
word_list = [word for word in word_list if len(wor... |
/* Get all edit-config tags | function(platform) {
var platform_tag = this.doc.find('./platform[@name="' + platform + '"]');
var platform_edit_configs = platform_tag ? platform_tag.findall('edit-config') : [];
var edit_configs = this.doc.findall('edit-config').concat(platform_edit_configs);
return edit_configs.map(... |
@param array|CloudMessage|Message $message
@throws InvalidArgumentException
@throws InvalidMessage
@return array | public function validate($message): array
{
if (\is_array($message)) {
$message = CloudMessage::fromArray($message);
}
if (!($message instanceof Message)) {
throw new InvalidArgumentException(
'Unsupported message type. Use an array or a class impleme... |
Subsets and Splits
SQL Console for sentence-transformers/codesearchnet
Identifies examples where both requests.get() and beautifulsoup libraries are used together in code comments, revealing common web scraping patterns in the training data.
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.