comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
@return bool Whether the configuration is enabled
@throws InvalidArgumentException When the config is not enableable
|
protected function isConfigEnabled(ContainerBuilder $container, array $config)
{
if (!array_key_exists('enabled', $config)) {
throw new InvalidArgumentException("The config array has no 'enabled' key.");
}
return (bool) $container->getParameterBag()->resolveValue($config['enabled']);
}
|
Computes the output of the given data table array
@param DataTable\Map $table
@param array $allColumns
@return string
|
protected function renderDataTableMap($table, &$allColumns = array())
{
$str = '';
foreach ($table->getDataTables() as $currentLinePrefix => $dataTable) {
$returned = explode("\n", $this->renderTable($dataTable, $allColumns));
// get rid of the columns names
$returned = array_slice($returned, 1);
// case empty datatable we don't print anything in the CSV export
// when in xml we would output <result date="2008-01-15" />
if (!empty($returned)) {
foreach ($returned as &$row) {
$row = $currentLinePrefix . $this->separator . $row;
}
$str .= "\n" . implode("\n", $returned);
}
}
// prepend table key to column list
$allColumns = array_merge(array($table->getKeyName() => true), $allColumns);
// add header to output string
$str = $this->getHeaderLine(array_keys($allColumns)) . $str;
return $str;
}
|
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
|
def encode(self, s):
if isinstance(s, str) and self.needsEncoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s
|
// DestroyMachines removes a given set of machines.
|
func (client *Client) DestroyMachines(machines ...string) ([]params.DestroyMachineResult, error) {
return client.destroyMachines("DestroyMachine", machines)
}
|
$options为是否指定options的string内容,用在允许多次执行里面
|
private function _parseReturn($method, $operate = '', $options = null)
{
if ($operate) $operate = ' ' . $operate . ' ';
$string = (is_null($options) && isset($this->options[$method]['0'])) ? $this->options[$method]['0'] : $options;
if (isset($string)) {
if (in_array($method, array('table', 'join'))) {
$config = Config::config()->{$this->name};
$prefix = $config['prefix'];
unset($config);
$string = preg_replace_callback('/__([A-Z_-]+)__/sU', function ($match) use ($prefix) {
return '`' . $prefix . strtolower($match[1]) . '`';
}, $string);
}
return $operate . $string;
} else
return '';
}
|
Sets the host for this URL.
@param string $host The hostname or IP address for this URL.
@throws InvalidArgumentException If the given host is not an IP address or hostname.
@return void
|
public function setHost($host)
{
if (! (self::_isHostname($host) || self::_isIpAddress($host))) {
throw new InvalidArgumentException("Invalid host ($host)");
}
$this->_host = strtolower(trim($host));
}
|
// SetName sets the Name field's value.
|
func (s *PipelineObject) SetName(v string) *PipelineObject {
s.Name = &v
return s
}
|
// intersect removes positions from e that are not present in x.
|
func (e editSet) intersect(x editSet) {
for pos := range e {
if _, ok := x[pos]; !ok {
delete(e, pos)
}
}
}
|
Attempt to authenticate to the given transport using any of the private
keys available from an SSH agent.
|
def agent_auth(transport, username):
agent = ssh.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
return
for key in agent_keys:
print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()),
try:
transport.auth_publickey(username, key)
print '... success!'
return
except ssh.SSHException:
print '... nope.'
|
This function is similar to read_csv, but it reads data from the
list of <lines>.
fd = open("foo", "r")
data = chart_data.read_str(",", fd.readlines())
|
def read_str(delim=',', *lines):
""""""
data = []
for line in lines:
com = parse_line(line, delim)
data.append(com)
return data
|
<Enabled>true|false</Enabled>
<Days>number-of-days</Days>
|
def _convert_xml_to_retention_policy(xml, retention_policy):
'''
'''
# Enabled
retention_policy.enabled = _bool(xml.find('Enabled').text)
# Days
days_element = xml.find('Days')
if days_element is not None:
retention_policy.days = int(days_element.text)
|
Restores global URL aliases from the backup table.
|
protected function restoreGlobalAliases()
{
$table = static::MIGRATION_TABLE;
$backupTable = static::GLOBAL_ALIAS_BACKUP_TABLE;
if (!$this->tableExists($table)) {
throw new RuntimeException(
"Could not find main URL alias migration table '{$table}'. " .
'Ensure that table exists (you will have to create it manually).'
);
}
if (!$this->tableExists($backupTable)) {
throw new RuntimeException(
"Could not find global URL alias backup table '$backupTable'. " .
"Ensure that table is created by 'backup-global' action."
);
}
$this->doRestoreGlobalAliases();
}
|
// sniffNode sniffs a single node. This method is run as a goroutine
// in sniff. If successful, it returns the list of node URLs extracted
// from the result of calling Nodes Info API. Otherwise, an empty array
// is returned.
|
func (c *Client) sniffNode(url string) []*conn {
nodes := make([]*conn, 0)
// Call the Nodes Info API at /_nodes/http
req, err := NewRequest("GET", url+"/_nodes/http")
if err != nil {
return nodes
}
res, err := c.c.Do((*http.Request)(req))
if err != nil {
return nodes
}
if res == nil {
return nodes
}
if res.Body != nil {
defer res.Body.Close()
}
var info NodesInfoResponse
if err := json.NewDecoder(res.Body).Decode(&info); err == nil {
if len(info.Nodes) > 0 {
switch c.scheme {
case "https":
for nodeID, node := range info.Nodes {
m := reSniffHostAndPort.FindStringSubmatch(node.HTTPSAddress)
if len(m) == 3 {
url := fmt.Sprintf("https://%s:%s", m[1], m[2])
nodes = append(nodes, newConn(nodeID, url))
}
}
default:
for nodeID, node := range info.Nodes {
m := reSniffHostAndPort.FindStringSubmatch(node.HTTPAddress)
if len(m) == 3 {
url := fmt.Sprintf("http://%s:%s", m[1], m[2])
nodes = append(nodes, newConn(nodeID, url))
}
}
}
}
}
return nodes
}
|
stop all Patronis, remove their data directory and cleanup the keys in etcd
|
def after_feature(context, feature):
context.pctl.stop_all()
shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data'))
context.dcs_ctl.cleanup_service_tree()
if feature.status == 'failed':
shutil.copytree(context.pctl.output_dir, context.pctl.output_dir + '_failed')
|
Converts a string to the corresponding log level
|
def string_to_level(log_level):
if (log_level.strip().upper() == "DEBUG"):
return logging.DEBUG
if (log_level.strip().upper() == "INFO"):
return logging.INFO
if (log_level.strip().upper() == "WARNING"):
return logging.WARNING
if (log_level.strip().upper() == "ERROR"):
return logging.ERROR
|
Add translations
@param \Haven\CoreBundle\Entity\CategoryTranslation $translation
@return Category
|
public function addTranslation(\Haven\CoreBundle\Entity\CategoryTranslation $translation) {
$translation->setParent($this);
$this->translations[] = $translation;
return $this;
}
|
入口方法(主方法)
@param {Object} options
|
function commander (options) {
const { cmds, version } = options
const argvs = parseArgs()
if (argvs._.length === 0) {
if (argvs.v || argvs.version) {
process.stdout.write(version + '\n' || 'unknow\n')
process.exit()
} else {
help(options)
}
} else {
const cmd = cmds.filter(function (v) {
return v.command === argvs._[0] || v.aliases === argvs._[0]
})[0]
if (!cmd) {
help(options)
}
cmd.module.handler(argvs)
}
}
|
Sets the classpath.
|
public void setClasspath(String classpath) {
this.classpath = new LinkedList<String>();
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreTokens()) {
this.classpath.add(tokenizer.nextToken());
}
}
|
Convert a given value to a YAML string.
|
def to_yaml(value) -> str:
""""""
stream = yaml.io.StringIO()
dumper = ConfigDumper(stream, default_flow_style=True, width=sys.maxsize)
val = None
try:
dumper.open()
dumper.represent(value)
val = stream.getvalue().strip()
dumper.close()
finally:
dumper.dispose()
return val
|
// DeleteSha256Witness attempts to delete a sha256 preimage identified by hash.
|
func (w *WitnessCache) DeleteSha256Witness(hash lntypes.Hash) error {
return w.deleteWitness(Sha256HashWitness, hash[:])
}
|
Set active = false in offer list, after product was removed
|
protected function processOfferAfterDelete()
{
$obOfferList = $this->obElement->offer;
if ($obOfferList->isEmpty()) {
return;
}
foreach ($obOfferList as $obOffer) {
$obOffer->active = false;
$obOffer->save();
}
}
|
Creates a global IP.
|
def cli(env, ipv6, test):
""""""
mgr = SoftLayer.NetworkManager(env.client)
version = 4
if ipv6:
version = 6
if not (test or env.skip_confirmations):
if not formatting.confirm("This action will incur charges on your "
"account. Continue?"):
raise exceptions.CLIAbort('Cancelling order.')
result = mgr.add_global_ip(version=version, test_order=test)
table = formatting.Table(['item', 'cost'])
table.align['Item'] = 'r'
table.align['cost'] = 'r'
total = 0.0
for price in result['orderDetails']['prices']:
total += float(price.get('recurringFee', 0.0))
rate = "%.2f" % float(price['recurringFee'])
table.add_row([price['item']['description'], rate])
table.add_row(['Total monthly cost', "%.2f" % total])
env.fout(table)
|
Default implementation for {@link Streamable}.
<p>Subclasses can simply add {@code implements Streamable} if they have an implementation in
Sanitizers.<name>Streaming. If they don't, this method will throw while trying to find it.
|
public final AppendableAndOptions applyForJbcSrcStreaming(
JbcSrcPluginContext context, Expression delegateAppendable, List<SoyExpression> args) {
MethodRef sanitizerMethod = javaStreamingSanitizer;
if (sanitizerMethod == null) {
// lazily allocated
sanitizerMethod =
MethodRef.create(
Sanitizers.class,
name.substring(1) + "Streaming",
LoggingAdvisingAppendable.class)
.asNonNullable();
javaStreamingSanitizer = sanitizerMethod;
}
Expression streamingSanitizersExpr = sanitizerMethod.invoke(delegateAppendable);
if (isCloseable()) {
return AppendableAndOptions.createCloseable(streamingSanitizersExpr);
} else {
return AppendableAndOptions.create(streamingSanitizersExpr);
}
}
|
// NewCluster generates a new Cluster object using the provided ClusterOptions object
|
func NewCluster(options *ClusterOptions) (*Cluster, error) {
if options == nil {
options = defaultClusterOptions
}
if options.NodeManager == nil {
options.NodeManager = &defaultNodeManager{}
}
if options.ExecutionAttempts == 0 {
options.ExecutionAttempts = defaultExecutionAttempts
}
c := &Cluster{
executionAttempts: options.ExecutionAttempts,
nodeManager: options.NodeManager,
}
c.initStateData("clusterCreated", "clusterRunning", "clusterShuttingDown", "clusterShutdown", "clusterError")
if options.Nodes == nil {
c.nodes = make([]*Node, 0)
} else {
c.nodes = options.Nodes
}
if options.NoDefaultNode == false && len(c.nodes) == 0 {
defaultNode, nerr := NewNode(nil)
if nerr != nil {
return nil, nerr
}
c.nodes = append(c.nodes, defaultNode)
}
for _, node := range c.nodes {
if node == nil {
return nil, ErrClusterNodesMustBeNonNil
}
}
if options.QueueMaxDepth > 0 {
if options.QueueExecutionInterval == 0 {
options.QueueExecutionInterval = defaultQueueExecutionInterval
}
c.queueCommands = true
c.stopChan = make(chan struct{})
c.cq = newQueue(options.QueueMaxDepth)
c.commandQueueTicker = time.NewTicker(options.QueueExecutionInterval)
go c.executeEnqueuedCommands()
}
c.setState(clusterCreated)
return c, nil
}
|
Enables simple datepicker for input
@return $this
|
public function enableCalendarDatepicker()
{
if (!$this->isEnabledCalendarDatepicker()) {
// First time enabling
PageTail::getInstance()
->addCssUrl('plugins/datepicker/datepicker.css')
->addJsUrl('plugins/datepicker/bootstrap-datepicker.js');
$this->setDateFormat('yyyy-mm-dd');
}
$this->calendar_datepicker_enabled = true;
return $this;
}
|
Find any valid target for "ref()" in the graph by its name and
package name, or None for any package.
|
def find_refable_by_name(self, name, package):
return self._find_by_name(name, package, 'nodes', NodeType.refable())
|
Sets the potential range 0 to 1.
|
def normalize(self):
self.__v = self.__v - np.amin(self.__v)
self.__v = self.__v / np.amax(self.__v)
|
// SetTemplateBody sets the TemplateBody field's value.
|
func (s *CreateApplicationRequest) SetTemplateBody(v string) *CreateApplicationRequest {
s.TemplateBody = &v
return s
}
|
Get the content-type value of http header from the file's extension name.
@param string $name Default file extension name.
@return string content-type
|
public static function getMimetype($name)
{
$parts = explode('.', $name);
if (count($parts) > 1) {
$ext = strtolower(end($parts));
if (isset(self::$mime_types[$ext])) {
return self::$mime_types[$ext];
}
}
return null;
}
|
@param string $subdef_type
@param string $subdef_name
@return databox_subdef
@throws Exception_Databox_SubdefNotFound
|
public function get_subdef($subdef_type, $subdef_name)
{
$type = strtolower($subdef_type);
$name = strtolower($subdef_name);
$group = $this->getSubdefGroup(strtolower($subdef_type));
if (!$group) {
throw new Exception_Databox_SubdefNotFound(sprintf('Databox subdef name `%s` of type `%s` not found', $name, $type));
}
try {
return $group->getSubdef($name);
} catch (RuntimeException $exception) {
throw new Exception_Databox_SubdefNotFound(sprintf('Databox subdef name `%s` of type `%s` not found', $name, $type), $exception);
}
}
|
List default first if it exists
|
def list_available(cls) -> List[str]:
""""""
keys = list(Registrable._registry[cls].keys())
default = cls.default_implementation
if default is None:
return keys
elif default not in keys:
message = "Default implementation %s is not registered" % default
raise ConfigurationError(message)
else:
return [default] + [k for k in keys if k != default]
|
Switch a subField with its previous one
Called when the user clicked on the up arrow of a sortable list
@param {Event} e Original click event
|
function(e) {
var childElement = Event.getTarget(e).parentNode;
var previousChildNode = null;
var nodeIndex = -1;
for(var i = 1 ; i < childElement.parentNode.childNodes.length ; i++) {
var el=childElement.parentNode.childNodes[i];
if(el == childElement) {
previousChildNode = childElement.parentNode.childNodes[i-1];
nodeIndex = i;
break;
}
}
if(previousChildNode) {
// Remove the line
var removedEl = this.childContainer.removeChild(childElement);
// Adds it before the previousChildNode
var insertedEl = this.childContainer.insertBefore(removedEl, previousChildNode);
// Swap this.subFields elements (i,i-1)
var temp = this.subFields[nodeIndex];
this.subFields[nodeIndex] = this.subFields[nodeIndex-1];
this.subFields[nodeIndex-1] = temp;
// Note: not very efficient, we could just swap the names
this.resetAllNames();
// Color Animation
if(this.arrowAnim) {
this.arrowAnim.stop(true);
}
this.arrowAnim = new YAHOO.util.ColorAnim(insertedEl, {backgroundColor: this.arrowAnimColors}, 0.4);
this.arrowAnim.onComplete.subscribe(function() { Dom.setStyle(insertedEl, 'background-color', ''); });
this.arrowAnim.animate();
// Fire updated !
this.fireUpdatedEvt();
}
}
|
Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager:
|
def register_actions(self, shortcut_manager):
shortcut_manager.add_callback_for_action("undo", self.undo)
shortcut_manager.add_callback_for_action("redo", self.redo)
|
Fired to reset all key statuses based on no fingers being on the screen.
@param {Object} event DOM event data including the position touched.
|
function(event) {
this.states.left = false;
this.states.right = false;
this.states.front = false;
this.states.back = false;
event.preventDefault();
event.stopPropagation();
}
|
Loads a Bower asset from the Nails asset module's bower_components directory
@param string $sAsset The asset to unload
@param string $sForceType Force a particular type of asset (i.e. JS or CSS)
@return void
|
protected function unloadNailsBower($sAsset, $sForceType)
{
$sType = $this->determineType($sAsset, $sForceType);
switch ($sType) {
case 'CSS':
unset($this->aCss['NAILS-BOWER-' . $sAsset]);
break;
case 'JS':
unset($this->aJs['NAILS-BOWER-' . $sAsset]);
break;
}
}
|
Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used.
|
def _encode_ndef_uri_type(self, data):
t = 0x0
for (code, prefix) in uri_identifiers:
if data[:len(prefix)].decode('latin-1').lower() == prefix:
t = code
data = data[len(prefix):]
break
data = yubico_util.chr_byte(t) + data
return data
|
Gets range values.
@param AjaxChoiceLoaderInterface $choiceLoader The ajax choice loader
@return int[] The startTo and endTo
|
protected static function getRangeValues(AjaxChoiceLoaderInterface $choiceLoader)
{
$startTo = ($choiceLoader->getPageNumber() - 1) * $choiceLoader->getPageSize();
$startTo = $startTo < 0 ? 0 : $startTo;
$endTo = $startTo + $choiceLoader->getPageSize();
if (0 >= $choiceLoader->getPageSize()) {
$endTo = $choiceLoader->getSize();
}
if ($endTo > $choiceLoader->getSize()) {
$endTo = $choiceLoader->getSize();
}
return [$startTo, $endTo];
}
|
<p>
Same as {@link #prettyTimeFormat()} for the specified locale.
</p>
@param locale
Target locale
@return PrettyTimeFormat instance
@see PrettyTimeFormat
|
public static PrettyTimeFormat prettyTimeFormat(final Locale locale)
{
return withinLocale(new Callable<PrettyTimeFormat>()
{
public PrettyTimeFormat call() throws Exception
{
return context.get().getPrettyTimeFormat();
}
}, locale);
}
|
Send an xmpp message with the data
|
def returner(ret):
'''
'''
_options = _get_options(ret)
from_jid = _options.get('from_jid')
password = _options.get('password')
recipient_jid = _options.get('recipient_jid')
if not from_jid:
log.error('xmpp.jid not defined in salt config')
return
if not password:
log.error('xmpp.password not defined in salt config')
return
if not recipient_jid:
log.error('xmpp.recipient not defined in salt config')
return
message = ('id: {0}\r\n'
'function: {1}\r\n'
'function args: {2}\r\n'
'jid: {3}\r\n'
'return: {4}\r\n').format(
ret.get('id'),
ret.get('fun'),
ret.get('fun_args'),
ret.get('jid'),
pprint.pformat(ret.get('return')))
xmpp = SendMsgBot(from_jid, password, recipient_jid, message)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(block=True)
return True
return False
|
Count lines in a file
|
def count_lines_in(filename):
""
f = open(filename)
lines = 0
buf_size = 1024 * 1024
read_f = f.read # loop optimization
buf = read_f(buf_size)
while buf:
lines += buf.count('\n')
buf = read_f(buf_size)
return lines
|
Extract requested controller key.
In case the key makes sense (we find a matching class) it will be returned.
@return mixed|null
|
protected function getRequestedControllerKey()
{
$return = null;
$requestedControllerKey = $this->getRequest()->getRequestParameter('oePayPalRequestedControllerKey');
if (!empty($requestedControllerKey) &&
\OxidEsales\Eshop\Core\Registry::getControllerClassNameResolver()->getClassNameById($requestedControllerKey)) {
$return = $requestedControllerKey;
}
return $return;
}
|
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated
|
public IfcWindowTypePartitioningEnum createIfcWindowTypePartitioningEnumFromString(EDataType eDataType,
String initialValue) {
IfcWindowTypePartitioningEnum result = IfcWindowTypePartitioningEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
|
Sets the ResourceSegment to the given property of the given document.
@param ResourceSegmentBehavior $document
@param PropertyMetadata $property
|
private function persistDocument(ResourceSegmentBehavior $document, PropertyMetadata $property)
{
$document->getStructure()->getProperty(
$property->getName()
)->setValue($document->getResourceSegment());
}
|
Sets the value to be returned by {@link
org.inferred.freebuilder.processor.property.Property#getBoxedType()}.
@return this {@code Builder} object
|
public org.inferred.freebuilder.processor.property.Property.Builder setNullableBoxedType(
TypeMirror boxedType) {
if (boxedType != null) {
return setBoxedType(boxedType);
} else {
return clearBoxedType();
}
}
|
<p>
A list containing the properties of each job that is returned.
</p>
@param dominantLanguageDetectionJobPropertiesList
A list containing the properties of each job that is returned.
|
public void setDominantLanguageDetectionJobPropertiesList(
java.util.Collection<DominantLanguageDetectionJobProperties> dominantLanguageDetectionJobPropertiesList) {
if (dominantLanguageDetectionJobPropertiesList == null) {
this.dominantLanguageDetectionJobPropertiesList = null;
return;
}
this.dominantLanguageDetectionJobPropertiesList = new java.util.ArrayList<DominantLanguageDetectionJobProperties>(
dominantLanguageDetectionJobPropertiesList);
}
|
Generates the generic spin operator in z basis for a system of
N=particles and for the selected spin index name. where index=0..N-1
The gauge term sets the behavoir for a system away from half-filling
|
def spin_gen(particles, index, gauge=1):
""""""
mat = np.zeros((2**particles, 2**particles))
flipper = 2**index
for i in range(2**particles):
ispin = btest(i, index)
if ispin == 1:
mat[i ^ flipper, i] = 1
else:
mat[i ^ flipper, i] = gauge
return mat
|
// SetToManyReferenceIDs sets the sweets reference IDs and satisfies the jsonapi.UnmarshalToManyRelations interface
|
func (u *User) SetToManyReferenceIDs(name string, IDs []string) error {
if name == "sweets" {
u.ChocolatesIDs = IDs
return nil
}
return errors.New("There is no to-many relationship with the name " + name)
}
|
/* (non-Javadoc)
@see com.popbill.api.CashbillService#issue(java.lang.String, java.lang.String, java.lang.String, java.lang.String)
|
@Override
public Response issue(String CorpNum, String MgtKey, String Memo,
String UserID) throws PopbillException {
if (MgtKey == null || MgtKey.isEmpty())
throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다.");
String PostData = toJsonString(new MemoRequest(Memo));
return httppost("/Cashbill/" + MgtKey, CorpNum, PostData,
UserID, "ISSUE", Response.class);
}
|
Query for TextLogErrorMatches identical to matches of the given TextLogError.
|
def precise_matcher(text_log_error):
""""""
failure_line = text_log_error.metadata.failure_line
logger.debug("Looking for test match in failure %d", failure_line.id)
if failure_line.action != "test_result" or failure_line.message is None:
return
f = {
'text_log_error___metadata__failure_line__action': 'test_result',
'text_log_error___metadata__failure_line__test': failure_line.test,
'text_log_error___metadata__failure_line__subtest': failure_line.subtest,
'text_log_error___metadata__failure_line__status': failure_line.status,
'text_log_error___metadata__failure_line__expected': failure_line.expected,
'text_log_error___metadata__failure_line__message': failure_line.message
}
qwargs = (
Q(text_log_error___metadata__best_classification=None)
& (Q(text_log_error___metadata__best_is_verified=True)
| Q(text_log_error__step__job=text_log_error.step.job))
)
qs = (TextLogErrorMatch.objects.filter(**f)
.exclude(qwargs)
.order_by('-score', '-classified_failure'))
if not qs:
return
# chunk through the QuerySet because it could potentially be very large
# time bound each call to the scoring function to avoid job timeouts
# returns an iterable of (score, classified_failure_id) tuples
chunks = chunked_qs_reverse(qs, chunk_size=20000)
return chain.from_iterable(time_boxed(score_matches, chunks, time_budget=500))
|
Sets and checks that the optional paths, if set, are actually valid.
@param bool $check Whether to check the paths for existence or not.
@throws \Codeception\Exception\ModuleConfigException If one of the paths does not exist.
|
protected function ensureOptionalPaths($check = true)
{
$optionalPaths = [
'themes' => [
'mustExist' => true,
'default' => '/wp-content/themes',
],
'plugins' => [
'mustExist' => true,
'default' => '/wp-content/plugins',
],
'mu-plugins' => [
'mustExist' => false,
'default' => '/wp-content/mu-plugins',
],
'uploads' => [
'mustExist' => true,
'default' => '/wp-content/uploads',
],
];
$wpRoot = Utils::untrailslashit($this->config['wpRootFolder']);
foreach ($optionalPaths as $configKey => $info) {
if (empty($this->config[$configKey])) {
$path = $info['default'];
} else {
$path = $this->config[$configKey];
}
if (!is_dir($path) || ($configKey === 'mu-plugins' && !is_dir(dirname($path)))) {
$path = Utils::unleadslashit(str_replace($wpRoot, '', $path));
$absolutePath = $wpRoot . DIRECTORY_SEPARATOR . $path;
} else {
$absolutePath = $path;
}
if ($check) {
$mustExistAndIsNotDir = $info['mustExist'] && !is_dir($absolutePath);
if ($mustExistAndIsNotDir) {
if (!mkdir($absolutePath, 0777, true) && !is_dir($absolutePath)) {
throw new ModuleConfigException(
__CLASS__,
"The {$configKey} config path [{$path}] does not exist."
);
}
}
}
$this->config[$configKey] = Utils::untrailslashit($absolutePath) . DIRECTORY_SEPARATOR;
}
}
|
// Close stops a Watcher and unlocks its mutex, then sends a close signal.
|
func (w *Watcher) Close() {
w.mu.Lock()
if !w.running {
w.mu.Unlock()
return
}
w.running = false
w.files = make(map[string]os.FileInfo)
w.names = make(map[string]bool)
w.mu.Unlock()
// Send a close signal to the Start method.
w.close <- struct{}{}
}
|
// HasFailures return true is there's at least one failing suite
|
func (s Suites) HasFailures() bool {
for _, suite := range s {
if suite.NumFailed() > 0 {
return true
}
}
return false
}
|
Handle a file modified event.
|
def on_modified(self, event):
""""""
path = event.src_path
if path not in self.saw:
self.saw.add(path)
self.recompile(path)
|
Unset an item
@param string | int $key
@return Collection
|
public function unsetItem($key) {
if (is_array($key)) {
$key = $this->arrayHashFunction($key);
}
if (! isset($this->_data[$key])) {
return;
}
unset($this->_data[$key], $this->_models[$key]);
$this->_map = array_keys($this->_data);
return $this;
}
|
Performs the Security and Export Change.<p>
@throws JspException if including a JSP sub element is not successful
|
public void actionChangeSecureExport() throws JspException {
// save initialized instance of this class in request attribute for included sub-elements
getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this);
String filename = getParamResource();
try {
// lock resource if auto lock is enabled
checkLock(getParamResource());
// write the properties
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORT, getParamExport());
writeProperty(CmsPropertyDefinition.PROPERTY_EXPORTNAME, getParamExportname());
writeProperty(CmsPropertyDefinition.PROPERTY_SECURE, getParamSecure());
// change the flag of the resource so that it is internal
CmsResource resource = getCms().readResource(filename, CmsResourceFilter.IGNORE_EXPIRATION);
if (resource.isInternal() && !Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() & (~CmsResource.FLAG_INTERNAL));
} else if (!resource.isInternal() && Boolean.valueOf(getParamIntern()).booleanValue()) {
getCms().chflags(filename, resource.getFlags() | CmsResource.FLAG_INTERNAL);
}
actionCloseDialog();
} catch (Throwable e) {
// error during change of secure settings, show error dialog
includeErrorpage(this, e);
}
}
|
Parses an SQL string into a JS object given the friendly type.
|
function parseSQLVal(type, val) {
if (val == 'NULL') {
return null;
}
switch (type) {
case 'datetime':
case 'timestamp':
if (val == 'CURRENT_TIMESTAMP') {
return val;
} else if (val == '0000-00-00 00:00:00') {
// HACK(arlen): Not sure if this is correct, but constructing
// a Date out of this yields "Invalid Date".
return null;
} else {
return new Date(val);
}
case 'text':
case 'string':
return val;
case 'integer':
case 'primary_key':
return parseInt(val);
case 'float':
return parseFloat(val);
case 'boolean':
return (val == "TRUE");
default:
throw "Unknown friendly type `" + type + "`!";
}
}
|
Connects the TeamSpeak3_Transport_Abstract object and performs initial actions on the remote
server.
@throws TeamSpeak3_Adapter_Update_Exception
@return void
|
public function syn()
{
if(!isset($this->options["host"]) || empty($this->options["host"])) $this->options["host"] = $this->default_host;
if(!isset($this->options["port"]) || empty($this->options["port"])) $this->options["port"] = $this->default_port;
$this->initTransport($this->options, "TeamSpeak3_Transport_UDP");
$this->transport->setAdapter($this);
TeamSpeak3_Helper_Profiler::init(spl_object_hash($this));
$this->getTransport()->send(TeamSpeak3_Helper_String::fromHex(33));
if(!preg_match_all("/,?(\d+)#([0-9a-zA-Z\._-]+),?/", $this->getTransport()->read(96), $matches) || !isset($matches[1]) || !isset($matches[2]))
{
throw new TeamSpeak3_Adapter_Update_Exception("invalid reply from the server");
}
$this->build_datetimes = $matches[1];
$this->version_strings = $matches[2];
TeamSpeak3_Helper_Signal::getInstance()->emit("updateConnected", $this);
}
|
// InvalidCollectionFormat another flavor of invalid type error
|
func InvalidCollectionFormat(name, in, format string) *Validation {
return &Validation{
code: InvalidTypeCode,
Name: name,
In: in,
Value: format,
message: fmt.Sprintf("the collection format %q is not supported for the %s param %q", format, in, name),
}
}
|
Get the url to the directory containing responsive images.
@return string
|
public function getResponsiveImagesDirectoryUrl(): string
{
return url($this->getBaseMediaDirectoryUrl().'/'.$this->pathGenerator->getPathForResponsiveImages($this->media)).'/';
}
|
Configures a {@link TransformerFactory} to protect it against XML
External Entity attacks.
@param factory the factory
@see <a href=
"https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet#Java">
XXE Cheat Sheet</a>
|
public static void applyXXEProtection(TransformerFactory factory) {
//@formatter:off
String[] attributes = {
//XMLConstants.ACCESS_EXTERNAL_DTD (Java 7 only)
"http://javax.xml.XMLConstants/property/accessExternalDTD",
//XMLConstants.ACCESS_EXTERNAL_STYLESHEET (Java 7 only)
"http://javax.xml.XMLConstants/property/accessExternalStylesheet"
};
//@formatter:on
for (String attribute : attributes) {
try {
factory.setAttribute(attribute, "");
} catch (IllegalArgumentException e) {
//attribute is not supported by the local XML engine, skip it
}
}
}
|
Checks if payment used for current order is available and active.
Throws exception if not available
@param \OxidEsales\Eshop\Application\Model\Basket $oBasket basket object
@return null
|
public function validatePayment($oBasket)
{
$paymentId = $oBasket->getPaymentId();
if (!$this->isValidPaymentId($paymentId) || !$this->isValidPayment($oBasket)) {
return self::ORDER_STATE_INVALIDPAYMENT;
}
}
|
检验auth数组正确性
@param array
@return null or die
|
public function checkAuthArray($array)
{
//root
if(array_has($array, 'root')){
if(array_get($array, 'root') != 'only') {
die('FooWeChat\Authorize\Auth\checkAuthArray: 参数 root 值错误');
}
}
//admin
if(array_has($array, 'admin')){
$a = array_get($array, 'admin');
if($a != 'yes' && $a != 'no' && $a != 'only') {
die('FooWeChat\Authorize\Auth\checkAuthArray: 参数 admin 值错误');
}
}
//way
if(array_has($array, 'way')){
$a = array_get($array, 'way');
if($a != 'wechat' && $a != 'web' && $a != 'all') {
die('FooWeChat\Authorize\Auth\checkAuthArray: 参数 way 值错误');
}
}
//except
if(array_has($array, 'except')){
$this->checkUser(array_get($array, 'except'));
}
//user
if(array_has($array, 'user')){
$this->checkUser(array_get($array, 'user'));
}
}
|
Transliterate an Unicode object into an ASCII string.
@param str Unicode String to transliterate.
@return ASCII string.
|
public static String decode(final String str) {
if (str == null) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int codepoint = str.codePointAt(i);
// Basic ASCII
if (codepoint < 0x80) {
sb.append(c);
continue;
}
// Characters in Private Use Area and above are ignored
if (codepoint > 0xffff)
continue;
int section = codepoint >> 8; // Chop off the last two hex digits
int position = codepoint % 256; // Last two hex digits
String[] table = getCache(section);
if (table != null && table.length > position) {
sb.append(table[position]);
}
}
return sb.toString().trim();
}
|
Find the closest WApplication instance.
@return the closest WApplication instance
|
private WApplication findApplication() {
WApplication appl = WApplication.instance(this);
if (appl == null) {
messages.addMessage(new Message(Message.WARNING_MESSAGE,
"There is no WApplication available for this example."));
}
return appl;
}
|
// DeleteAssets implements github.com/keybase/go/chat/storage/storage.AssetDeleter interface.
|
func (s *baseConversationSource) DeleteAssets(ctx context.Context, uid gregor1.UID,
convID chat1.ConversationID, assets []chat1.Asset) {
defer s.Trace(ctx, func() error { return nil }, "DeleteAssets: %v", assets)()
if len(assets) == 0 {
return
}
// Fire off a background load of the thread with a post hook to delete the bodies cache
s.G().ConvLoader.Queue(ctx, types.NewConvLoaderJob(convID, nil /*query*/, nil /*pagination*/, types.ConvLoaderPriorityHigh,
func(ctx context.Context, tv chat1.ThreadView, job types.ConvLoaderJob) {
fetcher := s.G().AttachmentURLSrv.GetAttachmentFetcher()
if err := fetcher.DeleteAssets(ctx, convID, assets, s.ri, s); err != nil {
s.Debug(ctx, "Error purging ephemeral attachments %v", err)
}
}))
}
|
Call multiple external functions and return all responses.
@param array $requests List of requests.
@return array Responses.
@since Moodle 3.7
|
public static function call_external_functions($requests) {
global $SESSION;
$params = self::validate_parameters(self::call_external_functions_parameters(), ['requests' => $requests]);
// We need to check if the functions being called are included in the service of the current token.
// This function only works when using mobile services via REST (this is intended).
$webservicemanager = new \webservice;
$token = $webservicemanager->get_user_ws_token(required_param('wstoken', PARAM_ALPHANUM));
$settings = \external_settings::get_instance();
$defaultlang = current_language();
$responses = [];
foreach ($params['requests'] as $request) {
// Some external functions modify _GET or $_POST data, we need to restore the original data after each call.
$originalget = fullclone($_GET);
$originalpost = fullclone($_POST);
// Set external settings and language.
$settings->set_raw($request['settingraw']);
$settings->set_filter($request['settingfilter']);
$settings->set_fileurl($request['settingfileurl']);
$settings->set_lang($request['settinglang']);
$SESSION->lang = $request['settinglang'] ?: $defaultlang;
// Parse arguments to an array, validation is done in external_api::call_external_function.
$args = @json_decode($request['arguments'], true);
if (!is_array($args)) {
$args = [];
}
if ($webservicemanager->service_function_exists($request['function'], $token->externalserviceid)) {
$response = external_api::call_external_function($request['function'], $args, false);
} else {
// Function not included in the service, return an access exception.
$response = [
'error' => true,
'exception' => [
'errorcode' => 'accessexception',
'module' => 'webservice'
]
];
if (debugging('', DEBUG_DEVELOPER)) {
$response['exception']['debuginfo'] = 'Access to the function is not allowed.';
}
}
if (isset($response['data'])) {
$response['data'] = json_encode($response['data']);
}
if (isset($response['exception'])) {
$response['exception'] = json_encode($response['exception']);
}
$responses[] = $response;
// Restore original $_GET and $_POST.
$_GET = $originalget;
$_POST = $originalpost;
if ($response['error']) {
// Do not process the remaining requests.
break;
}
}
return ['responses' => $responses];
}
|
// Error can be either of the following types:
//
// - InvalidObjectFault
// - RuntimeFault
|
func (service *VboxPortType) IFilequeryInfo(request *IFilequeryInfo) (*IFilequeryInfoResponse, error) {
response := new(IFilequeryInfoResponse)
err := service.client.Call("", request, response)
if err != nil {
return nil, err
}
return response, nil
}
|
Substitutes a free type variable with an actual type. See {@link GenericType this class's
javadoc} for an example.
|
@NonNull
public final <X> GenericType<T> where(
@NonNull GenericTypeParameter<X> freeVariable, @NonNull GenericType<X> actualType) {
TypeResolver resolver =
new TypeResolver().where(freeVariable.getTypeVariable(), actualType.__getToken().getType());
Type resolvedType = resolver.resolveType(this.token.getType());
@SuppressWarnings("unchecked")
TypeToken<T> resolvedToken = (TypeToken<T>) TypeToken.of(resolvedType);
return new GenericType<>(resolvedToken);
}
|
// SetMaxResults sets the MaxResults field's value.
|
func (s *ListTopicRulesInput) SetMaxResults(v int64) *ListTopicRulesInput {
s.MaxResults = &v
return s
}
|
//Initialize sets new logger which takes over logging operations.
//It is required to call this function before making any loggings.
|
func Initialize(l api.LoggerProvider) {
loggerProviderOnce.Do(func() {
loggerProviderInstance = l
logger := loggerProviderInstance.GetLogger(loggerModule)
logger.Debug("Logger provider initialized")
// TODO
// use custom leveler implementation (otherwise fallback to default)
// levelerProvider, ok := loggingProvider.(apilogging.Leveler)
// if !ok {
// }
})
}
|
Returns temp path.
@return string
|
public function getTempDirectory()
{
if (!file_exists($this->tempDirectory)) {
mkdir($this->tempDirectory, 0777);
chmod($this->tempDirectory, 0777);
}
return $this->tempDirectory;
}
|
this will retrieve the export object, using Linz's default export handler amongst custom export handlers this is based on the knowledge that only Linz's default export handler can have an `action` of `export` `exports` should be model.list.export
|
function (exports) {
var exp = undefined;
// retrieve the export object
exports.forEach(function (_export) {
// Linz's default export function is called export
if (_export.action && _export.action === 'export') {
exp = _export;
}
});
// if the export object could not be found, throw an error
if (!exp) {
throw new Error('The export was using Linz default export method, yet the model\'s list.export object could not be found.');
}
return exp;
}
|
Returns the type of the class a node is contained in
Returns null if the class is anonymous or the node is not contained in a class
@param Node $node The node used to find the containing class
@return Types\Object_|null
|
private function getContainingClassType(Node $node)
{
$classFqn = $this->getContainingClassFqn($node);
return $classFqn ? new Types\Object_(new Fqsen('\\' . $classFqn)) : null;
}
|
Redraw the series after an update in the axes.
|
function () {
var series = this,
chart = series.chart,
wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
if (series.setTooltipPoints) {
series.setTooltipPoints(true);
}
series.render();
if (wasDirtyData) {
fireEvent(series, 'updatedData');
}
}
|
Send a batch of messages
:param str topic: a kafka topic
:param ksr.transport.Message kmsgs: Messages to serialize
:param int timeout: Timeout in seconds
:return: Execution result
:rtype: kser.result.Result
|
def bulk_send(self, topic, kmsgs, timeout=60):
try:
for kmsg in kmsgs:
self.client.send(
topic, self._onmessage(kmsg).dumps().encode("UTF-8")
)
self.client.flush(timeout=timeout)
return Result(stdout="{} message(s) sent".format(len(kmsgs)))
except Exception as exc:
return Result.from_exception(exc)
|
Returns common ancestor for paths represented by absolute path and pattern.
|
public static String extractCommonAncestor(String pattern, String absPath)
{
pattern = normalizePath(pattern);
absPath = normalizePath(absPath);
String[] patterEntries = pattern.split("/");
String[] pathEntries = absPath.split("/");
StringBuilder ancestor = new StringBuilder();
int count = Math.min(pathEntries.length, patterEntries.length);
for (int i = 1; i < count; i++)
{
if (acceptName(patterEntries[i], pathEntries[i]))
{
ancestor.append("/");
ancestor.append(pathEntries[i]);
}
else
{
break;
}
}
return ancestor.length() == 0 ? JCRPath.ROOT_PATH : ancestor.toString();
}
|
// Fill scales the image to the smallest possible size that will cover the specified dimensions,
// crops the resized image to the specified dimensions using the given anchor point.
// Space delimited config: 200x300 TopLeft
|
func (i *Image) Fill(spec string) (*Image, error) {
return i.doWithImageConfig("fill", spec, func(src image.Image, conf imageConfig) (image.Image, error) {
if conf.AnchorStr == smartCropIdentifier {
return smartCrop(src, conf.Width, conf.Height, conf.Anchor, conf.Filter)
}
return imaging.Fill(src, conf.Width, conf.Height, conf.Anchor, conf.Filter), nil
})
}
|
<p>
Additional metadata about the event.
</p>
@param eventMetadata
Additional metadata about the event.
@return Returns a reference to this object so that method calls can be chained together.
|
public EventDetails withEventMetadata(java.util.Map<String, String> eventMetadata) {
setEventMetadata(eventMetadata);
return this;
}
|
Get messagearea search users returns.
@deprecated since 3.6
@return external_single_structure
@since 3.2
|
public static function data_for_messagearea_search_users_returns() {
return new external_single_structure(
array(
'contacts' => new external_multiple_structure(
self::get_messagearea_contact_structure()
),
'courses' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'The course id'),
'shortname' => new external_value(PARAM_TEXT, 'The course shortname'),
'fullname' => new external_value(PARAM_TEXT, 'The course fullname'),
)
)
),
'noncontacts' => new external_multiple_structure(
self::get_messagearea_contact_structure()
)
)
);
}
|
Registers helpers accessible by any template in the environment
@param string|array|object $name
@param string|callable|bool $helper
|
public function registerHelper($name, $helper = false)
{
if (is_array($name)) {
foreach ($name as $n => $helper) {
$this->registerHelper($n, $helper);
}
} elseif (is_object($name)) {
$this->registerJavascriptObject('helper', $this->wrapHelperObject($name));
} elseif ($helper === false) {
$this->registerJavascriptObject('helper', $name);
} elseif (is_callable($helper)) {
$this->registerJavascriptFunction('helper', $name, $this->wrapHelperCallable($name, $helper));
} else {
$this->registerJavascriptFunction('helper', $name, $helper);
}
}
|
Get a Jvm property / environment variable
@param prop the property to get
@return the property value
|
public static String getJvmProperty(String prop) {
return (System.getProperty(prop, System.getenv(prop)));
}
|
//----------------------------------------
|
func stripPrefix(key []byte, prefix []byte) (stripped []byte) {
if len(key) < len(prefix) {
panic("should not happen")
}
if !bytes.Equal(key[:len(prefix)], prefix) {
panic("should not happne")
}
return key[len(prefix):]
}
|
URL组装(带域名端口) 支持不同URL模式
eg: \Cml\Http\Response::fullUrl('Home/Blog/cate/id/1')
@param string $url URL表达式 路径/控制器/操作/参数1/参数1值/.....
@param bool $echo 是否输出 true输出 false return
@return string
|
public static function fullUrl($url = '', $echo = true)
{
$url = Request::baseUrl() . self::url($url, false);
if ($echo) {
echo $url;
return '';
} else {
return $url;
}
}
|
// NewFxFooYARPCProcedures provides FooYARPCServer procedures to an Fx application.
// It expects a FooYARPCServer to be present in the container.
//
// fx.Provide(
// examplepb.NewFxFooYARPCProcedures(),
// ...
// )
|
func NewFxFooYARPCProcedures() interface{} {
return func(params FxFooYARPCProceduresParams) FxFooYARPCProceduresResult {
return FxFooYARPCProceduresResult{
Procedures: BuildFooYARPCProcedures(params.Server),
ReflectionMeta: reflection.ServerMeta{
ServiceName: "uber.yarpc.internal.examples.protobuf.example.Foo",
FileDescriptors: yarpcFileDescriptorClosure43929dec9f67b739,
},
}
}
}
|
// Through will check if we should fallthrough for qname. Note that we've named the
// variable in each plugin "Fall", so this then reads Fall.Through().
|
func (f F) Through(qname string) bool {
return plugin.Zones(f.Zones).Matches(qname) != ""
}
|
singelton constructor
@param mixed $database
@return Pool
|
public static function getInstance($database = null)
{
if (self::$instance instanceof Pool) {
self::$instance->add($database);
return self::$instance;
}
self::$instance = new Pool($database);
return self::$instance;
}
|
Method to deserialize the BatchItemResponse object
@param jsonNode the json node
@return BatchItemResponse the batch item response
|
private BatchItemResponse getBatchItemResponse(JsonNode jsonNode) throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("BatchItemResponseDeserializer", new Version(1, 0, 0, null));
simpleModule.addDeserializer(BatchItemResponse.class, new BatchItemResponseDeserializer());
mapper.registerModule(simpleModule);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.treeToValue(jsonNode, BatchItemResponse.class);
}
|
/*
(non-Javadoc)
@see sfdc.adt.IParser#parse(java.lang.String, java.io.Reader)
|
@Override
public ParseResult parse(final Source source) {
return Util.execute(new ExceptionAction<ParseResult>() {
@Override
public ParseResult doAction() throws Throwable {
logger.fine("Parsing " + source.getSrcInfo());
final BufferedReader reader = source.createReader();
try {
final ParserImpl impl = factory.create(source.getSrcInfo(),
reader);
final Doc doc = impl.doc();
return new ParseResult(doc, impl.errors());
} finally {
reader.close();
}
}
});
}
|
Adds the false positive to description and changes severity to low
|
def _set_internal_compiler_error(self):
self.severity = "Low"
self.description_tail += (
" This issue is reported for internal compiler generated code."
)
self.description = "%s\n%s" % (self.description_head, self.description_tail)
self.code = ""
|
Loads container of elements from the reader. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:return:
|
async def _load_container(
self, reader, container_type, params=None, container=None
):
c_len = (
container_type.SIZE
if container_type.FIX_SIZE
else await load_uvarint(reader)
)
if container and get_elem(container) and c_len != len(container):
raise ValueError("Size mismatch")
elem_type = container_elem_type(container_type, params)
res = container if container else []
for i in range(c_len):
try:
self.tracker.push_index(i)
fvalue = await self.load_field(
reader,
elem_type,
params[1:] if params else None,
eref(res, i) if container else None,
)
self.tracker.pop()
except Exception as e:
raise helpers.ArchiveException(e, tracker=self.tracker) from e
if not container:
res.append(fvalue)
return res
|
Returns a valid timeout value. Non positive values are converted to null,
meaning no timeout.
@return float|null
@throws \InvalidArgumentException
|
private function getTimeout(): ?float
{
if (! is_numeric($this->option('timeout'))) {
throw new \InvalidArgumentException('The timeout value must be a number.');
}
$timeout = (float) $this->option('timeout');
return $timeout > 0 ? $timeout : null;
}
|
// nodePathLock returns an etcd directory path used specifically for semaphore
// indices based on the given key.
|
func (b *Etcd2Backend) nodePathLock(key string) string {
return filepath.Join(b.path, filepath.Dir(key), Etcd2NodeLockPrefix+filepath.Base(key)+"/")
}
|
Stops the profiling.
@param StopwatchEvent $event A stopwatchEvent instance
|
protected function stopProfiling(StopwatchEvent $event = null)
{
if ($this->stopwatch instanceof Stopwatch) {
$event->stop();
$values = [
'duration' => $event->getDuration(),
'memory_end' => memory_get_usage(true),
'memory_peak' => memory_get_peak_usage(true),
];
$this->profiles[$this->counter] = array_merge($this->profiles[$this->counter], $values);
$this->counter++;
}
}
|
// DestinationAddress returns the "destination address" field of the ipv6
// header.
|
func (b IPv6) DestinationAddress() tcpip.Address {
return tcpip.Address(b[v6DstAddr : v6DstAddr+IPv6AddressSize])
}
|
Releases a named lock.
@param string $lockName The lock name.
@return bool `true` if the lock was released, `false` if otherwise.
|
public static function releaseDbLock($lockName)
{
$sql = 'SELECT RELEASE_LOCK(?)';
$db = self::get();
return $db->fetchOne($sql, array($lockName)) == '1';
}
|
// SetPath sets the Path field's value.
|
func (s *CreateGroupInput) SetPath(v string) *CreateGroupInput {
s.Path = &v
return s
}
|
Check or set if we have recieved an exit request
@param bool $requested Have we received the request? (optional).
@return current exit request status
|
public function received_exit_request($requested = null)
{
// if we are retreiving the value of the exit request
if ($requested === null)
{
return $this->exit_request_status;
}
// ensure we have good data, or set to false if not
if (!is_bool($requested))
{
$requested = false;
}
// set and return the ne value
return ($this->exit_request_status = $requested);
}
|
Adds rules from the module/config/routes.php file
@return
|
private function addModuleRules()
{
// Load the routes from cache
$moduleRoutes = array();
$directories = glob(Yii::getPathOfAlias('application.modules') . '/*' , GLOB_ONLYDIR);
foreach ($directories as $dir)
{
$routePath = $dir .DS. 'config' .DS. 'routes.php';
if (file_exists($routePath))
{
$routes = require_once($routePath);
// Unit tests are failing here for some reason
if (!is_array($routes))
continue;
foreach ($routes as $k=>$v)
$moduleRoutes[$k] = $v;
}
}
return $moduleRoutes;
}
|
// Select allows to query only fields passed as parameter.
// c.Select("field1", "field2").All(&model)
// => SELECT field1, field2 FROM models
|
func (q *Query) Select(fields ...string) *Query {
for _, f := range fields {
if strings.TrimSpace(f) != "" {
q.addColumns = append(q.addColumns, f)
}
}
return q
}
|
Check whether an element is outside of all hidden selectors.
@private
@param {Object} issue - The issue to check.
@returns {Boolean} Returns whether the issue is outside of a hidden area.
|
function isElementOutsideHiddenArea(issue) {
const hiddenElements = [...window.document.querySelectorAll(options.hideElements)];
return !hiddenElements.some(hiddenElement => {
return hiddenElement.contains(issue.element);
});
}
|
Subsets and Splits
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.