query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
// hasStatusEnabled returns true if given CRD Subresources has non-nil Status set. | func hasStatusEnabled(subresources *apiextensions.CustomResourceSubresources) bool {
if subresources != nil && subresources.Status != nil {
return true
}
return false
} | csn |
Sets the minimum and preferred resources for this operator. This overrides the default resources.
The lower and upper resource limits will be considered in dynamic resource resize feature for future plan.
@param minResources The minimum resources for this operator.
@param preferredResources The preferred resources for... | private O setResources(ResourceSpec minResources, ResourceSpec preferredResources) {
Preconditions.checkNotNull(minResources, "The min resources must be not null.");
Preconditions.checkNotNull(preferredResources, "The preferred resources must be not null.");
Preconditions.checkArgument(minResources.isValid() && ... | csn |
Add an event to the queue. It will be processed in the order received.
@param event Event | public void addEvent(Event event) {
if(event == null)
throw new IllegalStateException("event must be non-null");
if(logger.isTraceEnabled())
logger.trace("Adding event " + event);
eventQueue.add(event);
} | csn |
remove N chars from tail
@see StringGrabber#carryTail()
@param cnt
count of chars
@return | public StringGrabber removeTail(int cnt) {
int leng = sb.length();
try {
sb.delete(leng - cnt, leng);
} catch (Exception e) {
}
return StringGrabber.this;
} | csn |
Purges a store given its name.
@param string $storename
@param cache_config $config
@return bool | public static function purge_store($storename, cache_config $config = null) {
if ($config === null) {
$config = cache_config::instance();
}
$stores = $config->get_all_stores();
if (!array_key_exists($storename, $stores)) {
// The store does not exist.
... | csn |
Make a matplotlib step plot from a ROOT histogram.
Parameters
----------
h : Hist
A rootpy Hist
logy : bool, optional (default=None)
If True then clip the y range between 1E-300 and 1E300.
If None (the default) then automatically determine if the axes are
log-scale and... | def step(h, logy=None, axes=None, **kwargs):
"""
Make a matplotlib step plot from a ROOT histogram.
Parameters
----------
h : Hist
A rootpy Hist
logy : bool, optional (default=None)
If True then clip the y range between 1E-300 and 1E300.
If None (the default) then auto... | csn |
Spawn a single entity at the specified position.
@param e the actual entity to be spawned.
@param w the world in which to spawn the entity.
@throws Exception | private void DrawPrimitive( DrawEntity e, World w ) throws Exception
{
String oldEntityName = e.getType().getValue();
String id = null;
for (EntityEntry ent : net.minecraftforge.fml.common.registry.ForgeRegistries.ENTITIES)
{
if (ent.getName().equals(oldEntityName))
... | csn |
Collect ids from field of item
@param $item
@param string $field
@return array | protected function collectIdsFromField($item, $field)
{
$ids = Arr::get($item, $field, []);
return is_object($ids) && method_exists($ids, 'toArray') ? $ids->toArray() : (array) $ids;
} | csn |
Answers true if the specified field is a relation of the given object.
@param DataObject $object
@param string $name
@return boolean | public function isRelation(DataObject $object, $name)
{
return (
$this->isHasOneRelation($object, $name) ||
$this->isHasManyRelation($object, $name) ||
$this->isManyManyRelation($object, $name)
);
} | csn |
Returns an array of users in the given conversation.
@return moodle_recordset A moodle_recordset instance. | private function get_unique_users() : moodle_recordset {
global $DB;
$subsql = 'SELECT DISTINCT(useridto) as id
FROM {message_email_messages}
WHERE id <= ?';
$sql = "SELECT *
FROM {user} u
WHERE id IN ($subsql)";
... | csn |
Load a TokenEmbedding. | def load_embedding_from_path(args):
"""Load a TokenEmbedding."""
if args.embedding_path.endswith('.bin'):
with utils.print_time('load fastText model.'):
model = \
nlp.model.train.FasttextEmbeddingModel.load_fasttext_format(
args.embedding_path)
idx... | csn |
P-TMSI REALLOCATION COMMAND Section 9.4.7 | def ptmsiReallocationCommand(PTmsiSignature_presence=0):
"""P-TMSI REALLOCATION COMMAND Section 9.4.7"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0x10) # 00010000
c = MobileId()
d = RoutingAreaIdentification()
e = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c / d / e
if PTmsiSig... | csn |
Give back an array of dicts with the connection
information for all the environments. | def get_login_info():
"""
Give back an array of dicts with the connection
information for all the environments.
"""
connections = {}
_defaults = {}
_defaults['start_in'] = ''
_defaults['rpm_sign_plugin'] = ''
config = _config_file()
_config_test(config)
juicer.utils.Log.lo... | csn |
Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame
@param string $js
@param array $args
@return mixed | public function execute($js, $args = [])
{
$params = ['script' => $js, 'args' => $args];
$result = $this->getDriver()->curl(
$this->getDriver()->factoryCommand('execute', WebDriver_Command::METHOD_POST, $params)
);
return isset($result['value'])?$result['value']:false;
... | csn |
Runs a run in another thread. Non-blocking.
Parameters
----------
run : class, object
Run class or object.
run_conf : str, dict, file
Specific configuration for the run.
use_thread : bool
If True, run run in thread and returns blocking functio... | def run_run(self, run, conf=None, run_conf=None, use_thread=False, catch_exception=True):
'''Runs a run in another thread. Non-blocking.
Parameters
----------
run : class, object
Run class or object.
run_conf : str, dict, file
Specific configuration for t... | csn |
initialize the NameSpaces from the given namespaceList
@param general
@param namespaceList | protected void initNameSpaces(General general, List<Ns> namespaceList) {
namespaces = new LinkedHashMap<String, Ns>();
namespacesById = new LinkedHashMap<Integer, Ns>();
namespacesByCanonicalName = new LinkedHashMap<String, Ns>();
for (Ns namespace : namespaceList) {
String namespacename = namespa... | csn |
Finds closest element matching selector. | function (selector, root) {
if (!isElement(root)) {
return null
}
var Closest = Element.prototype.closest ||
function (sel) {
var element = this;
if (!document.documentElement.contains(element)) {
return null
... | csn |
Unindents the current selected text. | def unindentSelection( self ):
"""
Unindents the current selected text.
"""
sel = self.getSelection()
for line in range(sel[0], sel[2] + 1):
self.unindent(line) | csn |
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words. | def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded) | csn |
Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name | def http_auth_required(realm):
"""Decorator that protects endpoints using Basic HTTP authentication.
:param realm: optional realm name"""
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
if _check_http_auth():
return fn(*args, **kwargs)
if... | csn |
Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date, if it exists.
If a time range is... | def get_dates(self, request):
""" Get available Sentinel-2 acquisitions at least time_difference apart
List of all available Sentinel-2 acquisitions for given bbox with max cloud coverage and the specified
time interval. When a single time is specified the request will return that specific date... | csn |
Validates a GPG key fingerprint
This handles both pre and post GPG 2.1 | def gpg_fingerprint(key):
"""Validates a GPG key fingerprint
This handles both pre and post GPG 2.1"""
if (len(key) == 8 and re.match(r'^[0-9A-F]{8}$', key)) or \
(len(key) == 40 and re.match(r'^[0-9A-F]{40}$', key)):
return
raise aomi.exceptions.Validation('Invalid GPG Fingerprint') | csn |
Sends a binary file to the client skipping rendering
@param file The file to send
@return A response object {@link io.mangoo.routing.Response} | @SuppressFBWarnings(justification = "null check of file on entry point of method", value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
public Response andBinaryFile(Path file) {
Objects.requireNonNull(file, Required.FILE.toString());
try (InputStream inputStream = Files.newInputStream(file)) {
... | csn |
Update load balancer pool
@param loadBalancerPool load balancer pool
@param config load balancer pool config
@return OperationFuture wrapper for load balancer pool | public OperationFuture<LoadBalancerPool> update(LoadBalancerPool loadBalancerPool, LoadBalancerPoolConfig config) {
LoadBalancerPoolMetadata loadBalancerPoolMetadata = findByRef(loadBalancerPool);
loadBalancerPoolClient.update(
loadBalancerPoolMetadata.getDataCenterId(),
loadBal... | csn |
If this is the first call, or there are no results in the resultPeople Set and stopIfFirstDaoReturnsNull=false,
the seed map is used. If not the attributes of the first user in the resultPeople Set are used for each child
dao. If stopIfFirstDaoReturnsNull=true and the first query returned no results in the resultPeopl... | @Override
protected Set<IPersonAttributes> getAttributesFromDao(final Map<String, List<Object>> seed, final boolean isFirstQuery, final IPersonAttributeDao currentlyConsidering, final Set<IPersonAttributes> resultPeople, final IPersonAttributeDaoFilter filter) {
if (isFirstQuery || (!stopIfFirstDaoReturnsNu... | csn |
Get list of fields that are localised
@param string $class Class to get fields for (if parent)
@return array | public function getLocalisedFields($class = null)
{
if (!$class) {
$class = get_class($this->owner);
}
if (isset($this->localisedFields[$class])) {
return $this->localisedFields[$class];
}
// List of DB fields
$fields = DataObject::getSchema()... | csn |
// NewNamespaceInformer constructs a new informer for Namespace type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server. | func NewNamespaceInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredNamespaceInformer(client, resyncPeriod, indexers, nil)
} | csn |
Returns all identifier octets. If an inheriting class models a tag with
the long form identifier format, it MUST reimplement this method to
return all octets of the identifier.
@throws LogicException If the identifier format is long form
@return string Identifier as a set of octets | public function getIdentifier()
{
$firstOctet = $this->getType();
if (Identifier::isLongForm($firstOctet)) {
throw new LogicException(sprintf('Identifier of %s uses the long form and must therefor override "Object::getIdentifier()".', get_class($this)));
}
return chr($f... | csn |
Returns a list of user groups the user belongs to.
The returned list includes the resources for unassigning
a user group if the user is in multiple groups.
@param $userId
@return \eZ\Publish\Core\REST\Server\Values\UserGroupRefList | public function loadUserGroupsOfUser($userId, Request $request)
{
$offset = $request->query->has('offset') ? (int)$request->query->get('offset') : 0;
$limit = $request->query->has('limit') ? (int)$request->query->get('limit') : 25;
$user = $this->userService->loadUser($userId);
$use... | csn |
Check if given absolute path is under given base.
:param path: absolute path
:type path: str
:param base: absolute base path
:type base: str
:param os_sep: path separator, defaults to os.sep
:return: wether file is under given base or not
:rtype: bool | def check_under_base(path, base, os_sep=os.sep):
'''
Check if given absolute path is under given base.
:param path: absolute path
:type path: str
:param base: absolute base path
:type base: str
:param os_sep: path separator, defaults to os.sep
:return: wether file is under given base or... | csn |
Convenience method to add multiple validation rules with an array
@param array $rules
@return $this
@throws \InvalidArgumentException | public function rules(array $rules)
{
foreach ($rules as $ruleType => $params) {
if (\is_array($params)) {
foreach ($params as $innerParams) {
$innerParams = (array) $innerParams;
$this->rule($ruleType, ...$innerParams);
}
... | csn |
Create a new repository and add it to the manager.
@param string $model Model class.
@param array $config Repository configuration.
@return ManagedRepository The created repository.
@throws RepositoryException If the requested repository type is not implemented. | public function createRepository($model, $config)
{
$defaults = [
'type' => 'db-soft',
'key' => 'id',
'deleted' => 'deleted'
];
$config = array_merge($defaults, $config);
switch ($config['type']) {
case 'db':
$r... | csn |
Check that a linear index of a square is within board's bounds. | def validate_index(self, index):
""" Check that a linear index of a square is within board's bounds. """
if index < 0 or index >= self.size:
raise ForbiddenIndex("Linear index {} not in {}x{} board.".format(
index, self.length, self.height)) | csn |
// GetDB set option by name | func (context *Context) GetDB() *gorm.DB {
if context.DB != nil {
return context.DB
}
return context.Widgets.Config.DB
} | csn |
Load all profiles. | def included_profiles(self):
"""Load all profiles."""
profiles = []
for directory in self.tcex_json.get('profile_include_dirs') or []:
profiles.extend(self._load_config_include(directory))
return profiles | csn |
As of December 2nd, 2013, this endpoint is deprecated and retired and no longer functions.
Place creation was used infrequently by third party applications and is generally no longer supported on Twitter.
@param array $parameters
@param bool $multipart
@param bool $appOnlyAuth
@return mixed | public function postGeoPlace(array $parameters = array(), $multipart = false, $appOnlyAuth = false)
{
return $this->post('geo/place', $parameters, $multipart, $appOnlyAuth);
} | csn |
Converts the header of a record to a header node, used for both ListRecords and ListIdentifiers
@param Header $header
@return \DOMElement | private function getRecordHeaderNode(Header $header)
{
$headerNode = $this->response->createElement('header');
$headerNode->appendChild($this->response->createElement('identifier', $header->getIdentifier()));
$headerNode->appendChild(
$this->response->createElement('datestamp', $... | csn |
Automatically compute the number of bins for discrete variables.
Parameters
----------
values = numpy array
values
Returns
-------
array with the bins
Notes
-----
Computes the width of the bins by taking the maximun of the Sturges and the Freedman-Diaconis
estimators. ... | def get_bins(values):
"""
Automatically compute the number of bins for discrete variables.
Parameters
----------
values = numpy array
values
Returns
-------
array with the bins
Notes
-----
Computes the width of the bins by taking the maximun of the Sturges and the ... | csn |
Method to get the department name | def get_dept_name(self):
"""Method to get the department name"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("name", None) | csn |
Returns closest match or just first from possibilities. | def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True):
"""Returns closest match or just first from possibilities."""
possibilities = list(possibilities)
try:
return difflib_get_close_matches(word, possibilities, 1, cutoff)[0]
except IndexError:
if fallback_to_first:
... | csn |
End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.firestore_v1beta1.query.Query.end_at` -- this will... | def end_before(self, document_fields):
"""End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~.... | csn |
Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`manager` agent, e.g. it is a slave
environment... | async def get_artifacts(self, agent=None):
'''Return artifacts published to the environment.
:param agent:
If not ``None``, then returns only artifacts created by the agent.
:returns: All artifacts published (by the agent).
:rtype: list
If environment has a :attr:`... | csn |
// CreateBootstrapConfigMapIfNotExists creates the kube-public ConfigMap if it doesn't exist already | func CreateBootstrapConfigMapIfNotExists(client clientset.Interface, file string) error {
fmt.Printf("[bootstrap-token] Creating the %q ConfigMap in the %q namespace\n", bootstrapapi.ConfigMapClusterInfo, metav1.NamespacePublic)
klog.V(1).Infoln("[bootstrap-token] loading admin kubeconfig")
adminConfig, err := cli... | csn |
Public for unit test | public function extractMantissa($data) {
$signAndExponent = $this->extractSignAndExponentFromData($data);
$mask = ~$signAndExponent;
$mantissa = $data & $mask;
return $mantissa;
} | csn |
If the object is not a Class, get its Class. Otherwise get the object as a Class. If the
class is anonymous, get a non-anonymous enclosing class.
@since 4.0.0 | public static Class<?> getNamedClass(Object obj) {
Class<?> cls = getClass(obj);
while (cls != null && cls.isAnonymousClass()) {
cls = cls.getEnclosingClass();
}
return cls;
} | csn |
Returns the offset constant to this variable. | public static String offsetName(String varName) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, varName) + "_OFFSET";
} | csn |
For each task, ensure all requirements are met. | public function check(array &$errors = null):int {
$count = 0;
foreach($this->taskList as $pathMatch => $task) {
$absolutePathMatch = implode(DIRECTORY_SEPARATOR, [
getcwd(),
$pathMatch,
]);
$fileList = Glob::glob($absolutePathMatch);
if(!empty($fileList)) {
$task->check($errors);
}
... | csn |
scale the matrix
@name scale
@memberOf me.Matrix2d
@function
@param {Number} x a number representing the abscissa of the scaling vector.
@param {Number} [y=x] a number representing the ordinate of the scaling vector.
@return {me.Matrix2d} Reference to this object for method chaining | function (x, y) {
var a = this.val,
_x = x,
_y = typeof(y) === "undefined" ? _x : y;
a[0] *= _x;
a[1] *= _x;
a[3] *= _y;
a[4] *= _y;
return this;
} | csn |
Register a function to be an event handler | def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY
if not isinstance(event, basestring):
# If not basestring, it is a BaseEvent subclass.
# Th... | csn |
Dimensiona il tubo, imponendo uno sforzo tangenziale al fondo.
<p>
<ol>
<li>Calcola l'angolo theta in funzione di g.
<li>Nota la portata di progetto del tratto considerato, determina il
diametro oldD (adottando una pendenza che garantisca l'autopulizia).
<li>Successivamente oldD viene approssimato al diametro commerci... | private double getDiameter( double[][] diameters, double tau, double g, double[] dD, double maxd, StringBuilder strWarnings ) {
/* Pari a A * ( Rh ^1/6 ) */
double B;
/* Anglo formato dalla sezione bagnata */
double thta;
/* Diametro calcolato imponendo il criterio di autopulizia... | csn |
Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] gives atomic forces in
each dis... | def dataset(self, dataset):
"""Set dataset having displacements and optionally forces
Note
----
Elements of the list accessed by 'first_atoms' corresponds to each
displaced supercell. Each displaced supercell contains only one
displacement. dict['first_atoms']['forces'] ... | csn |
Remove CSS class from container
@param string $class
@return Container | public function removeClass($class)
{
$this->setOption(self::OPTION_METHOD, "removeClass");
$this->setOption(self::OPTION_REMOVE_CLASS, $class);
return $this;
} | csn |
Returns the value of an object from a nested schema
@param data Object to map
@param nestedSchema Path to value, function to execute or nested schema
@returns {*}
@private | function _mapDataValue(data, nestedSchema) {
if (typeof nestedSchema === 'function') {
return nestedSchema.apply(data);
} else if (typeof nestedSchema === 'object') {
return _map(data, nestedSchema);
} else {
return _getDataValue(data, nestedSchema);
}
} | csn |
Sets the value of the `XMLElement`. Checks to see
whether the value should be prepended or appended
to the children.
@param string|XMLElement|array $value
Defaults to true. | public function setValue($value)
{
if (is_array($value)) {
$value = implode(', ', $value);
}
if (!is_null($value)) {
$this->_value = $value;
$this->appendChild($value);
}
} | csn |
// GetInt64 returns the result of applying a path to the given Graph.
// The result is returned as an int64. If the path result cannot be converted
// to an integer, then an error is returned. | func (g *Graph) GetInt64(path string) (int64, error) {
if len(path) == 0 {
return g.Int64(), nil
}
i := g.Get(path)
if i == nil {
return 0, errors.New("not found")
}
if i.Len() == 0 {
return 0, errors.New("Get() design error: not subnodes")
}
j, ok := _int64f(i.Out[0].This)
if !ok {
return 0, errors.... | csn |
Returns the projected fields from request. | def get_projected_fields(self, req):
"""
Returns the projected fields from request.
"""
try:
args = getattr(req, 'args', {})
return ','.join(json.loads(args.get('projections')))
except (AttributeError, TypeError):
return None | csn |
Fired when channel is opened
@param e | private void fireOnOpen(ChannelEvent e) {
if (readyState == ReadyState.OPEN) {
// If the channel has already been opened, then we should not fire
// any events.
return;
}
readyState = ReadyState.OPEN;
List<EventListener> listeners = changes.ge... | csn |
// RunCompiled runs an already-compiled mage command with the given args, | func RunCompiled(inv Invocation, exePath string, errlog *log.Logger) int {
debug.Println("running binary", exePath)
c := exec.Command(exePath, inv.Args...)
c.Stderr = inv.Stderr
c.Stdout = inv.Stdout
c.Stdin = inv.Stdin
c.Dir = inv.Dir
// intentionally pass through unaltered os.Environ here.. your magefile has
... | csn |
Ensure that the nodeList is either null or empty.
@param nodeList the nodeList to ensure to be either null or empty
@param expression the expression was used to fine the nodeList
@throws SpinXPathException if the nodeList is either null or empty | public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {
if (nodeList == null || nodeList.getLength() == 0) {
throw LOG.unableToFindXPathExpression(expression);
}
} | csn |
Sets the context properties for SECURITY_PRINCIPAL and SECURITY_CREDENTIAL to perform the lookup. This method is
a convenience for setting the properties SECURITY_PRINCIPAL and SECURITY_CREDENTIAL on the environment.
@param principalName
the principal name to use to perform the lookup
@param credentials
the credential... | public JNDIContentRepositoryBuilder withSecurityPrincipal(final String principalName, final String credentials) {
contextProperties.put(Context.SECURITY_PRINCIPAL, principalName);
contextProperties.put(Context.SECURITY_CREDENTIALS, credentials);
return this;
} | csn |
Removes a specific Embed from a has-many embed collection.
@api
@param string $key The has-many embed key.
@param Embed $embed The embed to remove from the collection.
@return self | public function removeEmbed($key, Embed $embed)
{
if (false === $this->isEmbedHasMany($key)) {
return $this;
}
$this->touch();
$collection = $this->hasManyEmbeds->get($key);
$collection->remove($embed);
$this->doDirtyCheck();
return $this;
} | csn |
Tells if a given value is a valid int.
@param mixed $value
@return ResultInterface Returns Ok if the value is valid, otherwise an Error is returned. | public function validate($value)
{
return is_int($value) ? Ok::unit() : Error::unit([ Error::NON_INT ]);
} | csn |
Mouse has changed position. Move tooltip accordingly
@param {string} event_name
@param {Object} event_object | function(event_name, event_object) {
this._tooltip.set('x', event_object.page.x); // left
this._tooltip.set('y', event_object.page.y); // top
} | csn |
Parse default value for fields with string values.
@param FieldBuilder $field The custom field instance.
@param string $value Value sent to the field.
@return string The field value. | private function parseString(FieldBuilder $field, $value = '')
{
return (empty($value) && isset($field['default'])) ? $field['default'] : $value;
} | csn |
Send a namespace declaration in the output document. The namespace
declaration will not be include if the namespace is already in scope
with the same prefix. | public void namespaceAfterStartElement(
final String prefix,
final String uri)
throws SAXException
{
startPrefixMapping(prefix,uri,false);
} | csn |
Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
... | def get_changes(self, serialized=False, keep=False):
""" Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
... | csn |
In-place location inferring of segments
Returns:
This track | def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring of segments
Returns:
This track
"""... | csn |
cleanup after itself | function clean(done) {
var del = require('del');
del(cfg.destination).then(function () {
if (typeof done === 'function') done();
else process.exit();
});
} | csn |
Creates a deferred rich iterable for the specified iterable | public static <T> LazyIterable<T> adapt(Iterable<T> iterable)
{
return new LazyIterableAdapter<T>(iterable);
} | csn |
Uses SHA-1 to hash the given string and returns the byte array. | public static byte[] stringToSalt(final String string) {
try {
final MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
return digest.digest(string.getBytes("UTF-8"));
} catch (final NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
} catch (final... | csn |
// Free frees the slice data. | func (s *Slice) Free() {
if !s.freed {
C.free(unsafe.Pointer(s.data))
s.freed = true
}
} | csn |
// volumeAttachmentParamsBySource separates the volume attachment parameters by volume source. | func volumeAttachmentParamsBySource(
baseStorageDir string,
params []storage.VolumeAttachmentParams,
registry storage.ProviderRegistry,
) (map[string][]storage.VolumeAttachmentParams, map[string]storage.VolumeSource, error) {
// TODO(axw) later we may have multiple instantiations (sources)
// for a storage provide... | csn |
Appends an operating system pattern to the map of pattern sorted by ID.
@param pattern
a pattern for a browser
@throws net.sf.qualitycheck.exception.IllegalNullArgumentException
if the pattern is {@code null}
@return itself | @Nonnull
public DataBuilder appendOperatingSystemPattern(@Nonnull final OperatingSystemPattern pattern) {
Check.notNull(pattern, "pattern");
if (!operatingSystemPatterns.containsKey(pattern.getId())) {
operatingSystemPatterns.put(pattern.getId(), new TreeSet<OperatingSystemPattern>(OS_PATTERN_COMPARATOR));
}... | csn |
Adds another input to the transaction. | def add_input(txin)
raise ArgumentError, "Input is missing" if !txin
if !(txin.transaction == nil || txin.transaction == self)
raise ArgumentError, "Can't add an input to a transaction when it references another transaction" # sanity check
end
txin.transaction = self
txin.index = @... | csn |
Get a value retrieving callback.
:type value: mixed
:rtype: callable | def _value_retriever(self, value):
"""
Get a value retrieving callback.
:type value: mixed
:rtype: callable
"""
if self._use_as_callable(value):
return value
return lambda item: data_get(item, value) | csn |
Checks to see if there is an exact pattern match for these digits. If so, we should use this
instead of any other formatting template whose leadingDigitsPattern also matches the input.
@return string | public function attemptToFormatAccruedDigits()
{
foreach ($this->possibleFormats as $numberFormat) {
$m = new Matcher($numberFormat->getPattern(), $this->nationalNumber);
if ($m->matches()) {
$nationalPrefixSeparatorsMatcher = new Matcher(self::$nationalPrefixSeparato... | csn |
Un-escapes characters in the given URI-escaped string that do not need
escaping in "-quoted data URIs. | def optimize_quoted_uri_escapes!(escaped)
escaped.gsub!('%3D', '=')
escaped.gsub!('%3A', ':')
escaped.gsub!('%2F', '/')
escaped.gsub!('%27', "'")
escaped.tr!('+', ' ')
end | csn |
// Pack returns a packed byte array which represents a HilControls payload | func (m *HilControls) Pack() []byte {
data := new(bytes.Buffer)
binary.Write(data, binary.LittleEndian, m.TIME_USEC)
binary.Write(data, binary.LittleEndian, m.ROLL_AILERONS)
binary.Write(data, binary.LittleEndian, m.PITCH_ELEVATOR)
binary.Write(data, binary.LittleEndian, m.YAW_RUDDER)
binary.Write(data, binary.Li... | csn |
create a new greenlet from a function and arguments
:param func: the function the new greenlet should run
:type func: function
:param args: any positional arguments for the function
:type args: tuple
:param kwargs: any keyword arguments for the function
:type kwargs: dict or None
the only ... | def greenlet(func, args=(), kwargs=None):
"""create a new greenlet from a function and arguments
:param func: the function the new greenlet should run
:type func: function
:param args: any positional arguments for the function
:type args: tuple
:param kwargs: any keyword arguments for the funct... | csn |
Retrieve annotation values as an array even if there's only one single value
@param string $key A valid annotation tag, should match parser rules
@return array | public function getAsArray($key)
{
if (! $this->has($key)) {
return [];
}
$res = $this->attributes[$key];
if (is_null($res)) {
return [null];
}
return (array) $res;
} | csn |
// Delete takes name of the roleBindingRestriction and deletes it. Returns an error if one occurs. | func (c *FakeRoleBindingRestrictions) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(rolebindingrestrictionsResource, c.ns, name), &authorization.RoleBindingRestriction{})
return err
} | csn |
Iterates over all input channels and collects the average number of queued buffers in a
channel in a best-effort way.
@return average number of queued buffers per channel | float refreshAndGetAvg() {
long total = 0;
int count = 0;
for (InputChannel channel : inputGate.getInputChannels().values()) {
if (channel instanceof RemoteInputChannel) {
RemoteInputChannel rc = (RemoteInputChannel) channel;
int size = rc.unsynchronizedGetNumberOfQueuedBuffers();
total += size;
... | csn |
Ensure our main app container takes up at least the viewport
height | function adjustHeight() {
var windowHeight = $(window).height();
var headerHeight = $("#main-nav").height();
var containerHeight = windowHeight - headerHeight;
$("#main").css("min-height", "" + containerHeight + "px");
} | csn |
Respond with an not found message.
@return Response | public function notFound(): Response
{
$this->response->setStatus(404);
$this->response->setBody('<html><title>404 Not found</title>404 Not found</html>');
return $this->response;
} | csn |
Set MyPy arguments. | def set_mypy_args(self, mypy_args=None):
"""Set MyPy arguments."""
if mypy_args is None:
self.mypy_args = None
else:
self.mypy_errs = []
self.mypy_args = list(mypy_args)
if not any(arg.startswith("--python-version") for arg in mypy_args):
... | csn |
Adds a single-item menu entry. The optional badge can be a subtitle.
@param string Url of item.
@param string Title shown.
@param string Optional, can be an icon, a subtitle or icon placeholder.
@param string Optional, is CSS extra class definition.
@param string Optional, the anchor target. | public function addItem($url, $title, $badge=NULL, $class=NULL, $target=NULL) {
$this->items[] = self::getItemObject($url, $title, $badge, $class, $target);
} | csn |
// ResolveUnitErrors clears errors on one or more units.
// Either specify one or more units, or all. | func (c *Client) ResolveUnitErrors(units []string, all, retry bool) error {
if len(units) > 0 && all {
return errors.NotSupportedf("specifying units with all=true")
}
if len(units) != set.NewStrings(units...).Size() {
return errors.New("duplicate unit specified")
}
args := params.UnitsResolved{
All: all,
... | csn |
Push the info represented by this ``Metric`` to CloudWatch. | def put(self):
"""Push the info represented by this ``Metric`` to CloudWatch."""
try:
self.cloudwatch.put_metric_data(
Namespace=self.namespace,
MetricData=[{
'MetricName': self.name,
'Value': self.value,... | csn |
Add cable to the equipment changes
All changes of equipment are stored in network.results.equipment_changes
which is used later to determine grid expansion costs.
Parameters
----------
network : :class:`~.grid.network.Network`
The eDisGo container object
line : class:`~.grid.components... | def _add_cable_to_equipment_changes(network, line):
"""Add cable to the equipment changes
All changes of equipment are stored in network.results.equipment_changes
which is used later to determine grid expansion costs.
Parameters
----------
network : :class:`~.grid.network.Network`
The ... | csn |
Choose an array value nearest to a specified value.
Useful when we work with time resolutions.
@param int $values
@param int $wantedValue
@return int
@example If the current time is 10 and the time resolution is 15, we have an array of values of [0, 15, 30, 45]: the closest value is 15. | protected function selectNearestValue(array $values, $wantedValue)
{
if (in_array($wantedValue, $values)) {
$result = $wantedValue;
} else {
$result = null;
$minDelta = PHP_INT_MAX;
foreach ($values as $value) {
$delta = abs($value - $w... | csn |
Flash an error message briefly. | function showError(message) {
$(document.createElement('div')).attr({'class': 'popup-error'})
.append($(document.createElement('div'))
.attr({'class': 'error-message'}).text(message))
.appendTo('body')
.fadeIn("slow")
.delay(2000)
.fadeOut("slow");
} | csn |
Calculates the new nonce hash based on the current attributes.
:param new_nonce: the new nonce to be hashed.
:param number: number to prepend before the hash.
:return: the hash for the given new nonce. | def calc_new_nonce_hash(self, new_nonce, number):
"""
Calculates the new nonce hash based on the current attributes.
:param new_nonce: the new nonce to be hashed.
:param number: number to prepend before the hash.
:return: the hash for the given new nonce.
"""
new... | csn |
Unsets the object, property or variable specified by the object path.
@param string $objectPath The object path as a string
@return void | protected function parseValueUnAssignment($objectPath)
{
$objectPathArray = $this->getParsedObjectPath($objectPath);
$this->setValueInObjectTree($objectPathArray, null);
} | csn |
return all element configurations as json string file.
could be further processed by beamline.Lattice class
:param fmt: 'json' (default) or 'dict' | def getAllConfig(self, fmt='json'):
"""
return all element configurations as json string file.
could be further processed by beamline.Lattice class
:param fmt: 'json' (default) or 'dict'
"""
for e in self.getCtrlConf(msgout=False):
self._lattice_c... | csn |
Extracts the public key from the private key.
@param string $private The private key.
@param null|string $passphrase The passphrase.
@return string The public key.
@throws RuntimeException If the public key could not be extracted.
@api | public function extractPublicKey($private, $passphrase = null)
{
$this->clearBufferedMessages();
if (false === ($resource = openssl_pkey_get_private($private, $passphrase))) {
throw new RuntimeException(sprintf(
'The private key could not be processed: %s',
... | csn |
put any object in kubernetes based on URL | def _kput(url, data):
''' put any object in kubernetes based on URL '''
# Prepare headers
headers = {"Content-Type": "application/json"}
# Make request
ret = http.query(url,
method='PUT',
header_dict=headers,
data=salt.utils.json.dumps(... | csn |
Sets the localized bodies of this commerce notification template from the map of locales and localized bodies.
@param bodyMap the locales and localized bodies of this commerce notification template | @Override
public void setBodyMap(Map<java.util.Locale, String> bodyMap) {
_commerceNotificationTemplate.setBodyMap(bodyMap);
} | csn |
Provides a list public IPs for public agents in the cluster | def get_public_agents_public_ip():
"""Provides a list public IPs for public agents in the cluster"""
public_ip_list = []
agents = get_public_agents()
for agent in agents:
status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public")
public_ip_list.appe... | csn |
// ListVolume to get the info of Vsm through a API call to m-apiserver | func (v OpenEBSVolume) ListVolume(vname string, obj interface{}) error {
addr := os.Getenv("MAPI_ADDR")
if addr == "" {
err := errors.New("MAPI_ADDR environment variable not set")
glog.Errorf("Error getting mayaapi-server IP Address: %v", err)
return err
}
url := addr + "/latest/volumes/info/" + vname
glog... | csn |
Program an HMAC-SHA1 OATH-HOTP credential. | def hotp(ctx, slot, key, digits, counter, no_enter, force):
"""
Program an HMAC-SHA1 OATH-HOTP credential.
"""
controller = ctx.obj['controller']
if not key:
while True:
key = click.prompt('Enter a secret key (base32)', err=True)
try:
key = parse_b32_... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.