comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Returns the version of marathon on marathon. | def mom_version(name='marathon-user'):
if service_available_predicate(name):
with marathon_on_marathon(name):
return marathon_version()
else:
# We can either skip the corresponding test by returning False
# or raise an exception.
print('WARN: {} MoM not found. Version is None'.format(name))
return None |
// ConvertWorkItemLinkTypeToModel converts the incoming app representation of a work item link type to the model layout.
// Values are only overwrriten if they are set in "in", otherwise the values in "out" remain. | func ConvertWorkItemLinkTypeToModel(appLinkType app.WorkItemLinkTypeSingle) (*link.WorkItemLinkType, error) {
modelLinkType := link.WorkItemLinkType{}
if appLinkType.Data == nil {
return nil, errors.NewBadParameterError("data", nil).Expected("not <nil>")
}
if appLinkType.Data.Attributes == nil {
return nil, errors.NewBadParameterError("data.attributes", nil).Expected("not <nil>")
}
if appLinkType.Data.Relationships == nil {
return nil, errors.NewBadParameterError("data.relationships", nil).Expected("not <nil>")
}
attrs := appLinkType.Data.Attributes
rel := appLinkType.Data.Relationships
if appLinkType.Data.ID != nil {
modelLinkType.ID = *appLinkType.Data.ID
}
if attrs != nil {
// If the name is not nil, it MUST NOT be empty
if attrs.Name != nil {
if *attrs.Name == "" {
return nil, errors.NewBadParameterError("data.attributes.name", *attrs.Name)
}
modelLinkType.Name = *attrs.Name
}
modelLinkType.Description = attrs.Description
modelLinkType.ForwardDescription = attrs.ForwardDescription
modelLinkType.ReverseDescription = attrs.ReverseDescription
if attrs.Version != nil {
modelLinkType.Version = *attrs.Version
}
// If the forwardName is not nil, it MUST NOT be empty
if attrs.ForwardName != nil {
if *attrs.ForwardName == "" {
return nil, errors.NewBadParameterError("data.attributes.forward_name", *attrs.ForwardName)
}
modelLinkType.ForwardName = *attrs.ForwardName
}
// If the ReverseName is not nil, it MUST NOT be empty
if attrs.ReverseName != nil {
if *attrs.ReverseName == "" {
return nil, errors.NewBadParameterError("data.attributes.reverse_name", *attrs.ReverseName)
}
modelLinkType.ReverseName = *attrs.ReverseName
}
if attrs.Topology != nil {
modelLinkType.Topology = link.Topology(*attrs.Topology)
if err := modelLinkType.Topology.CheckValid(); err != nil {
return nil, err
}
}
}
if rel != nil && rel.SpaceTemplate != nil && rel.SpaceTemplate.Data != nil {
modelLinkType.SpaceTemplateID = rel.SpaceTemplate.Data.ID
}
return &modelLinkType, nil
} |
// CreatePolicyGroup creates a new child PolicyGroup under the L2Domain | func (o *L2Domain) CreatePolicyGroup(child *PolicyGroup) *bambou.Error {
return bambou.CurrentSession().CreateChild(o, child)
} |
// deleteVolumeOperation deletes a volume. This method is running in standalone
// goroutine and already has all necessary locks. | func (ctrl *PersistentVolumeController) deleteVolumeOperation(volume *v1.PersistentVolume) (string, error) {
klog.V(4).Infof("deleteVolumeOperation [%s] started", volume.Name)
// This method may have been waiting for a volume lock for some time.
// Previous deleteVolumeOperation might just have saved an updated version, so
// read current volume state now.
newVolume, err := ctrl.kubeClient.CoreV1().PersistentVolumes().Get(volume.Name, metav1.GetOptions{})
if err != nil {
klog.V(3).Infof("error reading persistent volume %q: %v", volume.Name, err)
return "", nil
}
needsReclaim, err := ctrl.isVolumeReleased(newVolume)
if err != nil {
klog.V(3).Infof("error reading claim for volume %q: %v", volume.Name, err)
return "", nil
}
if !needsReclaim {
klog.V(3).Infof("volume %q no longer needs deletion, skipping", volume.Name)
return "", nil
}
pluginName, deleted, err := ctrl.doDeleteVolume(volume)
if err != nil {
// Delete failed, update the volume and emit an event.
klog.V(3).Infof("deletion of volume %q failed: %v", volume.Name, err)
if volerr.IsDeletedVolumeInUse(err) {
// The plugin needs more time, don't mark the volume as Failed
// and send Normal event only
ctrl.eventRecorder.Event(volume, v1.EventTypeNormal, events.VolumeDelete, err.Error())
} else {
// The plugin failed, mark the volume as Failed and send Warning
// event
if _, err := ctrl.updateVolumePhaseWithEvent(volume, v1.VolumeFailed, v1.EventTypeWarning, events.VolumeFailedDelete, err.Error()); err != nil {
klog.V(4).Infof("deleteVolumeOperation [%s]: failed to mark volume as failed: %v", volume.Name, err)
// Save failed, retry on the next deletion attempt
return pluginName, err
}
}
// Despite the volume being Failed, the controller will retry deleting
// the volume in every syncVolume() call.
return pluginName, err
}
if !deleted {
// The volume waits for deletion by an external plugin. Do nothing.
return pluginName, nil
}
klog.V(4).Infof("deleteVolumeOperation [%s]: success", volume.Name)
// Delete the volume
if err = ctrl.kubeClient.CoreV1().PersistentVolumes().Delete(volume.Name, nil); err != nil {
// Oops, could not delete the volume and therefore the controller will
// try to delete the volume again on next update. We _could_ maintain a
// cache of "recently deleted volumes" and avoid unnecessary deletion,
// this is left out as future optimization.
klog.V(3).Infof("failed to delete volume %q from database: %v", volume.Name, err)
return pluginName, nil
}
return pluginName, nil
} |
Check if we can create a post.
@param object $post Post object.
@return boolean Can we create it?. | protected function check_create_permission( $post ) {
$post_type = get_post_type_object( $post->post_type );
if ( ! $this->check_is_post_type_allowed( $post_type ) ) {
return false;
}
return current_user_can( $post_type->cap->create_posts );
} |
Set the origin. Pass a length three tuple of floats | def origin(self, origin):
""""""
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | @Override
public EClass getIfcWorkPlan() {
if (ifcWorkPlanEClass == null) {
ifcWorkPlanEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(772);
}
return ifcWorkPlanEClass;
} |
协程模式
@param Context $context 请求上下文对象
@param string $name Redis指令
@param array $arg Redis指令参数
@return mixed|Redis
@throws Exception | public function go($context, $name, ...$arg)
{
if (getInstance()->processType == Macro::PROCESS_TASKER) {//如果是task进程自动转换为同步模式
return $this->getSync()->$name(...$arg);
} else {
return $context->getObjectPool()->get(Redis::class, [$this, $name, $arg]);
}
} |
Returns data handler if provided with plugin otherwise return default handler function
@param app
@param schema {String} Schema name
@param data {Object|Array} default data
@returns {*|Function|Function} | function getHandler(app, schema, data) {
function handleSave(err, results, next) {
if (!err) {
delete DependenciesMap[schema];
SavedSchemas.push(schema);
_l('schema saved: ' + schema);
}
next(err, results);
}
// Default handler function
var ret = function (next) {
data = _.isObject(data) ? _.values(data) : data;
DBActions.getSimpleInstance(app, schema).multipleSave(data, function (err, results) {
handleSave(err, results, next);
});
};
// Data handler provided in plugin
var ret1 = SchemaDataHandler[schema] && function (next) {
SchemaDataHandler[schema](app, data)(function (err, results) {
handleSave(err, results, next);
});
};
return ret1 || ret;
} |
Fetches a resource.
@param msg the HTTP message that will be sent to the server
@throws IOException Signals that an I/O exception has occurred. | private void fetchResource(HttpMessage msg) throws IOException {
if (parent.getHttpSender() == null) {
return;
}
try {
parent.getHttpSender().sendAndReceive(msg);
} catch (ConnectException e) {
log.debug("Failed to connect to: " + msg.getRequestHeader().getURI(), e);
throw e;
} catch (SocketTimeoutException e) {
log.debug("Socket timeout: " + msg.getRequestHeader().getURI(), e);
throw e;
} catch (SocketException e) {
log.debug("Socket exception: " + msg.getRequestHeader().getURI(), e);
throw e;
} catch (UnknownHostException e) {
log.debug("Unknown host: " + msg.getRequestHeader().getURI(), e);
throw e;
} catch (Exception e) {
log.error("An error occurred while fetching the resource [" + msg.getRequestHeader().getURI() + "]: "
+ e.getMessage(), e);
throw e;
}
} |
Add answers fields
@param FormInterface $form | protected function addAnswersFields(FormInterface $form)
{
$question = $this->questionInteract->getQuestion();
$data = $this->getQuestionData();
/** @var AnswerCheckerInterface $checker */
$checker = $this->checkerLocator->get($question->getType());
$options = $checker->getOptions($question->getAnswers()->getValues(), $data);
$form->add('answers', $checker->getType(), $options);
} |
Static helper for extending list columns.
@param callable $callback
@return void | public static function extendListColumns($callback)
{
$calledClass = self::getCalledExtensionClass();
Event::listen('backend.list.extendColumns', function ($widget) use ($calledClass, $callback) {
if (!is_a($widget->getController(), $calledClass)) {
return;
}
call_user_func_array($callback, [$widget, $widget->model]);
});
} |
Builds Layer Menu from OPML File.
@access public
@param string $fileName URL of OPML File
@return | public function buildMenuFromOpmlFile( $fileName )
{
$list = Alg_Tree_Menu_Converter::convertFromOpmlFile( $fileName, $this->rootLabel );
return $this->buildMenuFromMenuList( $list );
} |
// Starts a cron job immediately. The request will be denied if the specified job does not
// exist for the role account, or the job is not a cron job.
//
// Parameters:
// - Job | func (p *AuroraSchedulerManagerClient) StartCronJob(ctx context.Context, job *JobKey) (r *Response, err error) {
var _args137 AuroraSchedulerManagerStartCronJobArgs
_args137.Job = job
var _result138 AuroraSchedulerManagerStartCronJobResult
if err = p.Client_().Call(ctx, "startCronJob", &_args137, &_result138); err != nil {
return
}
return _result138.GetSuccess(), nil
} |
@param Options $options
@return string | public function getData(Options $options = null)
{
if ($options === null) {
// Take store global/default options
$options = $this->store->getOptions();
}
// Get unformatted data when using excel writer
$options->getHydrationOptions()->disableFormatters();
// Some colu
$options->getHydrationOptions()->disableColumnExclusion();
$book = $this->getExcelBook();
$this->generateExcel($book, $options);
//$book->setLocale($locale);
$temp_dir = sys_get_temp_dir();
if (!is_dir($temp_dir)) {
throw new \Exception(__METHOD__ . " System temporary directory '$temp_dir' does not exists.");
}
if (!is_writable($temp_dir)) {
throw new \Exception(__METHOD__ . " System temporary directory '$temp_dir' is not writable.");
}
$filename = tempnam($temp_dir, 'libxl');
try {
$book->save($filename);
} catch (\Exception $e) {
unlink($filename);
throw $e;
}
$data = file_get_contents($filename);
unlink($filename);
return $data;
} |
Convert datetime.datetime object between timezones | def _convert(value, tzto, defaulttz):
""""""
if not isinstance(value, datetime):
raise ValueError('value must be a datetime.datetime object')
if value.tzinfo is None:
value = value.replace(tzinfo=defaulttz)
return value.astimezone(tzto) |
Map put method.
FilterHolder implements the Map interface as a
configuration conveniance. The methods are mapped to the
filter properties. | public synchronized Object put(Object name,Object value)
{
if (_initParams==null)
_initParams=new HashMap(3);
return _initParams.put(name,value);
} |
// Terminate the authentication process upon context cancellation;
// only to be called if/when ctx.Done() has been signalled. | func (self *authenticateeProcess) discard(ctx context.Context) error {
err := ctx.Err()
status := statusFrom(ctx)
for ; status < _statusTerminal; status = (&self.status).get() {
if self.terminate(status, statusDiscarded, err) {
break
}
}
return err
} |
Sets the weight of the connection between two layers (argument strings). | def setWeight(self, fromName, fromPos, toName, toPos, value):
for connection in self.connections:
if connection.fromLayer.name == fromName and \
connection.toLayer.name == toName:
connection.weight[fromPos][toPos] = value
return value
raise NetworkError('Connection was not found.', (fromName, toName)) |
Helper method for []=.
Add a new index and assign it value | def insert_vector(indexes, val)
new_index = @index.add(*indexes)
# May be create +=
(new_index.size - @index.size).times { @data << val }
@index = new_index
end |
Entry point into this API.
@throws IllegalArgumentException if pattern contains any syntax errors. | public static Phrase from(Resources r, @StringRes int patternResourceId) {
return from(r.getText(patternResourceId));
} |
Tries to return a ResponseData object
@param {any} result
@return {ResponseData} | function normalizeResult(result){
if (!result || result._isResponseData !== true)
return ResponseData(result,{default:true})
return result
} |
// Info implements Command.Info. | func (c *importKeysCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "import-ssh-key",
Args: "<lp|gh>:<user identity> ...",
Purpose: usageImportSSHKeySummary,
Doc: usageImportSSHKeyDetails,
})
} |
@param string|null $data
@param bool $compressed
@return mixed|null | public static function unpack($data, bool $compressed = false)
{
if (null === $data) {
return $data;
}
if ($compressed) {
$data = gzdecode($data);
}
return unserialize($data);
} |
Get active modules path info
@return array | public function getActiveModuleInfo()
{
$aModulePaths = $this->getModuleConfigParametersByKey(static::MODULE_KEY_PATHS);
// Extract module paths from extended classes
if (!is_array($aModulePaths) || count($aModulePaths) < 1) {
$aModulePaths = $this->extractModulePaths();
}
$aDisabledModules = $this->getDisabledModules();
if (is_array($aDisabledModules) && count($aDisabledModules) > 0 && count($aModulePaths) > 0) {
$aModulePaths = array_diff_key($aModulePaths, array_flip($aDisabledModules));
}
return $aModulePaths;
} |
Fill from a file-like object. | def parse(self, fileobj, name_hint='', parser=None):
""""""
self.current_block = None # Reset current block
parser = parser or Parser()
for line in parser.parse(fileobj, name_hint=name_hint):
self.handle_line(line) |
<p>
Information about the status of the instances.
</p>
@return Information about the status of the instances. | public java.util.List<InstanceStatus> getInstanceStatuses() {
if (instanceStatuses == null) {
instanceStatuses = new com.amazonaws.internal.SdkInternalList<InstanceStatus>();
}
return instanceStatuses;
} |
override Builder#listnum | def listnum(lines, id, caption, lang = nil)
first_line_num = line_num
if highlight_listings?
common_code_block_lst(id, lines, 'reviewlistnumlst', 'caption', caption, lang, first_line_num: first_line_num)
else
common_code_block(id, lines, 'reviewlist', caption, lang) { |line, idx| detab((idx + first_line_num).to_s.rjust(2) + ': ' + line) + "\n" }
end
end |
Generate a matrix from a configuration dictionary. | def from_config(config):
matrix = {}
variables = config.keys()
for entries in product(*config.values()):
combination = dict(zip(variables, entries))
include = True
for value in combination.values():
for reducer in value.reducers:
if reducer.pattern == '-':
match = not combination[reducer.variable].value
else:
match = fnmatch(combination[reducer.variable].value, reducer.pattern)
if match if reducer.is_exclude else not match:
include = False
if include:
key = '-'.join(entry.alias for entry in entries if entry.alias)
data = dict(
zip(variables, (entry.value for entry in entries))
)
if key in matrix and data != matrix[key]:
raise DuplicateEnvironment(key, data, matrix[key])
matrix[key] = data
return matrix |
{@inheritdoc}
@param FormBuilderInterface $builder The form builder.
@param array $options The options for this form.
@return void | public function buildForm(FormBuilderInterface $builder, array $options): void
{
$event = $options['data'];
$builder
->add('start', null, [
'label' => 'event.form.start',
'date_widget' => 'single_text',
'time_widget' => 'single_text',
])
->add('end', null, [
'label' => 'event.form.end',
'date_widget' => 'single_text',
'time_widget' => 'single_text',
])
->add('name', null, [
'label' => 'event.form.name',
])
->add('location', null, [
'label' => 'event.form.location',
])
->add('description', CKEditorType::class, [
'label' => 'event.form.description',
'required' => false,
'config' => ['toolbar' => 'basic'],
])
->add('full_company', CheckboxType::class, [
'label' => 'event.form.full_company',
'required' => false,
])
->add('invitations', CollectionType::class, [
'label' => 'event.form.invitations',
'entry_type' => InvitationType::class,
'entry_options' => ['label' => false],
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])
->add('colour', ChoiceType::class, [
'label' => 'event.form.colour',
'required' => false,
'choices' => [
'event.form.colour_choices.red' => 'important',
'event.form.colour_choices.green' => 'success',
'event.form.colour_choices.yellow' => 'warning',
'event.form.colour_choices.blue' => 'info',
'event.form.colour_choices.dark' => 'inverse',
'event.form.colour_choices.purple' => 'special',
],
])
->add('active', ChoiceType::class, [
// Show "unpublished" instead of active.
'choice_loader' => new CallbackChoiceLoader(function () use ($event) {
yield 'event.form.status_choices.active' => true;
if (!$event->isPublished()) {
yield 'event.form.status_choices.unpublished' => false;
} else {
yield 'event.form.status_choices.archived' => false;
}
}),
'label' => 'event.form.status',
])
;
} |
Retrieve the interaction cardinality
(single, multiple or ordered)
@access public
@author Sam, <sam@taotesting.com>
@param boolean numeric
@return mixed | public function getCardinality($numeric = false){
$returnValue = null;
// get maximum possibility:
switch(strtolower($this->getType())){
case 'choice':
case 'hottext':
case 'hotspot':
case 'selectpoint':
case 'positionobject':{
$max = intval($this->getAttributeValue('maxChoices'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max == 1) ? 'single' : 'multiple'; // default=1
}
break;
}
case 'associate':
case 'match':
case 'graphicassociate':{
$max = intval($this->getAttributeValue('maxAssociations'));
if($numeric){
$returnValue = $max;
}
else{
$returnValue = ($max == 1) ? 'single' : 'multiple';
} // default=1
break;
}
case 'extendedtext':{
// maxStrings + order or not?
$cardinality = $this->getAttributeValue('cardinality');
if($cardinality == 'ordered'){
if($numeric){
$returnValue = 0;
} // meaning, infinite
else {
$returnValue = $cardinality;
}
break;
}
$max = intval($this->getAttributeValue('maxStrings'));
if($numeric){
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single'; // optional
}
break;
}
case 'gapmatch':{
// count the number of gap, i.e. "groups" in the interaction:
$max = count($this->getGaps());
if($numeric) {
$returnValue = $max;
}
else {
$returnValue = ($max > 1) ? 'multiple' : 'single';
}
break;
}
case 'graphicgapmatch':{
// strange that the standard always specifies "multiple":
$returnValue = 'multiple';
break;
}
case 'order':
case 'graphicorder':{
$returnValue = ($numeric) ? 1 : 'ordered';
break;
}
case 'inlinechoice':
case 'textentry':
case 'media':
case 'slider':
case 'upload':
case 'endattempt':{
$returnValue = ($numeric) ? 1 : 'single';
break;
}
default:{
throw new QtiModelException("the current interaction type \"{$this->type}\" is not available yet");
}
}
return $returnValue;
} |
Adds a "where in" condition.
@param string $key
@param array $values
@return QueryBuilder | public function whereIn(string $key, array $values): QueryBuilder
{
$this->addWhere($key, 'IN', $values, 'AND');
return $this;
} |
Determine if this page references a parent which is archived, and not available in stage
@return bool True if there is an archived parent | protected function isParentArchived()
{
if ($parentID = $this->ParentID) {
/** @var SiteTree $parentPage */
$parentPage = Versioned::get_latest_version(self::class, $parentID);
if (!$parentPage || !$parentPage->isOnDraft()) {
return true;
}
}
return false;
} |
Reads the {@code Catalog} entry from the given input stream.
@param pInput the input stream
@return a new {@code Catalog}
@throws java.io.IOException if an I/O exception occurs during read | public static Catalog read(final InputStream pInput) throws IOException {
DataInput dataInput = new LittleEndianDataInputStream(pInput);
return read(dataInput);
} |
https://tc39.github.io/ecma262/#sec-toindex | function _toIndex(it) {
if (it === undefined) return 0;
var number = _toInteger(it);
var length = _toLength(number);
if (number !== length) throw RangeError('Wrong length!');
return length;
} |
remove a list and it's elements
@access public
@author Joel Bout, <joel.bout@tudor.lu>
@param Class listClass
@return boolean | public function removeList( core_kernel_classes_Class $listClass)
{
$returnValue = (bool) false;
if(!is_null($listClass)){
foreach($this->getListElements($listClass) as $element){
$this->removeListElement($element);
}
$returnValue = $listClass->delete();
}
return (bool) $returnValue;
} |
Converts a length from a CSS length or percentage to 'pt'.
@param spec the CSS length specification
@param whole the value that corresponds to 100%. It is used only when spec is a percentage.
@return the length in 'pt' | public double ptLength(TermLengthOrPercent spec, double whole)
{
float nval = spec.getValue();
if (spec.isPercentage())
{
return (whole * nval) / 100;
}
else if (spec instanceof TermCalc)
{
final CalcArgs args = ((TermCalc) spec).getArgs();
return args.evaluate(getPtEval().setWhole(whole));
}
else
{
final TermLength.Unit unit = spec.getUnit();
if (unit == null)
return 0;
switch (unit)
{
case pt:
return nval;
case in:
return nval * 72;
case cm:
return (nval * 72) / 2.54;
case mm:
return (nval * 72) / 25.4;
case q:
return (nval * 72) / (2.54 * 40.0);
case pc:
return nval * 12;
case px:
return (nval * 72) / dpi;
case em:
return (em * nval * 72) / dpi; //em is in pixels
case rem:
return (rem * nval * 72) / dpi;
case ex:
return (ex * nval * 72) / dpi;
case ch:
return (ch * nval * 72) / dpi;
case vw:
return (viewport.getVisibleRect().getWidth() * nval * 72) / (100.0 * dpi);
case vh:
return (viewport.getVisibleRect().getHeight() * nval * 72) / (100.0 * dpi);
case vmin:
return (Math.min(viewport.getVisibleRect().getWidth(), viewport.getVisibleRect().getHeight()) * nval * 72) / (100.0 * dpi);
case vmax:
return (Math.max(viewport.getVisibleRect().getWidth(), viewport.getVisibleRect().getHeight()) * nval * 72) / (100.0 * dpi);
default:
return 0;
}
}
} |
Retrieve SOAP types from the WSDL and parse them
@return array Array of types and their properties | public function getSoapTypes()
{
if (null === $this->types) {
$soapTypes = $this->__getTypes();
foreach ($soapTypes as $soapType) {
$properties = array();
$lines = explode("\n", $soapType);
if (!preg_match('/struct (.*) {/', $lines[0], $matches)) {
continue;
}
$typeName = $matches[1];
foreach (array_slice($lines, 1) as $line) {
if ($line == '}') {
continue;
}
preg_match('/\s* (.*) (.*);/', $line, $matches);
$properties[$matches[2]] = $matches[1];
}
// Since every object extends sObject, need to append sObject elements to all native and custom objects
if ($typeName !== 'sObject' && array_key_exists('sObject', $this->types)) {
$properties = array_merge($properties, $this->types['sObject']);
}
$this->types[$typeName] = $properties;
}
}
return $this->types;
} |
Returns the bounds of the underlying element.
@memberof wdg | function() {
var e = this._element;
if (!e) return null;
if (typeof e.getBoundingClientRect !== 'function') {
console.error("[wdg.rect] This element has non `getBoundingClientRect` function:", e);
}
var r = e.getBoundingClientRect();
if( typeof r.width === 'undefined' ) r.width = r.right - r.left;
if( typeof r.height === 'undefined' ) r.height = r.bottom - r.top;
return r;
} |
Overloads the left shift operator to provide an easy way to add
components to a popupMenu.<p>
@param self a JPopupMenu
@param str a String to be added to the popupMenu.
@return same popupMenu, after the value was added to it.
@since 1.6.4 | public static JPopupMenu leftShift(JPopupMenu self, String str) {
self.add(str);
return self;
} |
// SetCachingEnabled sets the CachingEnabled field's value. | func (s *MethodSetting) SetCachingEnabled(v bool) *MethodSetting {
s.CachingEnabled = &v
return s
} |
URL Template (RFC 6570) Transform. | function template (options) {
var variables = [], url = expand(options.url, options.params, variables);
variables.forEach(function (key) {
delete options.params[key];
});
return url;
} |
For the parameter <i>_expr</i> the index in the list of all field
expressions is returned.
@param _expr expression for which the index is searched
@return index of the field expression
@see #addFieldExpr
@see #getAllFieldExpr
@see #allFieldExpr | public int getFieldExprIndex(final String _expr)
{
int ret = -1;
if (getAllFieldExpr().containsKey(_expr)) {
final Integer ident = getAllFieldExpr().get(_expr);
ret = ident.intValue();
}
return ret;
} |
Applies the faded class to all lines but the one that has the given id
@param {number} exceptionItemId Id of the line that needs to stay the same
@private | function fadeLinesBut(exceptionItemId) {
let classToFade = 'g.legend-entry';
let entryLine = svg.select(`[data-item="${exceptionItemId}"]`);
if (entryLine.nodes().length){
svg.select('.legend-group')
.selectAll(classToFade)
.classed(isFadedClassName, true);
entryLine.classed(isFadedClassName, false);
}
} |
build before button string
@param int $current
@param string $url
@param string $class
@return bool|string | private function createBeforeButton($current, $url, $class, $fragments)
{
if ($this->isAvaibleCurrentPage($current) && $current > 1) {
$page = $current - 1;
return $this->buildChieldString("«", $url, $class, $fragments, $page);
} else {
return false;
}
} |
Timeout the resource
@return A {@link Broadcastable} used to broadcast events. | @GET
@Suspend(period = 60, timeUnit = TimeUnit.SECONDS, listeners = {EventsLogger.class})
@Path("timeout")
public Broadcastable timeout() {
return new Broadcastable(broadcaster);
} |
Switches to forward checking if possible. | private void switchToForward() {
assert(state == State.ITER_CHECK_BWD ||
(state == State.ITER_IN_FCD_SEGMENT && pos == limit) ||
(state.compareTo(State.IN_NORM_ITER_AT_LIMIT) >= 0 && pos == normalized.length()));
if(state == State.ITER_CHECK_BWD) {
// Turn around from backward checking.
start = pos = iter.getIndex();
if(pos == limit) {
state = State.ITER_CHECK_FWD; // Check forward.
} else { // pos < limit
state = State.ITER_IN_FCD_SEGMENT; // Stay in FCD segment.
}
} else {
// Reached the end of the FCD segment.
if(state == State.ITER_IN_FCD_SEGMENT) {
// The input text segment is FCD, extend it forward.
} else {
// The input text segment needed to be normalized.
// Switch to checking forward from it.
if(state == State.IN_NORM_ITER_AT_START) {
iter.moveIndex(limit - start);
}
start = limit;
}
state = State.ITER_CHECK_FWD;
}
} |
Generates a Stripe Token
@param array $params Expects: cardNumber, expiryMonth, expiryYear, cvc
@return array | public function generateToken(array $params)
{
$stripe = new Stripe(Billable::getStripeKey());
try {
$attributes = [
'card' => [
'number' => $params['cardNumber'],
'exp_month' => $params['expiryMonth'],
'cvc' => $params['cvc'],
'exp_year' => $params['expiryYear'],
],
];
$token = $stripe->tokens()->create($attributes);
return [
'status' => 'success',
'token' => $token['id']
];
} catch (\Exception $e) {
return [
'status' => 'error',
'message' => $e->getMessage()
];
}
} |
Updates the component error of a component, but only if it differs from the currently set
error.<p>
@param component the component
@param error the error
@return true if the error was changed | public static boolean updateComponentError(AbstractComponent component, ErrorMessage error) {
if (component.getComponentError() != error) {
component.setComponentError(error);
return true;
}
return false;
} |
Gets a project.
@param string $slug A project slug | public function getProject($slug)
{
if (!isset($this->projects[$slug])) {
throw new \InvalidArgumentException(sprintf('Project "%s" does not exist.', $slug));
}
return $this->projects[$slug];
} |
// Converts a base 62 byte into the number value that it represents. | func base62Value(digit byte) byte {
switch {
case digit >= '0' && digit <= '9':
return digit - '0'
case digit >= 'A' && digit <= 'Z':
return offsetUppercase + (digit - 'A')
default:
return offsetLowercase + (digit - 'a')
}
} |
// SetExpectedVersion sets the ExpectedVersion field's value. | func (s *UpdateJobExecutionInput) SetExpectedVersion(v int64) *UpdateJobExecutionInput {
s.ExpectedVersion = &v
return s
} |
统一的处理输入-输出为布尔型
@param array|string $params
@return array|bool | private static function parseInputToBool($params)
{
return is_array($params) ? array_map(function ($item) {
return ((bool)$item);
}, $params) : ((bool)$params);
} |
Parse specific 'data' command options. | public void execute() {
checkParameters();
if (loadCommandOptions.data != null) {
if (loadCommandOptions.loaderParams.containsKey("mongodb-index-folder")) {
configuration.getDatabases().getMongodb().getOptions().put("mongodb-index-folder",
loadCommandOptions.loaderParams.get("mongodb-index-folder"));
}
// If 'authenticationDatabase' is not passed by argument then we read it from configuration.json
if (loadCommandOptions.loaderParams.containsKey("authenticationDatabase")) {
configuration.getDatabases().getMongodb().getOptions().put("authenticationDatabase",
loadCommandOptions.loaderParams.get("authenticationDatabase"));
}
// loadRunner = new LoadRunner(loader, database, loadCommandOptions.loaderParams, numThreads, configuration);
loadRunner = new LoadRunner(loader, database, numThreads, configuration);
String[] loadOptions;
if (loadCommandOptions.data.equals("all")) {
loadOptions = new String[]{EtlCommons.GENOME_DATA, EtlCommons.GENE_DATA, EtlCommons.CONSERVATION_DATA,
EtlCommons.REGULATION_DATA, EtlCommons.PROTEIN_DATA, EtlCommons.PPI_DATA,
EtlCommons.PROTEIN_FUNCTIONAL_PREDICTION_DATA, EtlCommons.VARIATION_DATA,
EtlCommons.VARIATION_FUNCTIONAL_SCORE_DATA, EtlCommons.CLINICAL_VARIANTS_DATA,
EtlCommons.REPEATS_DATA, EtlCommons.STRUCTURAL_VARIANTS_DATA, };
} else {
loadOptions = loadCommandOptions.data.split(",");
}
for (int i = 0; i < loadOptions.length; i++) {
String loadOption = loadOptions[i];
try {
switch (loadOption) {
case EtlCommons.GENOME_DATA:
loadIfExists(input.resolve("genome_info.json"), "genome_info");
loadIfExists(input.resolve("genome_sequence.json.gz"), "genome_sequence");
loadIfExists(input.resolve("genomeVersion.json"), METADATA);
loadRunner.index("genome_sequence");
break;
case EtlCommons.GENE_DATA:
loadIfExists(input.resolve("gene.json.gz"), "gene");
loadIfExists(input.resolve("dgidbVersion.json"), METADATA);
loadIfExists(input.resolve("ensemblCoreVersion.json"), METADATA);
loadIfExists(input.resolve("uniprotXrefVersion.json"), METADATA);
loadIfExists(input.resolve("geneExpressionAtlasVersion.json"), METADATA);
loadIfExists(input.resolve("hpoVersion.json"), METADATA);
loadIfExists(input.resolve("disgenetVersion.json"), METADATA);
loadRunner.index("gene");
break;
case EtlCommons.VARIATION_DATA:
loadVariationData();
break;
case EtlCommons.VARIATION_FUNCTIONAL_SCORE_DATA:
loadIfExists(input.resolve("cadd.json.gz"), "cadd");
loadIfExists(input.resolve("caddVersion.json"), METADATA);
loadRunner.index("variation_functional_score");
break;
case EtlCommons.CONSERVATION_DATA:
loadConservation();
break;
case EtlCommons.REGULATION_DATA:
loadIfExists(input.resolve("regulatory_region.json.gz"), "regulatory_region");
loadIfExists(input.resolve("ensemblRegulationVersion.json"), METADATA);
loadIfExists(input.resolve("mirbaseVersion.json"), METADATA);
loadIfExists(input.resolve("targetScanVersion.json"), METADATA);
loadIfExists(input.resolve("miRTarBaseVersion.json"), METADATA);
loadRunner.index("regulatory_region");
break;
case EtlCommons.PROTEIN_DATA:
loadIfExists(input.resolve("protein.json.gz"), "protein");
loadIfExists(input.resolve("uniprotVersion.json"), METADATA);
loadIfExists(input.resolve("interproVersion.json"), METADATA);
loadRunner.index("protein");
break;
case EtlCommons.PPI_DATA:
loadIfExists(input.resolve("protein_protein_interaction.json.gz"), "protein_protein_interaction");
loadIfExists(input.resolve("intactVersion.json"), METADATA);
loadRunner.index("protein_protein_interaction");
break;
case EtlCommons.PROTEIN_FUNCTIONAL_PREDICTION_DATA:
loadProteinFunctionalPrediction();
break;
case EtlCommons.CLINICAL_VARIANTS_DATA:
loadClinical();
break;
case EtlCommons.REPEATS_DATA:
loadRepeats();
break;
case EtlCommons.STRUCTURAL_VARIANTS_DATA:
loadStructuralVariants();
break;
default:
logger.warn("Not valid 'data'. We should not reach this point");
break;
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | ExecutionException
| NoSuchMethodException | InterruptedException | ClassNotFoundException | LoaderException | IOException e) {
e.printStackTrace();
}
}
}
} |
Prepare the data for this run.
Note: This will also remove posts from the queue.
@param int $timenow | protected function prepare_data(int $timenow) {
global $DB;
$sql = "SELECT p.*, f.id AS forum, f.course
FROM {forum_queue} q
INNER JOIN {forum_posts} p ON p.id = q.postid
INNER JOIN {forum_discussions} d ON d.id = p.discussion
INNER JOIN {forum} f ON f.id = d.forum
WHERE q.userid = :userid
AND q.timemodified < :timemodified
ORDER BY d.id, q.timemodified ASC";
$queueparams = [
'userid' => $this->recipient->id,
'timemodified' => $timenow,
];
$posts = $DB->get_recordset_sql($sql, $queueparams);
$discussionids = [];
$forumids = [];
$courseids = [];
$userids = [];
foreach ($posts as $post) {
$discussionids[] = $post->discussion;
$forumids[] = $post->forum;
$courseids[] = $post->course;
$userids[] = $post->userid;
unset($post->forum);
if (!isset($this->posts[$post->discussion])) {
$this->posts[$post->discussion] = [];
}
$this->posts[$post->discussion][$post->id] = $post;
}
$posts->close();
if (empty($discussionids)) {
// All posts have been removed since the task was queued.
$this->empty_queue($this->recipient->id, $timenow);
return;
}
list($in, $params) = $DB->get_in_or_equal($discussionids);
$this->discussions = $DB->get_records_select('forum_discussions', "id {$in}", $params);
list($in, $params) = $DB->get_in_or_equal($forumids);
$this->forums = $DB->get_records_select('forum', "id {$in}", $params);
list($in, $params) = $DB->get_in_or_equal($courseids);
$this->courses = $DB->get_records_select('course', "id $in", $params);
list($in, $params) = $DB->get_in_or_equal($userids);
$this->users = $DB->get_records_select('user', "id $in", $params);
$this->fill_digest_cache();
$this->empty_queue($this->recipient->id, $timenow);
} |
Print application config path. | def print_app_config_path(ctx, param, value):
""""""
if not value or ctx.resilient_parsing:
return
click.echo(config_path(os.environ.get('RENKU_CONFIG')))
ctx.exit() |
// GetPublicIPv6 is used to return the first public IP address
// associated with an interface on the machine | func GetPublicIPv6() (net.IP, error) {
addresses, err := net.InterfaceAddrs()
if err != nil {
return nil, fmt.Errorf("Failed to get interface addresses: %v", err)
}
return getPublicIPv6(addresses)
} |
Wraps given stopwatch source in a cache.
@param stopwatchSource Stopwatch source
@return Cached stopwatch source | private static <T> CachedStopwatchSource<T, Method> newCacheStopwatchSource(final AbstractMethodStopwatchSource<T> stopwatchSource) {
return new CachedStopwatchSource<T, Method>(stopwatchSource) {
@Override
protected Method getLocationKey(T location) {
return stopwatchSource.getTargetMethod(location);
}
};
} |
// WeekdayWide returns the locales wide weekday given the 'weekday' provided | func (luo *luo) WeekdayWide(weekday time.Weekday) string {
return luo.daysWide[weekday]
} |
Get PID file name for a named notebook. | def get_pid(self, name):
""""""
pid_file = os.path.join(self.get_work_folder(name), "notebook.pid")
return pid_file |
Does the counting from DB. Unlike the other counter that uses Redis. Hence
the name local_count
@param [Time] duration A time/time range object
@param [Fixnum] type The type of counter to look for | def local_count(duration, type)
aggr = {}
Octo::Enterprise.each do |enterprise|
args = {
enterprise_id: enterprise.id,
ts: duration,
type: type
}
aggr[enterprise.id.to_s] = {} unless aggr.has_key?(enterprise.id.to_s)
results = where(args)
results_group = results.group_by { |x| x.uid }
results_group.each do |uid, counters|
_sum = counters.inject(0) do |sum, counter|
sum + counter.count
end
aggr[enterprise.id.to_s][uid] = _sum
end
end
aggr
end |
// assembleService assembles a services back from a hain of netlink attributes | func assembleService(attrs []syscall.NetlinkRouteAttr) (*Service, error) {
var s Service
for _, attr := range attrs {
attrType := int(attr.Attr.Type)
switch attrType {
case ipvsSvcAttrAddressFamily:
s.AddressFamily = native.Uint16(attr.Value)
case ipvsSvcAttrProtocol:
s.Protocol = native.Uint16(attr.Value)
case ipvsSvcAttrAddress:
ip, err := parseIP(attr.Value, s.AddressFamily)
if err != nil {
return nil, err
}
s.Address = ip
case ipvsSvcAttrPort:
s.Port = binary.BigEndian.Uint16(attr.Value)
case ipvsSvcAttrFWMark:
s.FWMark = native.Uint32(attr.Value)
case ipvsSvcAttrSchedName:
s.SchedName = nl.BytesToString(attr.Value)
case ipvsSvcAttrFlags:
s.Flags = native.Uint32(attr.Value)
case ipvsSvcAttrTimeout:
s.Timeout = native.Uint32(attr.Value)
case ipvsSvcAttrNetmask:
s.Netmask = native.Uint32(attr.Value)
case ipvsSvcAttrStats:
stats, err := assembleStats(attr.Value)
if err != nil {
return nil, err
}
s.Stats = stats
}
}
return &s, nil
} |
Finds the conversion method.
@param <T> the type of the converter
@param cls the class to find a method for, not null
@return the method to call, null means use {@code toString} | private <T> Constructor<T> findFromStringConstructorByType(Class<T> cls) {
try {
return cls.getDeclaredConstructor(String.class);
} catch (NoSuchMethodException ex) {
try {
return cls.getDeclaredConstructor(CharSequence.class);
} catch (NoSuchMethodException ex2) {
throw new IllegalArgumentException("Constructor not found", ex2);
}
}
} |
// VolumeInspectWithRaw returns the information about a specific volume in the docker host and its raw representation | func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) {
var volume types.Volume
resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil)
if err != nil {
if resp.statusCode == http.StatusNotFound {
return volume, nil, volumeNotFoundError{volumeID}
}
return volume, nil, err
}
defer ensureReaderClosed(resp)
body, err := ioutil.ReadAll(resp.body)
if err != nil {
return volume, nil, err
}
rdr := bytes.NewReader(body)
err = json.NewDecoder(rdr).Decode(&volume)
return volume, body, err
} |
Return a configuration dict | def get_config():
""""""
from os import environ
from os.path import expanduser
from pathlib import Path
import yaml
def pexp(p):
try:
return Path(p).expanduser()
except AttributeError:
# python 3.4
return Path(expanduser(p))
paths = [environ.get("METAPACK_CONFIG"), '~/.metapack.yaml', '/etc/metapack.yaml']
for p in paths:
if not p:
continue
p = pexp(p)
if p.exists():
with p.open() as f:
config = yaml.safe_load(f)
if not config:
config = {}
config['_loaded_from'] = str(p)
return config
return None |
Sets mode to READ_ONLY, discarding flush task | protected void setReadOnly()
{
// try to stop merger in safe way
if (merger != null)
{
merger.dispose();
merger = null;
}
if (flushTask != null)
{
flushTask.cancel();
}
FLUSH_TIMER.purge();
this.redoLog = null;
} |
Adds a new level to the progress stack. | private void onPushLevelProgress(int steps, Object source, boolean singlesteplevel)
{
if (this.currentStep.isLevelFinished()) {
// If current step is done move to next one
this.currentStep = this.currentStep.getParent().nextStep(null, source);
}
// Add level
this.currentStep = this.currentStep.addLevel(steps, source, singlesteplevel);
} |
@param string $client_id
@param string $user_id
@return bool | public function removeClientUser($client_id, $user_id)
{
$sql = 'DELETE from %s where client_id = :client_id and user_id = :user_id';
$sql = sprintf($sql, $this->config['client_user_table']);
$params = array_map('trim', compact('client_id', 'user_id'));
return $this->db->prepare($sql)->execute($params);
} |
Delete all the keys in the Redis database
@throws ModuleException | public function cleanup()
{
try {
$this->driver->flushdb();
} catch (\Exception $e) {
throw new ModuleException(
__CLASS__,
$e->getMessage()
);
}
} |
Returns the minimum length for this ruler based on its notches and the
given orientation.
:param orientation | <Qt.Orientation>
:return <int> | def minLength( self, orientation ):
padding = self.padStart() + self.padEnd()
count = len(self.notches())
notch_padding = self.notchPadding()
if ( orientation == Qt.Horizontal ):
section = self.maxNotchSize(Qt.Vertical)
else:
section = self.maxNotchSize(Qt.Horizontal)
return notch_padding * count + section * count + padding |
// SetName sets the Name field's value. | func (s *InstanceProfile) SetName(v string) *InstanceProfile {
s.Name = &v
return s
} |
// TcpProfiles returns a list of Tcp profiles | func (b *BigIP) TcpProfiles() (*TcpProfiles, error) {
var tcpProfiles TcpProfiles
err, _ := b.getForEntity(&tcpProfiles, uriLtm, uriProfile, uriTcp)
if err != nil {
return nil, err
}
return &tcpProfiles, nil
} |
Gets the absolute path.
@param file
the file
@param removeLastChar
the remove last char
@return the absolute path | public static String getAbsolutePath(final File file, final boolean removeLastChar)
{
String absolutePath = file.getAbsolutePath();
if (removeLastChar)
{
absolutePath = absolutePath.substring(0, absolutePath.length() - 1);
}
return absolutePath;
} |
Return a taskfileinfo that the user chose from the available options
:returns: the chosen taskfileinfo
:rtype: :class:`jukeboxcore.filesys.TaskFileInfo`
:raises: None | def get_taskfileinfo_selection(self, ):
sel = OptionSelector(self.reftrack)
sel.exec_()
return sel.selected |
// URL-safe base64 encode that strips padding | func base64URLEncode(data []byte) string {
var result = base64.URLEncoding.EncodeToString(data)
return strings.TrimRight(result, "=")
} |
// SetSecretOptions sets the SecretOptions field's value. | func (s *LogConfiguration) SetSecretOptions(v []*Secret) *LogConfiguration {
s.SecretOptions = v
return s
} |
// RemoveContainers removes running k8s pods | func (runtime *CRIRuntime) RemoveContainers(containers []string) error {
errs := []error{}
for _, container := range containers {
out, err := runtime.exec.Command("crictl", "-r", runtime.criSocket, "stopp", container).CombinedOutput()
if err != nil {
// don't stop on errors, try to remove as many containers as possible
errs = append(errs, errors.Wrapf(err, "failed to stop running pod %s: output: %s, error", container, string(out)))
} else {
out, err = runtime.exec.Command("crictl", "-r", runtime.criSocket, "rmp", container).CombinedOutput()
if err != nil {
errs = append(errs, errors.Wrapf(err, "failed to remove running container %s: output: %s, error", container, string(out)))
}
}
}
return errorsutil.NewAggregate(errs)
} |
Pop a node from the tail of the vector and return the
top of the stack after the pop.
@return The top of the stack after it's been popped | public final Node popAndTop()
{
m_firstFree--;
m_map[m_firstFree] = null;
return (m_firstFree == 0) ? null : m_map[m_firstFree - 1];
} |
声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列
:param exchange_name:
:param routing_key:
:param queue_name:
:param callback:
:return: | def declare_consuming(self, exchange_name, routing_key, queue_name, callback):
self.bind_topic_exchange(exchange_name, routing_key, queue_name)
self.basic_consuming(
queue_name=queue_name,
callback=callback
) |
// NewApplicationListCommand returns a new instance of an `argocd app list` command | func NewApplicationListCommand(clientOpts *argocdclient.ClientOptions) *cobra.Command {
var (
output string
)
var command = &cobra.Command{
Use: "list",
Short: "List applications",
Run: func(c *cobra.Command, args []string) {
conn, appIf := argocdclient.NewClientOrDie(clientOpts).NewApplicationClientOrDie()
defer util.Close(conn)
apps, err := appIf.List(context.Background(), &application.ApplicationQuery{})
errors.CheckError(err)
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
var fmtStr string
headers := []interface{}{"NAME", "CLUSTER", "NAMESPACE", "PROJECT", "STATUS", "HEALTH", "SYNCPOLICY", "CONDITIONS"}
if output == "wide" {
fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
headers = append(headers, "REPO", "PATH", "TARGET")
} else {
fmtStr = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"
}
fmt.Fprintf(w, fmtStr, headers...)
for _, app := range apps.Items {
vals := []interface{}{
app.Name,
app.Spec.Destination.Server,
app.Spec.Destination.Namespace,
app.Spec.GetProject(),
app.Status.Sync.Status,
app.Status.Health.Status,
formatSyncPolicy(app),
formatConditionsSummary(app),
}
if output == "wide" {
vals = append(vals, app.Spec.Source.RepoURL, app.Spec.Source.Path, app.Spec.Source.TargetRevision)
}
fmt.Fprintf(w, fmtStr, vals...)
}
_ = w.Flush()
},
}
command.Flags().StringVarP(&output, "output", "o", "", "Output format. One of: wide")
return command
} |
Trys to read a properties file.
Returns null if properties file could not be loaded
@param _file
@return Properties Object or null | public static Properties readProperties(File _file) {
if (_file.exists()) {
try {
return readProperties(new FileInputStream(_file));
} catch (FileNotFoundException _ex) {
LOGGER.info("Could not load properties file: " + _file, _ex);
}
}
return null;
} |
Get the vacuums current fan speed setting.
@return The fan speed.
@throws CommandExecutionException When there has been a error during the communication or the response was invalid. | public int getFanSpeed() throws CommandExecutionException {
int resp = sendToArray("get_custom_mode").optInt(0, -1);
if ((resp < 0) || (resp > 100)) throw new CommandExecutionException(CommandExecutionException.Error.INVALID_RESPONSE);
return resp;
} |
// ListKeys returns a list of all the keys of the objects currently
// in the FIFO. | func (f *DeltaFIFO) ListKeys() []string {
f.lock.RLock()
defer f.lock.RUnlock()
list := make([]string, 0, len(f.items))
for key := range f.items {
list = append(list, key)
}
return list
} |
add custom KRYO serialization | private static Map mapifySerializations(List sers) {
Map rtn = new HashMap();
if (sers != null) {
int size = sers.size();
for (int i = 0; i < size; i++) {
if (sers.get(i) instanceof Map) {
rtn.putAll((Map) sers.get(i));
} else {
rtn.put(sers.get(i), null);
}
}
}
return rtn;
} |
Get the "Preview <element>" link.
@since 0.1.0
@param string $permalink Permalink to the current post.
@param ArgumentCollection $args Collection of arguments.
@return string HTML link to preview the post. | protected function getPreviewLink( $permalink, $args ) {
if ( ! $permalink ) {
return '';
}
$preview_permalink = add_query_arg( 'preview', 'true', $permalink );
return sprintf(
' <a target="_blank" href="%s">%s</a>',
esc_url( $preview_permalink ),
$args[ Argument::LINKS ][ Link::PREVIEW_LINK ]
);
} |
return all association categories
@return Categories | public function findAssociationCategories()
{
$xmlQuery = $this->metaApiService->getAssociationCategories();
$categories = new Categories();
$mapper = new \RGU\Dvoconnector\Mapper\AssociationCategories($xmlQuery);
$mapper->mapToAbstractEntity($categories);
return $categories;
} |
TODO
@param $data
@param $params
@return string | public function display($data, $params)
{
$this->getResponse()->setContentType('application/json; charset=utf-8;');
$result = array();
$header = array();
//$messages = array();
foreach ($this->messages as $message) {
$result[$message['type']][] = $message['message'];
}
$header['date'] = date('Y-m-d H:i:s');
$header['controller'] = get_class($this);
$result['header'] = $header;
if ($data instanceof Model || $data instanceof ModelResult) {
$result['data'] = $data->json();
} else {
$result['data'] = $data;
}
$options = 0;
if (isset($_GET['pretty'])) {
$options = 128;
}
return json_encode($result, $options);
} |
// PushBackUniq inserts a new Element e with value v at the back of list l and returns e. | func (l *List) PushBackUniq(v string) *Element {
l.lazyInit()
l.lazyInit()
e := l.Find(v)
if e == nil {
e = &Element{Value: v}
} else {
l.remove(e)
}
l.insert(e, l.root.prev)
return e
} |
Check if the given field is valid or not.
@return boolean | public function isValid()
{
/**
* First, check if the upload is valid or not
*/
if (!parent::isValid()) {
return false;
}
$value = $this->field->getValue();
// if here, we know that the field is uploaded.
// check if it's an image, and get it's size
$size = @getimagesize($value['tmp_name']);
if ($size === false) {
$this->setErrorMessage($this->messages['not_an_image']);
return false;
}
list ($width, $height) = $size;
/**
* Validate the aspect ratio.
*/
if (!$this->validateAspectRatio($width, $height)) {
return false;
}
/**
* Validate the proportions
*/
if (!$this->validateSize($width, $height)) {
return false;
}
// if here, everything is ok!
return true;
} |
Add a new Header with the given name/value, or replace an existing value
if a Header already exists with name
@param name
@param value | public void set(String name, String value) {
HttpHeader header = get(name);
if(header == null) {
add(name,value);
} else {
header.setValue(value);
}
} |
This may be overridden by a subclass. | def run(self, *args, **kw):
if self._runFunc is not None:
# remove the two args sent by EditParDialog which we do not use
if 'mode' in kw: kw.pop('mode')
if '_save' in kw: kw.pop('_save')
return self._runFunc(self, *args, **kw)
else:
raise taskpars.NoExecError('No way to run task "'+self.__taskName+\
'". You must either override the "run" method in your '+ \
'ConfigObjPars subclass, or you must supply a "run" '+ \
'function in your package.') |
Increment the semantic version number.
@param $version
@param int $patch_limit
@param int $minor_limit
@return string | protected function incrementVersion($version, $patch_limit = 20, $minor_limit = 50)
{
if (!$this->isVersionNumeric($version)) {
throw new DeploymentRuntimeException(
'Unable to increment semantic version.'
);
}
list($major, $minor, $patch) = explode('.', $version);
if ($patch < $patch_limit) {
++$patch;
} else if ($minor < $minor_limit) {
++$minor;
$patch = 0;
} else {
++$major;
$patch = 0;
$minor = 0;
}
return "{$major}.{$minor}.{$patch}";
} |
// Finalise finalises the state by removing the self destructed objects
// and clears the journal as well as the refunds. | func (s *StateDB) Finalise(deleteEmptyObjects bool) {
for addr := range s.journal.dirties {
stateObject, exist := s.stateObjects[addr]
if !exist {
// ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
// That tx goes out of gas, and although the notion of 'touched' does not exist there, the
// touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
// it will persist in the journal even though the journal is reverted. In this special circumstance,
// it may exist in `s.journal.dirties` but not in `s.stateObjects`.
// Thus, we can safely ignore it here
continue
}
if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) {
s.deleteStateObject(stateObject)
} else {
stateObject.updateRoot(s.db)
s.updateStateObject(stateObject)
}
s.stateObjectsDirty[addr] = struct{}{}
}
// Invalidate journal because reverting across transactions is not allowed.
s.clearJournalAndRefund()
} |
// GetBuild returns a milo build from a swarming task id. | func GetBuild(c context.Context, host, taskId string) (*ui.MiloBuildLegacy, error) {
if taskId == "" {
return nil, errors.New("no swarming task id", grpcutil.InvalidArgumentTag)
}
sf, err := NewProdService(c, host)
if err != nil {
return nil, err
}
return SwarmingBuildImpl(c, sf, taskId)
} |
Process callbacks for a given event
@param string $eventName
@param File $file
@return void | protected function processCallbacksFor($eventName, File $file)
{
if (! array_key_exists($eventName, $this->callbacks) || empty($this->callbacks[$eventName])) {
return;
}
foreach ($this->callbacks[$eventName] as $callback) {
$callback($file);
}
} |
Method copy-pasted from symfony/serializer.
Remove it after symfony/serializer version update @link https://github.com/symfony/symfony/pull/28263.
{@inheritdoc}
@internal | protected function instantiateObject(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes, string $format = null)
{
if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
unset($context[static::OBJECT_TO_POPULATE]);
return $object;
}
if ($this->classDiscriminatorResolver && $mapping = $this->classDiscriminatorResolver->getMappingForClass($class)) {
if (!isset($data[$mapping->getTypeProperty()])) {
throw new RuntimeException(sprintf('Type property "%s" not found for the abstract object "%s"', $mapping->getTypeProperty(), $class));
}
$type = $data[$mapping->getTypeProperty()];
if (null === ($mappedClass = $mapping->getClassForType($type))) {
throw new RuntimeException(sprintf('The type "%s" has no mapped class for the abstract object "%s"', $type, $class));
}
$class = $mappedClass;
$reflectionClass = new \ReflectionClass($class);
}
$constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
if ($constructor) {
$constructorParameters = $constructor->getParameters();
$params = [];
foreach ($constructorParameters as $constructorParameter) {
$paramName = $constructorParameter->name;
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
$allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
$ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
if ($constructorParameter->isVariadic()) {
if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
if (!\is_array($data[$paramName])) {
throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
}
$params = array_merge($params, $data[$paramName]);
}
} elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
$params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $context, $format);
// Don't run set for a parameter passed to the constructor
unset($data[$key]);
} elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
$params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
} elseif ($constructorParameter->isDefaultValueAvailable()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new MissingConstructorArgumentsException(
sprintf(
'Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.',
$class,
$constructorParameter->name
)
);
}
}
if ($constructor->isConstructor()) {
return $reflectionClass->newInstanceArgs($params);
}
return $constructor->invokeArgs(null, $params);
}
return new $class();
} |
This method is invoked in case of authentication cancelation.
@param ClientInterface $client auth client instance.
@return Response response instance.
@since 2.1.5 | protected function authCancel($client)
{
if ($this->cancelCallback !== null) {
$response = call_user_func($this->cancelCallback, $client);
if ($response instanceof Response) {
return $response;
}
}
return $this->redirectCancel();
} |
Returns the object manager instance
@return ObjectManagerInterface
@throws FlowException | public function getObjectManager(): ObjectManagerInterface
{
if (!isset($this->earlyInstances[ObjectManagerInterface::class])) {
debug_print_backtrace();
throw new FlowException('The Object Manager is not available at this stage of the bootstrap run.', 1301120788);
}
return $this->earlyInstances[ObjectManagerInterface::class];
} |
Use this API to fetch all the nsxmlnamespace resources that are configured on netscaler. | public static nsxmlnamespace[] get(nitro_service service) throws Exception{
nsxmlnamespace obj = new nsxmlnamespace();
nsxmlnamespace[] response = (nsxmlnamespace[])obj.get_resources(service);
return response;
} |
Update EFT bank account
@param CustomerVault\Profile $profile
@param CustomerVault\EFTBankaccounts $bankDetails
@return \Paysafe\CustomerVault\Profile
@throws PaysafeException | public function updateEFTBankAccount( CustomerVault\Profile $profile, CustomerVault\EFTBankaccounts $bankDetails )
{
$profile->setRequiredFields(array('id'));
$profile->checkRequiredFields();
$bankDetails->setRequiredFields(array(
'transitNumber',
'institutionId',
'accountHolderName',
'billingAddressId'
));
$bankDetails->checkRequiredFields();
$bankDetails->setOptionalFields(array(
'nickName',
'merchantRefNum',
'accountNumber'
));
$request = new Request(array(
'method' => Request::PUT,
'uri' => $this->prepareURI("/profiles/" . $profile->id . "/eftbankaccounts/" . $bankDetails->id),
'body' => $bankDetails
));
$response = $this->client->processRequest($request);
return new CustomerVault\EFTBankaccounts($response);
} |