comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Calls the specified handler when this promise is fulfilled.
If the handler returns a promise,
@param callable $handler
@return PromiseInterface | public function to($handler /*, $args… */)
{
$args = array_slice(func_get_args(), 1);
return $this->then(
function (Allocation $allocation) use ($handler, $args) {
try {
$result = call_user_func_array($handler, $args);
$result = \React\Promise\resolve($result);
$result->then(array($allocation, 'releaseAll'), array($allocation, 'releaseAll'));
} catch (\Exception $e) {
$result = new RejectedPromise($e);
$allocation->releaseAll();
}
return $result;
}
);
} |
Make JsonResponse
:param rv: Response: the object to encode, or tuple (response, status, headers)
:type rv: tuple|*
:rtype: JsonResponse | def make_json_response(rv):
# Tuple of (response, status, headers)
rv, status, headers = normalize_response_value(rv)
# JsonResponse
if isinstance(rv, JsonResponse):
return rv
# Data
return JsonResponse(rv, status, headers) |
Computes the bounding circle
@param geometry
@return | public static Geometry computeBoundingCircle(Geometry geometry) {
if (geometry == null) {
return null;
}
return new MinimumBoundingCircle(geometry).getCircle();
} |
// NewMockClientFacade creates a new mock instance | func NewMockClientFacade(ctrl *gomock.Controller) *MockClientFacade {
mock := &MockClientFacade{ctrl: ctrl}
mock.recorder = &MockClientFacadeMockRecorder{mock}
return mock
} |
Describes tget_grades_table return value.
@return external_single_structure
@since Moodle 2.9 | public static function get_grades_table_returns() {
return new external_single_structure(
array(
'tables' => new external_multiple_structure(
new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'course id'),
'userid' => new external_value(PARAM_INT, 'user id'),
'userfullname' => new external_value(PARAM_TEXT, 'user fullname'),
'maxdepth' => new external_value(PARAM_INT, 'table max depth (needed for printing it)'),
'tabledata' => new external_multiple_structure(
new external_single_structure(
array(
'itemname' => new external_single_structure(
array (
'class' => new external_value(PARAM_RAW, 'class'),
'colspan' => new external_value(PARAM_INT, 'col span'),
'content' => new external_value(PARAM_RAW, 'cell content'),
'celltype' => new external_value(PARAM_RAW, 'cell type'),
'id' => new external_value(PARAM_ALPHANUMEXT, 'id')
), 'The item returned data', VALUE_OPTIONAL
),
'leader' => new external_single_structure(
array (
'class' => new external_value(PARAM_RAW, 'class'),
'rowspan' => new external_value(PARAM_INT, 'row span')
), 'The item returned data', VALUE_OPTIONAL
),
'weight' => new external_single_structure(
self::grades_table_column(), 'weight column', VALUE_OPTIONAL
),
'grade' => new external_single_structure(
self::grades_table_column(), 'grade column', VALUE_OPTIONAL
),
'range' => new external_single_structure(
self::grades_table_column(), 'range column', VALUE_OPTIONAL
),
'percentage' => new external_single_structure(
self::grades_table_column(), 'percentage column', VALUE_OPTIONAL
),
'lettergrade' => new external_single_structure(
self::grades_table_column(), 'lettergrade column', VALUE_OPTIONAL
),
'rank' => new external_single_structure(
self::grades_table_column(), 'rank column', VALUE_OPTIONAL
),
'average' => new external_single_structure(
self::grades_table_column(), 'average column', VALUE_OPTIONAL
),
'feedback' => new external_single_structure(
self::grades_table_column(), 'feedback column', VALUE_OPTIONAL
),
'contributiontocoursetotal' => new external_single_structure(
self::grades_table_column(), 'contributiontocoursetotal column', VALUE_OPTIONAL
),
), 'table'
)
)
)
)
),
'warnings' => new external_warnings()
)
);
} |
/*
getWsagObject receives in serializedData the object information in xml
must returns a eu.atos.sla.parser.data.wsag.Agreement | @Override
public Agreement getWsagObject(String serializedData) throws ParserException{
Agreement agreementXML = null;
try{
logger.info("Will parse {}", serializedData);
JAXBContext jaxbContext = JAXBContext.newInstance(Agreement.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
jaxbUnmarshaller.setEventHandler(new ValidationHandler());
agreementXML = (Agreement)jaxbUnmarshaller.unmarshal(new StringReader(serializedData));
logger.info("Agreement parsed {}", agreementXML);
}catch(JAXBException e){
throw new ParserException(e);
}
return agreementXML;
} |
Visit the given $query parameters into hash representation. | private function visitParameters(Query $query, VisitorInterface $subVisitor): array
{
$parametersByLanguage = [
$query->getLocale() => iterator_to_array(
$this->visitTranslationParameters($query, $subVisitor)
),
];
foreach ($query->getAvailableLocales() as $availableLocale) {
if ($availableLocale === $query->getLocale()) {
continue;
}
$translatedQuery = $this->collectionService->loadQuery(
$query->getId(),
[$availableLocale],
false
);
$parametersByLanguage[$availableLocale] = iterator_to_array(
$this->visitTranslationParameters(
$translatedQuery,
$subVisitor
)
);
}
ksort($parametersByLanguage);
return $parametersByLanguage;
} |
Try to restore user from data in session.
@return void | protected static function restoreFromSession()
{
$session = Http\Session::getInstance();
try {
$mapper = new UserMapper(Database::get());
$user = $mapper->findFromSession($session);
} catch (\Exception $exception) {
$user = new Data\User\User();
}
static::$user = $user;
} |
// Init will initialize or reset a StringTree. | func (t *StringTree) Init(flags byte) *StringTree {
t.Tree.Init(stringCompare, flags)
return t
} |
Resize the given BufferedImage.
@param originalImage
the original image
@param formatName
the format name
@param targetWidth
the target width
@param targetHeight
the target height
@return the byte[] | public static byte[] resize(final BufferedImage originalImage, final String formatName,
final int targetWidth, final int targetHeight)
{
return resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, formatName,
targetWidth, targetHeight);
} |
Close a ResultSet
@param rs a database ResultSet object | public static void closeResultSet(final ResultSet rs) {
if (rs == null) {
return;
}
try {
rs.close();
} catch (Exception e) {
if (LOG.isWarnEnabled()) LOG.warn("Error closing ResultSet: " + rs, e);
}
} |
Recurse through the data tree and fill an array of paths that reference
the nodes in the decoded JSON data structure.
@param mixed $s Decoded JSON data (decoded with json_decode)
@param string $r The current path key (for example: '#children.0'). | private function getPaths(&$s, $r = "#")
{
$this->paths[$r] = &$s;
if (is_array($s) || is_object($s)) {
foreach ($s as $k => &$v) {
if ($k !== "\$ref") {
$this->getPaths($v, $r == "#" ? "#{$k}" : "{$r}.{$k}");
}
}
}
} |
TODO handler.addTo | function (name, HandlerClass) {
if (!HandlerClass) { return this; }
var handler = this[name] = new HandlerClass(this);
this._handlers.push(handler);
if (this.options[name]) {
handler.enable();
}
return this;
} |
expression : LNOT expression %prec ULNOT | def p_expression_ulnot(self, p):
''
p[0] = Ulnot(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
Checks if the current user has the specified role.
@param roleNames the names of the required roles
@return true iff the current user has the specified role | public static boolean hasRoles(List<String> roleNames) throws Throwable
{
DEADBOLT_HANDLER.beforeRoleCheck();
RoleHolder roleHolder = getRoleHolder();
return roleHolder != null &&
roleHolder.getRoles() != null &&
hasAllRoles(roleHolder,
roleNames.toArray(new String[roleNames.size()]));
} |
Create an instance of {@link JAXBElement }{@code <}{@link ArithType }{@code >}} | @XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "abs")
public JAXBElement<ArithType> createAbs(ArithType value) {
return new JAXBElement<ArithType>(_Abs_QNAME, ArithType.class, null, value);
} |
// SetStatus sets the completion status of the Package. | func (p *Package) SetStatus(inc JobStatus) {
p.statusLock.Lock()
defer p.statusLock.Unlock()
p.status = inc
} |
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent
@raise WindowsError if any underlying error occures. | def get_low_battery_warning_level(self):
power_status = SYSTEM_POWER_STATUS()
if not GetSystemPowerStatus(pointer(power_status)):
raise WinError()
if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC:
return common.LOW_BATTERY_WARNING_NONE
else:
if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600:
return common.LOW_BATTERY_WARNING_FINAL
elif power_status.BatteryLifePercent <= 22:
return common.LOW_BATTERY_WARNING_EARLY
else:
return common.LOW_BATTERY_WARNING_NONE |
Create a CryptKey instance without permissions check.
@param string $key
@return \League\OAuth2\Server\CryptKey | protected function makeCryptKey($type)
{
$key = str_replace('\\n', "\n", $this->app->make(Config::class)->get('passport.'.$type.'_key'));
if (! $key) {
$key = 'file://'.Passport::keyPath('oauth-'.$type.'.key');
}
return new CryptKey($key, null, false);
} |
Gets a configuration.
@param key the configuration key
@return a map, or null if the key is not found | public synchronized Map<String, Object> getConfiguration(String key) {
return Optional.ofNullable(inventory.get(key))
.flatMap(v->v.getConfiguration())
.map(v->v.getMap())
.orElse(null);
} |
// Start starts the scheduler | func (s *scheduler) Start() error {
if s.metricManager == nil {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
"_error": ErrMetricManagerNotSet.Error(),
}).Error("error on scheduler start")
return ErrMetricManagerNotSet
}
s.state = schedulerStarted
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
}).Info("scheduler started")
//Autodiscover
autoDiscoverPaths := s.metricManager.GetAutodiscoverPaths()
if autoDiscoverPaths != nil && len(autoDiscoverPaths) != 0 {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
}).Info("auto discover path is enabled")
for _, pa := range autoDiscoverPaths {
fullPath, err := filepath.Abs(pa)
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
"autodiscoverpath": pa,
}).Fatal(err)
}
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
}).Info("autoloading tasks from: ", fullPath)
files, err := ioutil.ReadDir(fullPath)
if err != nil {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
"autodiscoverpath": pa,
}).Fatal(err)
}
var taskFiles []os.FileInfo
for _, file := range files {
if file.IsDir() {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
"autodiscoverpath": pa,
}).Warning("Ignoring subdirectory: ", file.Name())
continue
}
// tasks files (JSON and YAML)
fname := strings.ToLower(file.Name())
if !strings.HasSuffix(fname, ".json") && !strings.HasSuffix(fname, ".yaml") && !strings.HasSuffix(fname, ".yml") {
continue
}
taskFiles = append(taskFiles, file)
}
autoDiscoverTasks(taskFiles, fullPath, s.CreateTask)
}
} else {
schedulerLogger.WithFields(log.Fields{
"_block": "start-scheduler",
}).Info("auto discover path is disabled")
}
return nil
} |
A specific, existing tag can be deleted by making a DELETE request
on the URL for that tag.
Returns an empty data record.
@param tag The tag to delete.
@return response | public function delete($tag, $params = array(), $options = array())
{
$path = sprintf("/tags/%s", $tag);
return $this->client->delete($path, $params, $options);
} |
Validate a value
@param mixed $value Value to be validated
@return bool True when the variable is valid | public function validate($value)
{
$result = false;
if (is_string($value) && strlen($value))
{
if ($value[0] == '/' || $value[0] == '\\'
|| (strlen($value) > 3 && ctype_alpha($value[0])
&& $value[1] == ':'
&& ($value[2] == '\\' || $value[2] == '/')
)
|| null !== parse_url($value, PHP_URL_SCHEME)
) {
$result = true;
}
}
return $result;
} |
Saves the service and types php code to file
@param PhpClass $service
@param array $types | public function save(PhpClass $service, array $types)
{
$this->setOutputDirectory();
$this->saveClassToFile($service);
foreach ($types as $type) {
$this->saveClassToFile($type);
}
$classes = array_merge(array($service), $types);
$this->saveAutoloader($service->getIdentifier(), $classes);
} |
Gets the list of entries in the specified directory.
@param directory the directory to get the entries of.
@return the list of entries (never <code>null</code>).
@since 1.0 | private synchronized List<Entry> getEntriesList( DirectoryEntry directory )
{
List<Entry> entries = contents.get( directory );
if ( entries == null )
{
entries = new ArrayList<Entry>();
contents.put( directory, entries );
}
return entries;
} |
Checks, that option exists in config.
@param string $name Option name.
@return void
@throws ConfigException Thrown when option with a given name doesn't exist. | protected function assertOptionName($name)
{
if ( !isset($this->options[$name]) ) {
throw new ConfigException(
'Option "' . $name . '" doesn\'t exist in configuration',
ConfigException::TYPE_NOT_FOUND
);
}
} |
// WeekdayShort returns the locales short weekday given the 'weekday' provided | func (kkj *kkj_CM) WeekdayShort(weekday time.Weekday) string {
return kkj.daysShort[weekday]
} |
// For any index defined by IndexFields, if a matcher can match only (a subset)
// of objects that return <value> for a given index, a pair (<index name>, <value>)
// wil be returned.
// TODO: Consider supporting also labels. | func (s *SelectionPredicate) MatcherIndex() []MatchValue {
var result []MatchValue
for _, field := range s.IndexFields {
if value, ok := s.Field.RequiresExactMatch(field); ok {
result = append(result, MatchValue{IndexName: field, Value: value})
}
}
return result
} |
// SetId sets the Id field's value. | func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput {
s.Id = &v
return s
} |
Overloaded to display the correctly formatted value for this data type
@param array $properties
@return string | public function Field($properties = array())
{
if ($this->value) {
$val = Convert::raw2xml($this->value);
$val = DBCurrency::config()->get('currency_symbol')
. number_format(preg_replace('/[^0-9.-]/', '', $val), 2);
$valforInput = Convert::raw2att($val);
} else {
$valforInput = '';
}
return "<input class=\"text\" type=\"text\" disabled=\"disabled\""
. " name=\"" . $this->name . "\" value=\"" . $valforInput . "\" />";
} |
分词时查询到一个用户词典中的词语,此处控制是否接受它
@param begin 起始位置
@param end 终止位置
@param value 词性
@return true 表示接受
@deprecated 自1.6.7起废弃,强制模式下为最长匹配,否则按分词结果合并 | protected boolean acceptCustomWord(int begin, int end, CoreDictionary.Attribute value)
{
return config.forceCustomDictionary || (end - begin >= 4 && !value.hasNatureStartsWith("nr") && !value.hasNatureStartsWith("ns") && !value.hasNatureStartsWith("nt"));
} |
是否可以删除缓存
@param cacheDeleteKey CacheDeleteKey注解
@param arguments 参数
@param retVal 结果值
@return Can Delete
@throws Exception 异常 | public boolean isCanDelete(CacheDeleteKey cacheDeleteKey, Object[] arguments, Object retVal) throws Exception {
boolean rv = true;
if (null != arguments && arguments.length > 0 && null != cacheDeleteKey.condition()
&& cacheDeleteKey.condition().length() > 0) {
rv = this.getElValue(cacheDeleteKey.condition(), null, arguments, retVal, true, Boolean.class);
}
return rv;
} |
Factory function that creates a value.
:param value_id: id of the value, used to reference the value within this list.BaseException
:param value_class: The class of the value that should be created with this function. | def add(self, value_id, name, value_class):
item = value_class(
name,
value_id=self.controller.component_id + "." + value_id,
is_input=self.is_input,
index=self.count,
spine = self.controller.spine
)
#if self._inject and self.controller:
# setattr(self.controller, value_id, item)
#setattr(self, value_id, item)
self.count += 1
self._items[value_id] = item
if self.is_input and self.controller:
item.add_observer(self.controller)
return item |
Updates the state machine context. | void update(long index, Instant instant, Type type) {
this.index = index;
this.type = type;
clock.set(instant);
} |
Creates a {@link UTF8StreamJsonParser} from the inputstream with the supplied buf {@code inBuffer} to use. | public static UTF8StreamJsonParser newJsonParser(InputStream in, byte[] buf,
int offset, int limit) throws IOException
{
return newJsonParser(in, buf, offset, limit, false,
new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), in,
false));
} |
// LoadGopmfile loads and returns given gopmfile. | func LoadGopmfile(fileName string) (*goconfig.ConfigFile, error) {
if !base.IsFile(fileName) {
return goconfig.LoadFromData([]byte(""))
}
gf, err := goconfig.LoadConfigFile(fileName)
if err != nil {
return nil, fmt.Errorf("Fail to load gopmfile: %v", err)
}
return gf, nil
} |
Loads a collection from the database
@param array|int|string $condition
@return array | public function get($condition)
{
$result = null;
$this->hook->attach('collection.get.before', $condition, $result, $this);
if (isset($result)) {
return $result;
}
if (!is_array($condition)) {
$condition = array('collection_id' => $condition);
}
$condition['limit'] = array(0, 1);
$list = (array) $this->getList($condition);
$result = empty($list) ? array() : reset($list);
$this->hook->attach('collection.get.after', $condition, $result, $this);
return $result;
} |
Performs a forward pass using multiple GPUs. This is a simplification
of torch.nn.parallel.data_parallel to support the allennlp model
interface. | def data_parallel(batch_group: List[TensorDict],
model: Model,
cuda_devices: List) -> Dict[str, torch.Tensor]:
assert len(batch_group) <= len(cuda_devices)
moved = [nn_util.move_to_device(batch, device)
for batch, device in zip(batch_group, cuda_devices)]
used_device_ids = cuda_devices[:len(moved)]
# Counterintuitively, it appears replicate expects the source device id to be the first element
# in the device id list. See torch.cuda.comm.broadcast_coalesced, which is called indirectly.
replicas = replicate(model, used_device_ids)
# We pass all our arguments as kwargs. Create a list of empty tuples of the
# correct shape to serve as (non-existent) positional arguments.
inputs = [()] * len(batch_group)
outputs = parallel_apply(replicas, inputs, moved, used_device_ids)
# Only the 'loss' is needed.
# a (num_gpu, ) tensor with loss on each GPU
losses = gather([output['loss'].unsqueeze(0) for output in outputs], used_device_ids[0], 0)
return {'loss': losses.mean()} |
Randomly augment a single image tensor.
# Arguments
sample: 3D or 4D tensor, single sample.
seed: random seed.
# Returns
A randomly transformed version of the input (same shape). | def random_transform(self, sample, seed=None):
img_row_axis = self.row_axis - 1
img_col_axis = self.col_axis - 1
img_channel_axis = self.channel_axis - 1
transform_matrix = self.get_random_transform_matrix(sample, seed)
if transform_matrix is not None:
h, w = sample.shape[img_row_axis], sample.shape[img_col_axis]
transform_matrix = transform_matrix_offset_center(transform_matrix, h, w)
sample = apply_transform(sample, transform_matrix, img_channel_axis,
fill_mode=self.fill_mode, cval=self.cval)
if self.channel_shift_range != 0:
sample = random_channel_shift(sample,
self.channel_shift_range,
img_channel_axis)
if self.horizontal_flip:
if np.random.random() < 0.5:
sample = flip_axis(sample, img_col_axis)
if self.vertical_flip:
if np.random.random() < 0.5:
sample = flip_axis(sample, img_row_axis)
return sample |
Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ResourceSkuInner> object | public Observable<Page<ResourceSkuInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<ResourceSkuInner>>, Page<ResourceSkuInner>>() {
@Override
public Page<ResourceSkuInner> call(ServiceResponse<Page<ResourceSkuInner>> response) {
return response.body();
}
});
} |
// Machine provides access to methods of a state.Machine through the facade. | func (st *State) Machine(tag names.MachineTag) (*Machine, error) {
life, err := st.machineLife(tag)
if err != nil {
return nil, errors.Annotate(err, "can't get life for machine")
}
return &Machine{
tag: tag,
life: life,
st: st,
}, nil
} |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__OBJ_TYPE:
setObjType(OBJ_TYPE_EDEFAULT);
return;
case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__ARCH_VRSN:
setArchVrsn(ARCH_VRSN_EDEFAULT);
return;
case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__DCA_FN_SET:
setDCAFnSet(DCA_FN_SET_EDEFAULT);
return;
case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__OCA_FN_SET:
setOCAFnSet(OCA_FN_SET_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
Tries to find a directory with a .git repository | def find_git_repository(self, path):
while path is not None:
git_path = os.path.join(path,'.git')
if os.path.exists(git_path) and os.path.isdir(git_path):
return path
path = os.path.dirname(path)
return None |
指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。<br>
本メソッド呼び出しによってデータセットの更新は行われない。<br>
学習データの更新を伴わないため、高速に処理が可能となっている。
@param kn K値
@param targetPoint 対象点
@param dataSet 学習データセット
@return LOFスコア | public static double calculateLofWithoutUpdate(int kn, LofPoint targetPoint, LofDataSet dataSet)
{
// 対象点のK距離、K距離近傍を算出する。
KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet);
LofPoint tmpPoint = targetPoint.deepCopy();
tmpPoint.setkDistance(kResult.getkDistance());
tmpPoint.setkDistanceNeighbor(kResult.getkDistanceNeighbor());
updateLrd(tmpPoint, dataSet);
// 対象の局所外れ係数を算出する。
double lof = calculateLof(tmpPoint, dataSet);
return lof;
} |
Sets the time zone for which this <code>Calendar</code> will be resolved.
@param \DateTimeZone $timeZone The time zone to use for this Calendar, null if default should be used | public function setTimeZone(\DateTimeZone $timeZone = null)
{
if ($timeZone) {
$value = $timeZone->getName();
} else {
$value = null;
}
$this->setValue('timezone', $value);
} |
Builds thumb uploader
@param string $dir Target directory
@param integer $quality Desired quality for thumbs
@param array $options
@return \Krystal\Image\Tool\Upload\Plugin\ThumbFactory | public function build($dir, $quality, array $options = array())
{
// Alter default quality on demand
if (isset($options['quality'])) {
$quality = $options['quality'];
}
return new Thumb($dir, $options['dimensions'], $quality);
} |
Parses a PHP File and returns nested Array of collected Information.
@access public
@param string $fileName File Name of PHP File to parse
@param string $innerPath Base Path to File to be removed in Information
@return array | public function parseFile( $fileName, $innerPath )
{
$content = FS_File_Reader::load( $fileName );
if( !Alg_Text_Unicoder::isUnicode( $content ) )
$content = Alg_Text_Unicoder::convertToUnicode( $content );
$lines = explode( "\n", $content );
$fileBlock = NULL;
$openClass = FALSE;
$function = NULL;
$functionBody = array();
$file = new ADT_PHP_File;
$file->setBasename( basename( $fileName ) );
$file->setPathname( substr( str_replace( "\\", "/", $fileName ), strlen( $innerPath ) ) );
$file->setUri( str_replace( "\\", "/", $fileName ) );
$level = 0;
$class = NULL;
do
{
$line = trim( array_shift( $lines ) );
# remark( ( $openClass ? "I" : "O" )." :: ".$level." :: ".$this->lineNumber." :: ".$line );
$this->lineNumber ++;
if( preg_match( "@^(<\?(php)?)|((php)?\?>)$@", $line ) )
continue;
if( preg_match( '@}$@', $line ) )
$level--;
if( $line == "/**" && $level < 2 )
{
$list = array();
while( !preg_match( "@\*?\*/\s*$@", $line ) )
{
$list[] = $line;
$line = trim( array_shift( $lines ) );
$this->lineNumber ++;
}
array_unshift( $lines, $line );
$this->lineNumber --;
if( $list )
{
$this->openBlocks[] = $this->parseDocBlock( $list );
if( !$fileBlock && !$class )
{
$fileBlock = array_shift( $this->openBlocks );
array_unshift( $this->openBlocks, $fileBlock );
$this->decorateCodeDataWithDocData( $file, $fileBlock );
}
}
continue;
}
if( !$openClass )
{
if( preg_match( $this->regexClass, $line, $matches ) )
{
$parts = array_slice( $matches, -1 );
while( !trim( array_pop( $parts ) ) )
array_pop( $matches );
$class = $this->parseClassOrInterface( $file, $matches );
$openClass = TRUE;
}
else if( preg_match( $this->regexMethod, $line, $matches ) )
{
$openClass = FALSE;
$function = $this->parseFunction( $file, $matches );
$file->setFunction( $function );
}
}
else
{
if( preg_match( $this->regexClass, $line, $matches ) )
{
if( $class instanceof ADT_PHP_Class )
$file->addClass( $class );
else if( $class instanceof ADT_PHP_Interface )
$file->addInterface( $class );
array_unshift( $lines, $line );
$this->lineNumber --;
$openClass = FALSE;
$level = 1;
continue;
}
if( preg_match( $this->regexMethod, $line, $matches ) )
{
$method = $this->parseMethod( $class, $matches );
$function = $matches[6];
$class->setMethod( $method );
}
else if( $level <= 1 )
{
if( preg_match( $this->regexDocVariable, $line, $matches ) )
{
if( $openClass && $class )
$this->varBlocks[$class->getName()."::".$matches[2]] = $this->parseDocMember( $matches );
else
$this->varBlocks[$matches[2]] = $this->parseDocVariable( $matches );
}
else if( preg_match( $this->regexVariable, $line, $matches ) )
{
$name = $matches[4];
if( $openClass && $class )
{
$key = $class->getName()."::".$name;
$varBlock = isset( $this->varBlocks[$key] ) ? $this->varBlocks[$key] : NULL;
$variable = $this->parseMember( $class, $matches, $varBlock );
$class->setMember( $variable );
}
else
{
remark( "Parser Error: found var after class -> not handled yet" );
/* $key = $name;
$varBlock = isset( $this->varBlocks[$key] ) ? $this->varBlocks[$key] : NULL;
$variable = $this->parseMember( $matches, $varBlock );*/
}
}
}
else if( $level > 1 && $function )
{
$functionBody[$function][] = $line;
}
}
if( preg_match( '@{$@', $line ) )
$level++;
if( $level < 1 && !preg_match( $this->regexClass, $line, $matches ) )
$openClass = FALSE;
}
while( $lines );
$file->setSourceCode( $content );
if( $class )
{
foreach( $class->getMethods() as $methodName => $method )
if( isset( $functionBody[$methodName] ) )
$method->setSourceCode( $functionBody[$methodName] );
if( $class instanceof ADT_PHP_Class )
$file->addClass( $class );
else if( $class instanceof ADT_PHP_Interface )
$file->addInterface( $class );
}
return $file;
} |
Determine whether an array value is empty, taking into account casting.
@param string $key
@param array $value
@return mixed | private function nullIfEmptyArray($key, $value)
{
if ($this->isJsonCastable($key) && ! empty($value)) {
return $this->setJsonCastValue($value);
}
return empty($value) ? null : $value;
} |
Parse an input stream containing a Fortran namelist. | def _readstream(self, nml_file, nml_patch_in=None):
""""""
nml_patch = nml_patch_in if nml_patch_in is not None else Namelist()
tokenizer = Tokenizer()
f90lex = []
for line in nml_file:
toks = tokenizer.parse(line)
while tokenizer.prior_delim:
new_toks = tokenizer.parse(next(nml_file))
# Skip empty lines
if not new_toks:
continue
# The tokenizer always pre-tokenizes the whitespace (leftover
# behaviour from Fortran source parsing) so this must be added
# manually.
if new_toks[0].isspace():
toks[-1] += new_toks.pop(0)
# Append the rest of the string (if present)
if new_toks:
toks[-1] += new_toks[0]
# Attach the rest of the tokens
toks.extend(new_toks[1:])
toks.append('\n')
f90lex.extend(toks)
self.tokens = iter(f90lex)
nmls = Namelist()
# Attempt to get first token; abort on empty file
try:
self._update_tokens(write_token=False)
except StopIteration:
return nmls
# TODO: Replace "while True" with an update_token() iterator
while True:
try:
# Check for classic group terminator
if self.token == 'end':
self._update_tokens()
# Ignore tokens outside of namelist groups
while self.token not in ('&', '$'):
self._update_tokens()
except StopIteration:
break
# Create the next namelist
self._update_tokens()
g_name = self.token
g_vars = Namelist()
v_name = None
# TODO: Edit `Namelist` to support case-insensitive `get` calls
grp_patch = nml_patch.get(g_name.lower(), Namelist())
# Populate the namelist group
while g_name:
if self.token not in ('=', '%', '('):
self._update_tokens()
# Set the next active variable
if self.token in ('=', '(', '%'):
v_name, v_values = self._parse_variable(
g_vars,
patch_nml=grp_patch
)
if v_name in g_vars:
v_prior_values = g_vars[v_name]
v_values = merge_values(v_prior_values, v_values)
g_vars[v_name] = v_values
# Deselect variable
v_name = None
v_values = []
# Finalise namelist group
if self.token in ('/', '&', '$'):
# Append any remaining patched variables
for v_name, v_val in grp_patch.items():
g_vars[v_name] = v_val
v_strs = nmls._var_strings(v_name, v_val)
for v_str in v_strs:
self.pfile.write(
'{0}{1}\n'.format(nml_patch.indent, v_str)
)
# Append the grouplist to the namelist
if g_name in nmls:
g_update = nmls[g_name]
# Update to list of groups
if not isinstance(g_update, list):
g_update = [g_update]
g_update.append(g_vars)
else:
g_update = g_vars
nmls[g_name] = g_update
# Reset state
g_name, g_vars = None, None
try:
self._update_tokens()
except StopIteration:
break
return nmls |
Initializes curl resource with options.
@param string $url
@param string $postString
@param array $headers
@return $this | protected function init($url, $postString, $headers)
{
$this->headers = $headers;
$this->curl = curl_init($url);
if (empty($this->cookieJar)) {
$this->loadCookies();
}
curl_setopt_array($this->curl, $this->makeHttpOptions($postString));
return $this;
} |
Load executable code from a URL or a path | def load_code(name, base_path=None, recurse=False):
""""""
if '/' in name:
return load_location(name, base_path, module=False)
return importer.import_code(name, base_path, recurse=recurse) |
// NextMatcher gets the immediately following sibling of each element in the
// Selection filtered by a matcher. It returns a new Selection object
// containing the matched elements. | func (s *Selection) NextMatcher(m Matcher) *Selection {
return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNext, nil, nil), m)
} |
_Really_ obtain the config for a named class
@param string $class The class to get the config for
@return \Weasel\JsonMarshaller\Config\ClassMarshaller The config, or null if not found | protected function _getConfig($class)
{
$rClass = new \ReflectionClass($class);
// Delegate actually loading the config for the class to the ClassAnnotationDriver
$classDriver = new ClassAnnotationDriver($rClass, $this->annotationReaderFactory, $this->annotationNamespace);
return $classDriver->getConfig();
} |
// SetCacheLength sets the CacheLength field's value. | func (s *RtmpGroupSettings) SetCacheLength(v int64) *RtmpGroupSettings {
s.CacheLength = &v
return s
} |
Initialize grid lines. | private void initGridLines() {
gridLines = new Line[base.getDimension() - 1][linesSlicing.length];
int i2 = 0;
for (int i = 0; i < base.getDimension() - 1; i++) {
if (i2 == index) {
i2++;
}
for (int j = 0; j < gridLines[i].length; j++) {
double[] originBase = new double[base.getDimension()];
double[] endBase = new double[base.getDimension()];
System.arraycopy(origin, 0, originBase, 0, base.getDimension());
System.arraycopy(origin, 0, endBase, 0, base.getDimension());
endBase[i2] = base.getCoordinateSpace()[i2 + 1][i2];
originBase[index] = linesSlicing[j];
endBase[index] = linesSlicing[j];
if (j == 0 || j == gridLines[i].length - 1) {
gridLines[i][j] = new Line(originBase, endBase);
} else {
gridLines[i][j] = new Line(Line.Style.DOT, Color.lightGray, originBase, endBase);
}
}
i2++;
}
} |
Modifies the given N1QL query (as a {@link JsonObject}) to reflect these {@link N1qlParams}.
@param queryJson the N1QL query | public void injectParams(JsonObject queryJson) {
if (this.serverSideTimeout != null) {
queryJson.put("timeout", this.serverSideTimeout);
}
if (this.consistency != null) {
queryJson.put("scan_consistency", this.consistency.n1ql());
}
if (this.scanWait != null
&& (ScanConsistency.REQUEST_PLUS == this.consistency
|| ScanConsistency.STATEMENT_PLUS == this.consistency)) {
queryJson.put("scan_wait", this.scanWait);
}
if (this.clientContextId != null) {
queryJson.put("client_context_id", this.clientContextId);
}
if (this.maxParallelism != null) {
queryJson.put("max_parallelism", this.maxParallelism.toString());
}
if (this.pipelineCap != null) {
queryJson.put("pipeline_cap", this.pipelineCap.toString());
}
if (this.pipelineBatch != null) {
queryJson.put("pipeline_batch", this.pipelineBatch.toString());
}
if (this.scanCap != null) {
queryJson.put("scan_cap", this.scanCap.toString());
}
if (this.disableMetrics) {
queryJson.put("metrics", false);
}
if (this.mutationState != null) {
if (this.consistency != null) {
throw new IllegalArgumentException("`consistency(...)` cannot be used "
+ "together with `consistentWith(...)`");
}
queryJson.put("scan_vectors", mutationState.export());
queryJson.put("scan_consistency", "at_plus");
}
if (!this.credentials.isEmpty()) {
JsonArray creds = JsonArray.create();
for (Map.Entry<String, String> c : credentials.entrySet()) {
if (c.getKey() != null && !c.getKey().isEmpty()) {
creds.add(JsonObject.create()
.put("user", c.getKey())
.put("pass", c.getValue()));
}
}
if (!creds.isEmpty()) {
queryJson.put("creds", creds);
}
}
if (!this.pretty) {
queryJson.put("pretty", false);
}
if (this.readonly) {
queryJson.put("readonly", true);
}
if (this.profile != null) {
queryJson.put("profile", this.profile.toString());
}
if (this.rawParams != null) {
for (Map.Entry<String, Object> entry : rawParams.entrySet()) {
queryJson.put(entry.getKey(), entry.getValue());
}
}
} |
Send stat command to Memcached Server and return response lines.
@param cmd: Command string.
@return: Array of strings. | def _sendStatCmd(self, cmd):
try:
self._conn.write("%s\r\n" % cmd)
regex = re.compile('^(END|ERROR)\r\n', re.MULTILINE)
(idx, mobj, text) = self._conn.expect([regex,], self._timeout) #@UnusedVariable
except:
raise Exception("Communication with %s failed" % self._instanceName)
if mobj is not None:
if mobj.group(1) == 'END':
return text.splitlines()[:-1]
elif mobj.group(1) == 'ERROR':
raise Exception("Protocol error in communication with %s."
% self._instanceName)
else:
raise Exception("Connection with %s timed out." % self._instanceName) |
<p>readContent.</p>
@param in a {@link java.io.Reader} object.
@return a {@link java.lang.String} object.
@throws java.io.IOException if any. | public static String readContent( Reader in ) throws IOException
{
char[] buffer = new char[2048];
StringBuilder sb = new StringBuilder();
int read;
while ((read = in.read( buffer )) != -1)
{
sb.append( buffer, 0, read );
}
return sb.toString();
} |
// AddNode add new node to directory (name must be unique in directory) | func (d *Dir) AddNode(newNode os.FileInfo) error {
for _, node := range d.nodes {
if newNode.Name() == node.Name() {
return fmt.Errorf("node named " + newNode.Name() + " exists")
}
}
d.nodes = append(d.nodes, newNode)
return nil
} |
Load image from path.
@param path Path to image.
@return Image
@throws java.io.IOException
@throws NullPointerException if {@code path} is null. | private Image loadImage(Resource path) throws IOException {
URL url = path.getURL();
if (url == null) {
logger.warn("Unable to locate splash screen in classpath at: " + path);
return null;
}
return Toolkit.getDefaultToolkit().createImage(url);
} |
/*
(non-Javadoc)
@see javax.persistence.EntityManager#createQuery(java.lang.String) | @Override
public Query createQuery(String qlString)
{
try
{
return ivEm.createQuery(qlString);
} finally
{
if (!inJTATransaction())
{
ivEm.clear();
}
}
} |
// NewService creates an instance of a Service. | func NewService() *Service {
s := &Service{
TokenGenerator: rand.NewTokenGenerator(64),
IDGenerator: snowflake.NewIDGenerator(),
time: time.Now,
}
s.initializeSources(context.TODO())
return s
} |
Loads PHPExcel from file
@param string $pFilename
@return PHPExcel
@throws PHPExcel_Reader_Exception | public function load($pFilename)
{
// Read the OLE file
$this->_loadOLE($pFilename);
// Initialisations
$this->_phpExcel = new PHPExcel;
$this->_phpExcel->removeSheetByIndex(0); // remove 1st sheet
if (!$this->_readDataOnly) {
$this->_phpExcel->removeCellStyleXfByIndex(0); // remove the default style
$this->_phpExcel->removeCellXfByIndex(0); // remove the default style
}
// Read the summary information stream (containing meta data)
$this->_readSummaryInformation();
// Read the Additional document summary information stream (containing application-specific meta data)
$this->_readDocumentSummaryInformation();
// total byte size of Excel data (workbook global substream + sheet substreams)
$this->_dataSize = strlen($this->_data);
// initialize
$this->_pos = 0;
$this->_codepage = 'CP1252';
$this->_formats = array();
$this->_objFonts = array();
$this->_palette = array();
$this->_sheets = array();
$this->_externalBooks = array();
$this->_ref = array();
$this->_definedname = array();
$this->_sst = array();
$this->_drawingGroupData = '';
$this->_xfIndex = '';
$this->_mapCellXfIndex = array();
$this->_mapCellStyleXfIndex = array();
// Parse Workbook Global Substream
while ($this->_pos < $this->_dataSize) {
$code = self::_GetInt2d($this->_data, $this->_pos);
switch ($code) {
case self::XLS_Type_BOF: $this->_readBof(); break;
case self::XLS_Type_FILEPASS: $this->_readFilepass(); break;
case self::XLS_Type_CODEPAGE: $this->_readCodepage(); break;
case self::XLS_Type_DATEMODE: $this->_readDateMode(); break;
case self::XLS_Type_FONT: $this->_readFont(); break;
case self::XLS_Type_FORMAT: $this->_readFormat(); break;
case self::XLS_Type_XF: $this->_readXf(); break;
case self::XLS_Type_XFEXT: $this->_readXfExt(); break;
case self::XLS_Type_STYLE: $this->_readStyle(); break;
case self::XLS_Type_PALETTE: $this->_readPalette(); break;
case self::XLS_Type_SHEET: $this->_readSheet(); break;
case self::XLS_Type_EXTERNALBOOK: $this->_readExternalBook(); break;
case self::XLS_Type_EXTERNNAME: $this->_readExternName(); break;
case self::XLS_Type_EXTERNSHEET: $this->_readExternSheet(); break;
case self::XLS_Type_DEFINEDNAME: $this->_readDefinedName(); break;
case self::XLS_Type_MSODRAWINGGROUP: $this->_readMsoDrawingGroup(); break;
case self::XLS_Type_SST: $this->_readSst(); break;
case self::XLS_Type_EOF: $this->_readDefault(); break 2;
default: $this->_readDefault(); break;
}
}
// Resolve indexed colors for font, fill, and border colors
// Cannot be resolved already in XF record, because PALETTE record comes afterwards
if (!$this->_readDataOnly) {
foreach ($this->_objFonts as $objFont) {
if (isset($objFont->colorIndex)) {
$color = self::_readColor($objFont->colorIndex,$this->_palette,$this->_version);
$objFont->getColor()->setRGB($color['rgb']);
}
}
foreach ($this->_phpExcel->getCellXfCollection() as $objStyle) {
// fill start and end color
$fill = $objStyle->getFill();
if (isset($fill->startcolorIndex)) {
$startColor = self::_readColor($fill->startcolorIndex,$this->_palette,$this->_version);
$fill->getStartColor()->setRGB($startColor['rgb']);
}
if (isset($fill->endcolorIndex)) {
$endColor = self::_readColor($fill->endcolorIndex,$this->_palette,$this->_version);
$fill->getEndColor()->setRGB($endColor['rgb']);
}
// border colors
$top = $objStyle->getBorders()->getTop();
$right = $objStyle->getBorders()->getRight();
$bottom = $objStyle->getBorders()->getBottom();
$left = $objStyle->getBorders()->getLeft();
$diagonal = $objStyle->getBorders()->getDiagonal();
if (isset($top->colorIndex)) {
$borderTopColor = self::_readColor($top->colorIndex,$this->_palette,$this->_version);
$top->getColor()->setRGB($borderTopColor['rgb']);
}
if (isset($right->colorIndex)) {
$borderRightColor = self::_readColor($right->colorIndex,$this->_palette,$this->_version);
$right->getColor()->setRGB($borderRightColor['rgb']);
}
if (isset($bottom->colorIndex)) {
$borderBottomColor = self::_readColor($bottom->colorIndex,$this->_palette,$this->_version);
$bottom->getColor()->setRGB($borderBottomColor['rgb']);
}
if (isset($left->colorIndex)) {
$borderLeftColor = self::_readColor($left->colorIndex,$this->_palette,$this->_version);
$left->getColor()->setRGB($borderLeftColor['rgb']);
}
if (isset($diagonal->colorIndex)) {
$borderDiagonalColor = self::_readColor($diagonal->colorIndex,$this->_palette,$this->_version);
$diagonal->getColor()->setRGB($borderDiagonalColor['rgb']);
}
}
}
// treat MSODRAWINGGROUP records, workbook-level Escher
if (!$this->_readDataOnly && $this->_drawingGroupData) {
$escherWorkbook = new PHPExcel_Shared_Escher();
$reader = new PHPExcel_Reader_Excel5_Escher($escherWorkbook);
$escherWorkbook = $reader->load($this->_drawingGroupData);
// debug Escher stream
//$debug = new Debug_Escher(new PHPExcel_Shared_Escher());
//$debug->load($this->_drawingGroupData);
}
// Parse the individual sheets
foreach ($this->_sheets as $sheet) {
if ($sheet['sheetType'] != 0x00) {
// 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module
continue;
}
// check if sheet should be skipped
if (isset($this->_loadSheetsOnly) && !in_array($sheet['name'], $this->_loadSheetsOnly)) {
continue;
}
// add sheet to PHPExcel object
$this->_phpSheet = $this->_phpExcel->createSheet();
// Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula
// cells... during the load, all formulae should be correct, and we're simply bringing the worksheet
// name in line with the formula, not the reverse
$this->_phpSheet->setTitle($sheet['name'],false);
$this->_phpSheet->setSheetState($sheet['sheetState']);
$this->_pos = $sheet['offset'];
// Initialize isFitToPages. May change after reading SHEETPR record.
$this->_isFitToPages = false;
// Initialize drawingData
$this->_drawingData = '';
// Initialize objs
$this->_objs = array();
// Initialize shared formula parts
$this->_sharedFormulaParts = array();
// Initialize shared formulas
$this->_sharedFormulas = array();
// Initialize text objs
$this->_textObjects = array();
// Initialize cell annotations
$this->_cellNotes = array();
$this->textObjRef = -1;
while ($this->_pos <= $this->_dataSize - 4) {
$code = self::_GetInt2d($this->_data, $this->_pos);
switch ($code) {
case self::XLS_Type_BOF: $this->_readBof(); break;
case self::XLS_Type_PRINTGRIDLINES: $this->_readPrintGridlines(); break;
case self::XLS_Type_DEFAULTROWHEIGHT: $this->_readDefaultRowHeight(); break;
case self::XLS_Type_SHEETPR: $this->_readSheetPr(); break;
case self::XLS_Type_HORIZONTALPAGEBREAKS: $this->_readHorizontalPageBreaks(); break;
case self::XLS_Type_VERTICALPAGEBREAKS: $this->_readVerticalPageBreaks(); break;
case self::XLS_Type_HEADER: $this->_readHeader(); break;
case self::XLS_Type_FOOTER: $this->_readFooter(); break;
case self::XLS_Type_HCENTER: $this->_readHcenter(); break;
case self::XLS_Type_VCENTER: $this->_readVcenter(); break;
case self::XLS_Type_LEFTMARGIN: $this->_readLeftMargin(); break;
case self::XLS_Type_RIGHTMARGIN: $this->_readRightMargin(); break;
case self::XLS_Type_TOPMARGIN: $this->_readTopMargin(); break;
case self::XLS_Type_BOTTOMMARGIN: $this->_readBottomMargin(); break;
case self::XLS_Type_PAGESETUP: $this->_readPageSetup(); break;
case self::XLS_Type_PROTECT: $this->_readProtect(); break;
case self::XLS_Type_SCENPROTECT: $this->_readScenProtect(); break;
case self::XLS_Type_OBJECTPROTECT: $this->_readObjectProtect(); break;
case self::XLS_Type_PASSWORD: $this->_readPassword(); break;
case self::XLS_Type_DEFCOLWIDTH: $this->_readDefColWidth(); break;
case self::XLS_Type_COLINFO: $this->_readColInfo(); break;
case self::XLS_Type_DIMENSION: $this->_readDefault(); break;
case self::XLS_Type_ROW: $this->_readRow(); break;
case self::XLS_Type_DBCELL: $this->_readDefault(); break;
case self::XLS_Type_RK: $this->_readRk(); break;
case self::XLS_Type_LABELSST: $this->_readLabelSst(); break;
case self::XLS_Type_MULRK: $this->_readMulRk(); break;
case self::XLS_Type_NUMBER: $this->_readNumber(); break;
case self::XLS_Type_FORMULA: $this->_readFormula(); break;
case self::XLS_Type_SHAREDFMLA: $this->_readSharedFmla(); break;
case self::XLS_Type_BOOLERR: $this->_readBoolErr(); break;
case self::XLS_Type_MULBLANK: $this->_readMulBlank(); break;
case self::XLS_Type_LABEL: $this->_readLabel(); break;
case self::XLS_Type_BLANK: $this->_readBlank(); break;
case self::XLS_Type_MSODRAWING: $this->_readMsoDrawing(); break;
case self::XLS_Type_OBJ: $this->_readObj(); break;
case self::XLS_Type_WINDOW2: $this->_readWindow2(); break;
case self::XLS_Type_PAGELAYOUTVIEW: $this->_readPageLayoutView(); break;
case self::XLS_Type_SCL: $this->_readScl(); break;
case self::XLS_Type_PANE: $this->_readPane(); break;
case self::XLS_Type_SELECTION: $this->_readSelection(); break;
case self::XLS_Type_MERGEDCELLS: $this->_readMergedCells(); break;
case self::XLS_Type_HYPERLINK: $this->_readHyperLink(); break;
case self::XLS_Type_DATAVALIDATIONS: $this->_readDataValidations(); break;
case self::XLS_Type_DATAVALIDATION: $this->_readDataValidation(); break;
case self::XLS_Type_SHEETLAYOUT: $this->_readSheetLayout(); break;
case self::XLS_Type_SHEETPROTECTION: $this->_readSheetProtection(); break;
case self::XLS_Type_RANGEPROTECTION: $this->_readRangeProtection(); break;
case self::XLS_Type_NOTE: $this->_readNote(); break;
//case self::XLS_Type_IMDATA: $this->_readImData(); break;
case self::XLS_Type_TXO: $this->_readTextObject(); break;
case self::XLS_Type_CONTINUE: $this->_readContinue(); break;
case self::XLS_Type_EOF: $this->_readDefault(); break 2;
default: $this->_readDefault(); break;
}
}
// treat MSODRAWING records, sheet-level Escher
if (!$this->_readDataOnly && $this->_drawingData) {
$escherWorksheet = new PHPExcel_Shared_Escher();
$reader = new PHPExcel_Reader_Excel5_Escher($escherWorksheet);
$escherWorksheet = $reader->load($this->_drawingData);
// debug Escher stream
//$debug = new Debug_Escher(new PHPExcel_Shared_Escher());
//$debug->load($this->_drawingData);
// get all spContainers in one long array, so they can be mapped to OBJ records
$allSpContainers = $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers();
}
// treat OBJ records
foreach ($this->_objs as $n => $obj) {
// echo '<hr /><b>Object</b> reference is ',$n,'<br />';
// var_dump($obj);
// echo '<br />';
// the first shape container never has a corresponding OBJ record, hence $n + 1
if (isset($allSpContainers[$n + 1]) && is_object($allSpContainers[$n + 1])) {
$spContainer = $allSpContainers[$n + 1];
// we skip all spContainers that are a part of a group shape since we cannot yet handle those
if ($spContainer->getNestingLevel() > 1) {
continue;
}
// calculate the width and height of the shape
list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($spContainer->getStartCoordinates());
list($endColumn, $endRow) = PHPExcel_Cell::coordinateFromString($spContainer->getEndCoordinates());
$startOffsetX = $spContainer->getStartOffsetX();
$startOffsetY = $spContainer->getStartOffsetY();
$endOffsetX = $spContainer->getEndOffsetX();
$endOffsetY = $spContainer->getEndOffsetY();
$width = PHPExcel_Shared_Excel5::getDistanceX($this->_phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX);
$height = PHPExcel_Shared_Excel5::getDistanceY($this->_phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY);
// calculate offsetX and offsetY of the shape
$offsetX = $startOffsetX * PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, $startColumn) / 1024;
$offsetY = $startOffsetY * PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $startRow) / 256;
switch ($obj['otObjType']) {
case 0x19:
// Note
// echo 'Cell Annotation Object<br />';
// echo 'Object ID is ',$obj['idObjID'],'<br />';
//
if (isset($this->_cellNotes[$obj['idObjID']])) {
$cellNote = $this->_cellNotes[$obj['idObjID']];
if (isset($this->_textObjects[$obj['idObjID']])) {
$textObject = $this->_textObjects[$obj['idObjID']];
$this->_cellNotes[$obj['idObjID']]['objTextData'] = $textObject;
}
}
break;
case 0x08:
// echo 'Picture Object<br />';
// picture
// get index to BSE entry (1-based)
$BSEindex = $spContainer->getOPT(0x0104);
$BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection();
$BSE = $BSECollection[$BSEindex - 1];
$blipType = $BSE->getBlipType();
// need check because some blip types are not supported by Escher reader such as EMF
if ($blip = $BSE->getBlip()) {
$ih = imagecreatefromstring($blip->getData());
$drawing = new PHPExcel_Worksheet_MemoryDrawing();
$drawing->setImageResource($ih);
// width, height, offsetX, offsetY
$drawing->setResizeProportional(false);
$drawing->setWidth($width);
$drawing->setHeight($height);
$drawing->setOffsetX($offsetX);
$drawing->setOffsetY($offsetY);
switch ($blipType) {
case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG:
$drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG);
$drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG);
break;
case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG:
$drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG);
$drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG);
break;
}
$drawing->setWorksheet($this->_phpSheet);
$drawing->setCoordinates($spContainer->getStartCoordinates());
}
break;
default:
// other object type
break;
}
}
}
// treat SHAREDFMLA records
if ($this->_version == self::XLS_BIFF8) {
foreach ($this->_sharedFormulaParts as $cell => $baseCell) {
list($column, $row) = PHPExcel_Cell::coordinateFromString($cell);
if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle()) ) {
$formula = $this->_getFormulaFromStructure($this->_sharedFormulas[$baseCell], $cell);
$this->_phpSheet->getCell($cell)->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA);
}
}
}
if (!empty($this->_cellNotes)) {
foreach($this->_cellNotes as $note => $noteDetails) {
if (!isset($noteDetails['objTextData'])) {
if (isset($this->_textObjects[$note])) {
$textObject = $this->_textObjects[$note];
$noteDetails['objTextData'] = $textObject;
} else {
$noteDetails['objTextData']['text'] = '';
}
}
// echo '<b>Cell annotation ',$note,'</b><br />';
// var_dump($noteDetails);
// echo '<br />';
$cellAddress = str_replace('$','',$noteDetails['cellRef']);
$this->_phpSheet->getComment( $cellAddress )
->setAuthor( $noteDetails['author'] )
->setText($this->_parseRichText($noteDetails['objTextData']['text']) );
}
}
}
// add the named ranges (defined names)
foreach ($this->_definedname as $definedName) {
if ($definedName['isBuiltInName']) {
switch ($definedName['name']) {
case pack('C', 0x06):
// print area
// in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2
$ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
$extractedRanges = array();
foreach ($ranges as $range) {
// $range should look like one of these
// Foo!$C$7:$J$66
// Bar!$A$1:$IV$2
$explodes = explode('!', $range); // FIXME: what if sheetname contains exclamation mark?
$sheetName = trim($explodes[0], "'");
if (count($explodes) == 2) {
if (strpos($explodes[1], ':') === FALSE) {
$explodes[1] = $explodes[1] . ':' . $explodes[1];
}
$extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66
}
}
if ($docSheet = $this->_phpExcel->getSheetByName($sheetName)) {
$docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2
}
break;
case pack('C', 0x07):
// print titles (repeating rows)
// Assuming BIFF8, there are 3 cases
// 1. repeating rows
// formula looks like this: Sheet!$A$1:$IV$2
// rows 1-2 repeat
// 2. repeating columns
// formula looks like this: Sheet!$A$1:$B$65536
// columns A-B repeat
// 3. both repeating rows and repeating columns
// formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2
$ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma?
foreach ($ranges as $range) {
// $range should look like this one of these
// Sheet!$A$1:$B$65536
// Sheet!$A$1:$IV$2
$explodes = explode('!', $range);
if (count($explodes) == 2) {
if ($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) {
$extractedRange = $explodes[1];
$extractedRange = str_replace('$', '', $extractedRange);
$coordinateStrings = explode(':', $extractedRange);
if (count($coordinateStrings) == 2) {
list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[0]);
list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[1]);
if ($firstColumn == 'A' and $lastColumn == 'IV') {
// then we have repeating rows
$docSheet->getPageSetup()->setRowsToRepeatAtTop(array($firstRow, $lastRow));
} elseif ($firstRow == 1 and $lastRow == 65536) {
// then we have repeating columns
$docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($firstColumn, $lastColumn));
}
}
}
}
}
break;
}
} else {
// Extract range
$explodes = explode('!', $definedName['formula']);
if (count($explodes) == 2) {
if (($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) ||
($docSheet = $this->_phpExcel->getSheetByName(trim($explodes[0],"'")))) {
$extractedRange = $explodes[1];
$extractedRange = str_replace('$', '', $extractedRange);
$localOnly = ($definedName['scope'] == 0) ? false : true;
$scope = ($definedName['scope'] == 0) ?
null : $this->_phpExcel->getSheetByName($this->_sheets[$definedName['scope'] - 1]['name']);
$this->_phpExcel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $docSheet, $extractedRange, $localOnly, $scope) );
}
} else {
// Named Value
// TODO Provide support for named values
}
}
}
return $this->_phpExcel;
} |
Commit an http request.
@param string $method
@param string $url
@param array $params
@param array $options
@return \Shoperti\PayMe\Contracts\ResponseInterface | public function commit($method, $url, $params = [], $options = [])
{
if (empty($this->connectionToken)) {
$this->loginApplication();
}
$request = [
'exceptions' => false,
'timeout' => '80',
'connect_timeout' => '30',
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$this->connectionToken,
],
];
if (!empty($params)) {
$request[$method === 'get' ? 'query' : 'json'] = $params;
}
$raw = $this->getHttpClient()->{$method}($url, $request);
$statusCode = $raw->getStatusCode();
$response = $statusCode == 200
? $this->parseResponse($raw->getBody())
: $this->responseError($raw->getBody(), $statusCode);
return $this->respond($response);
} |
Compares the two Git trees (with caching). | private List<DiffEntry> blockingCompareTrees(RevTree treeA, RevTree treeB) {
if (cache == null) {
return blockingCompareTreesUncached(treeA, treeB, TreeFilter.ALL);
}
final CacheableCompareTreesCall key = new CacheableCompareTreesCall(this, treeA, treeB);
CompletableFuture<List<DiffEntry>> existingFuture = cache.getIfPresent(key);
if (existingFuture != null) {
final List<DiffEntry> existingDiffEntries = existingFuture.getNow(null);
if (existingDiffEntries != null) {
// Cached already.
return existingDiffEntries;
}
}
// Not cached yet. Acquire a lock so that we do not compare the same tree pairs simultaneously.
final List<DiffEntry> newDiffEntries;
final Lock lock = key.coarseGrainedLock();
lock.lock();
try {
existingFuture = cache.getIfPresent(key);
if (existingFuture != null) {
final List<DiffEntry> existingDiffEntries = existingFuture.getNow(null);
if (existingDiffEntries != null) {
// Other thread already put the entries to the cache before we acquire the lock.
return existingDiffEntries;
}
}
newDiffEntries = blockingCompareTreesUncached(treeA, treeB, TreeFilter.ALL);
cache.put(key, newDiffEntries);
} finally {
lock.unlock();
}
logger.debug("Cache miss: {}", key);
return newDiffEntries;
} |
Rewrite references to `local_path` with `remote_path` in job inputs. | def rewrite_paths(self, local_path, remote_path):
self.__rewrite_command_line(local_path, remote_path)
self.__rewrite_config_files(local_path, remote_path) |
Returns the initial of given name.
For standard names: "First [Midddles] Last", returns capital "FL";
For others, returns substr(0, 2).
@param {string} name -
@return {string} - initial | function getNameInitial(name) {
var namePart = name.split(' ');
if (namePart.length >= 2) {
return (namePart[0].charAt(0) + namePart[namePart.length - 1].charAt(0)).toUpperCase();
} else {
return name.substr(0, 2);
}
} |
Sets the variables to the selected stage using cap rbenv set | def set_vars_to_stage(stage, variables)
# convert to array using VAR=value
vars_array = variables.map{|k,v| "#{k}=#{v}" }
Capistrano::Application.invoke(stage)
Capistrano::Application.invoke("rbenv:vars:set", *vars_array)
end |
Create a 500 response.
@param \Exception $exception The exception to log.
@return JsonResponse | private function createInternalServerError(\Exception $exception)
{
$message = sprintf(
'%s: %s (uncaught exception) at %s line %s',
get_class($exception),
$exception->getMessage(),
$exception->getFile(),
$exception->getLine()
);
$this->logger->error($message, array('exception' => $exception));
$response = [
'status' => 'ERROR',
'message' => JsonResponse::$statusTexts[JsonResponse::HTTP_INTERNAL_SERVER_ERROR]
];
if ($this->debug) {
$response['exception'] = $this->formatException($exception);
}
return new JsonResponse($response, JsonResponse::HTTP_INTERNAL_SERVER_ERROR);
} |
// SetAmznClientToken sets the AmznClientToken field's value. | func (s *CreateConnectorDefinitionVersionInput) SetAmznClientToken(v string) *CreateConnectorDefinitionVersionInput {
s.AmznClientToken = &v
return s
} |
// SetApplicationVersionId sets the ApplicationVersionId field's value. | func (s *AddApplicationInputProcessingConfigurationOutput) SetApplicationVersionId(v int64) *AddApplicationInputProcessingConfigurationOutput {
s.ApplicationVersionId = &v
return s
} |
Writes out headers for $this->part and follows them with an empty line.
@param StreamInterface $stream | public function writePartHeadersTo(StreamInterface $stream)
{
foreach ($this->getPartHeadersIterator() as $header) {
$stream->write("${header[0]}: ${header[1]}\r\n");
}
$stream->write("\r\n");
} |
Add all additional defined and undefined symbols. | def __add_symbols(self, cmd):
if self.__config.define_symbols:
symbols = self.__config.define_symbols
cmd.append(''.join(
[' -D"%s"' % def_symbol for def_symbol in symbols]))
if self.__config.undefine_symbols:
un_symbols = self.__config.undefine_symbols
cmd.append(''.join(
[' -U"%s"' % undef_symbol for undef_symbol in un_symbols]))
return cmd |
// CanCastle returns true if the given color and side combination
// can castle, otherwise returns false. | func (cr CastleRights) CanCastle(c Color, side Side) bool {
char := "k"
if side == QueenSide {
char = "q"
}
if c == White {
char = strings.ToUpper(char)
}
return strings.Contains(string(cr), char)
} |
Finds all nodes that are after the ``min_line_number`` | def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]:
return [node for node in nodes if node.lineno > min_line_number] |
Checks for valid uploaded file.
@param array $package
@return bool | protected function isUploadedFile($package)
{
if (isset($package['name'], $package['tmp_name'], $package['type'], $package['size'])) {
if (in_array($package['type'], ['application/zip', 'application/x-zip-compressed'])) {
return true;
}
}
return false;
} |
Compare two attributes
@param control
@param test
@param listener
@throws DifferenceFoundException | protected void compareRecognizedXMLSchemaInstanceAttribute(Attr control,
Attr test,
DifferenceListener listener)
throws DifferenceFoundException {
Attr nonNullNode = control != null ? control : test;
Difference d =
XMLConstants.W3C_XML_SCHEMA_INSTANCE_SCHEMA_LOCATION_ATTR
.equals(nonNullNode.getLocalName())
? SCHEMA_LOCATION : NO_NAMESPACE_SCHEMA_LOCATION;
if (control != null) {
controlTracker.visited(control);
}
if (test != null) {
testTracker.visited(test);
}
compare(control != null ? control.getValue() : ATTRIBUTE_ABSENT,
test != null ? test.getValue() : ATTRIBUTE_ABSENT,
control, test, listener, d);
} |
Export this data so it can be used as the context for a mustache template.
@param \renderer_base $output
@return stdClass | public function export_for_template(renderer_base $output) {
global $USER, $OUTPUT;
$data = new \stdClass();
if (!isset($this->config->display_picture) || $this->config->display_picture == 1) {
$data->userpicture = $OUTPUT->user_picture($USER, array('class' => 'userpicture'));
}
$data->userfullname = fullname($USER);
if (!isset($this->config->display_country) || $this->config->display_country == 1) {
$countries = get_string_manager()->get_list_of_countries(true);
if (isset($countries[$USER->country])) {
$data->usercountry = $countries[$USER->country];
}
}
if (!isset($this->config->display_city) || $this->config->display_city == 1) {
$data->usercity = $USER->city;
}
if (!isset($this->config->display_email) || $this->config->display_email == 1) {
$data->useremail = obfuscate_mailto($USER->email, '');
}
if (!empty($this->config->display_icq) && !empty($USER->icq)) {
$data->usericq = s($USER->icq);
}
if (!empty($this->config->display_skype) && !empty($USER->skype)) {
$data->userskype = s($USER->skype);
}
if (!empty($this->config->display_yahoo) && !empty($USER->yahoo)) {
$data->useryahoo = s($USER->yahoo);
}
if (!empty($this->config->display_aim) && !empty($USER->aim)) {
$data->useraim = s($USER->aim);
}
if (!empty($this->config->display_msn) && !empty($USER->msn)) {
$data->usermsn = s($USER->msn);
}
if (!empty($this->config->display_phone1) && !empty($USER->phone1)) {
$data->userphone1 = s($USER->phone1);
}
if (!empty($this->config->display_phone2) && !empty($USER->phone2)) {
$data->userphone2 = s($USER->phone2);
}
if (!empty($this->config->display_institution) && !empty($USER->institution)) {
$data->userinstitution = format_string($USER->institution);
}
if (!empty($this->config->display_address) && !empty($USER->address)) {
$data->useraddress = format_string($USER->address);
}
if (!empty($this->config->display_firstaccess) && !empty($USER->firstaccess)) {
$data->userfirstaccess = userdate($USER->firstaccess);
}
if (!empty($this->config->display_lastaccess) && !empty($USER->lastaccess)) {
$data->userlastaccess = userdate($USER->lastaccess);
}
if (!empty($this->config->display_currentlogin) && !empty($USER->currentlogin)) {
$data->usercurrentlogin = userdate($USER->currentlogin);
}
if (!empty($this->config->display_lastip) && !empty($USER->lastip)) {
$data->userlastip = $USER->lastip;
}
return $data;
} |
// AddMultiple adds a list of cookies. | func AddMultiple(cookies []*http.Cookie) p.Plugin {
return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) {
for _, cookie := range cookies {
ctx.Request.AddCookie(cookie)
}
h.Next(ctx)
})
} |
Gets the next match_temp_var. | def get_temp_var(self):
""""""
tempvar = match_temp_var + "_" + str(self.var_index)
self.var_index += 1
return tempvar |
Returns true if the associate PushMode was selected in the configuration
@param Configuration $configuration
@return bool | public function isMode( Configuration $configuration ) {
if( $this->inServiceChecker->isInService($configuration) )
return false;
if( $this->replaceUpgradeChecker->isReplaceUpgrade($configuration) )
return false;
return true;
} |
Start healthcheck (status monitoring) for a peer
It also whitelists the address to answer invites and listen for messages | def start_health_check(self, node_address):
if self._stop_event.ready():
return
with self._health_lock:
if self._address_mgr.is_address_known(node_address):
return # already healthchecked
node_address_hex = to_normalized_address(node_address)
self.log.debug('Healthcheck', peer_address=node_address_hex)
candidates = [
self._get_user(user)
for user in self._client.search_user_directory(node_address_hex)
]
user_ids = {
user.user_id
for user in candidates
if validate_userid_signature(user) == node_address
}
self.whitelist(node_address)
self._address_mgr.add_userids_for_address(node_address, user_ids)
# Ensure network state is updated in case we already know about the user presences
# representing the target node
self._address_mgr.refresh_address_presence(node_address) |
Custom error handler that will throw an exception on any errors | public function handleError()
{
// get error info
list ($errno, $message, $file, $line) = func_get_args();
// construct error message
$msg = "ERROR ($errno): $message";
if ($line !== null) {
$file = "$file:$line";
}
if ($file !== null) {
$msg .= " [$file]";
}
static::$lastErrno = $errno;
// throw the exception
throw new RuntimeException($msg, $errno);
} |
// details outputs details for a single transaction. | func (w *walletAPIHandler) details(ctx context.Context, c Call, wr io.Writer) error {
var opts txIDOptions
if err := unmarshalOptions(c, &opts); err != nil {
return w.encodeErr(c, err, wr)
}
detail, err := w.cli.PaymentDetailCLILocal(ctx, opts.TxID)
if err != nil {
return w.encodeErr(c, err, wr)
}
return w.encodeResult(c, detail, wr)
} |
Set dotted attr (like "a.b.c") on obj to val. | def setattrdeep(obj, attr, val):
''
attrs = attr.split('.')
for a in attrs[:-1]:
obj = getattr(obj, a)
setattr(obj, attrs[-1], val) |
--------------------------------------------------------------------------- | function replaceInFile (filename, regex, replacement) {
let contents = fs.readFileSync (filename, 'utf8')
const parts = contents.split (regex)
const newContents = parts[0] + replacement + parts[1]
fs.truncateSync (filename)
fs.writeFileSync (filename, newContents)
} |
Check so Locale settings (country, currency, language) are set.
@throws KlarnaException
@return void | private function _checkLocale()
{
if (!is_int($this->_country)
|| !is_int($this->_language)
|| !is_int($this->_currency)
) {
throw new Klarna_InvalidLocaleException;
}
} |
@param \PHP_CodeSniffer\Files\File $phpCsFile
@param int $stackPointer
@return bool | protected function hasMethodAnnotation(File $phpCsFile, int $stackPointer): bool
{
$position = $phpCsFile->findPrevious(T_DOC_COMMENT_CLOSE_TAG, $stackPointer);
$tokens = $phpCsFile->getTokens();
while ($position !== false) {
$position = $phpCsFile->findPrevious(T_DOC_COMMENT_TAG, $position);
if ($position !== false) {
if (strpos($tokens[$position + 2]['content'], $this->getMethodName() . '()') !== false) {
return true;
}
$position--;
}
}
return false;
} |
Remove a parser from the render queue.
@param \Ems\Contracts\Core\TextParser $parser
@return self | public function remove(TextParser $parser)
{
$parserHash = $this->objectHash($parser);
$this->parsers = array_filter($this->parsers, function ($known) use ($parserHash) {
return $this->objectHash($known) != $parserHash;
});
if (isset($this->parserIds[$parserHash])) {
unset($this->parserIds[$parserHash]);
}
return $this;
} |
// GetZone returns the Zone containing the current availability zone and locality region that the program is running in.
// If the node is not running with availability zones, then it will fall back to fault domain. | func (az *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) {
if az.UseInstanceMetadata {
metadata, err := az.metadata.GetMetadata()
if err != nil {
return cloudprovider.Zone{}, err
}
if metadata.Compute == nil {
return cloudprovider.Zone{}, fmt.Errorf("failure of getting compute information from instance metadata")
}
zone := ""
if metadata.Compute.Zone != "" {
zoneID, err := strconv.Atoi(metadata.Compute.Zone)
if err != nil {
return cloudprovider.Zone{}, fmt.Errorf("failed to parse zone ID %q: %v", metadata.Compute.Zone, err)
}
zone = az.makeZone(zoneID)
} else {
klog.V(3).Infof("Availability zone is not enabled for the node, falling back to fault domain")
zone = metadata.Compute.FaultDomain
}
return cloudprovider.Zone{
FailureDomain: zone,
Region: az.Location,
}, nil
}
// if UseInstanceMetadata is false, get Zone name by calling ARM
hostname, err := os.Hostname()
if err != nil {
return cloudprovider.Zone{}, fmt.Errorf("failure getting hostname from kernel")
}
return az.vmSet.GetZoneByNodeName(strings.ToLower(hostname))
} |
Decode sensor data.
Returns:
dict: Sensor values | def decode_data(self, encoded):
'''
'''
try:
identifier = None
data_format = 2
if len(encoded) > 8:
data_format = 4
identifier = encoded[8:]
encoded = encoded[:8]
decoded = bytearray(base64.b64decode(encoded, '-_'))
return {
'data_format': data_format,
'temperature': self._get_temperature(decoded),
'humidity': self._get_humidity(decoded),
'pressure': self._get_pressure(decoded),
'identifier': identifier
}
except:
log.exception('Encoded value: %s not valid', encoded)
return None |
<p>
A list of the configuration options and their values in this configuration set.
</p>
@return A list of the configuration options and their values in this configuration set. | public java.util.List<ConfigurationOptionSetting> getOptionSettings() {
if (optionSettings == null) {
optionSettings = new com.amazonaws.internal.SdkInternalList<ConfigurationOptionSetting>();
}
return optionSettings;
} |
// SetDeadline implements the net.PacketConn SetDeadline method. | func (c *Conn) SetDeadline(t time.Time) error {
return c.p.SetDeadline(t)
} |
// Reset cleans up the request queue | func (s *BulkService) Reset() {
s.requests = make([]BulkableRequest, 0)
s.sizeInBytes = 0
s.sizeInBytesCursor = 0
} |
Registers a named object in the store. | function(obj, type, name, nameIsUnique, oldName) {
var nameMap, objList
this._store[type] = nameMap = this._store[type] || {}
nameMap[name] = objList = nameMap[name] || []
// Adding new mapping
if (objList.indexOf(obj) === -1) {
if (nameIsUnique && objList.length > 0)
throw new Error('there is already a ' + type + ' with name "' + name + '"')
objList.push(obj)
}
// Removing old mapping
if (oldName) {
objList = nameMap[oldName]
objList.splice(objList.indexOf(obj), 1)
}
exports.emitter.emit('namedObjects:registered:' + type, obj)
} |
Function creating an iterator of edges for the given type.
@param {Graph} graph - Target Graph instance.
@param {string} type - Type of edges to retrieve.
@return {Iterator} | function createEdgeIterator(graph, type) {
if (graph.size === 0)
return Iterator.empty();
let iterator;
if (type === 'mixed') {
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
});
}
iterator = graph._edges.values();
return new Iterator(function next() {
const step = iterator.next();
if (step.done)
return step;
const data = step.value;
if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) {
const value = [
data.key,
data.attributes,
data.source.key,
data.target.key,
data.source.attributes,
data.target.attributes
];
return {value, done: false};
}
return next();
});
} |
// SetFIFOCompactionOptions sets the options for FIFO compaction style.
// Default: nil | func (opts *Options) SetFIFOCompactionOptions(value *FIFOCompactionOptions) {
C.rocksdb_options_set_fifo_compaction_options(opts.c, value.c)
} |
Method to create the blank transaction nodes as a dict. If bic is True,
the BIC node will also be created. | def _create_TX_node(self, bic=True):
ED = dict()
ED['DrctDbtTxInfNode'] = ET.Element("DrctDbtTxInf")
ED['PmtIdNode'] = ET.Element("PmtId")
ED['EndToEndIdNode'] = ET.Element("EndToEndId")
ED['InstdAmtNode'] = ET.Element("InstdAmt")
ED['DrctDbtTxNode'] = ET.Element("DrctDbtTx")
ED['MndtRltdInfNode'] = ET.Element("MndtRltdInf")
ED['MndtIdNode'] = ET.Element("MndtId")
ED['DtOfSgntrNode'] = ET.Element("DtOfSgntr")
ED['DbtrAgtNode'] = ET.Element("DbtrAgt")
ED['FinInstnId_DbtrAgt_Node'] = ET.Element("FinInstnId")
if bic:
ED['BIC_DbtrAgt_Node'] = ET.Element("BIC")
ED['DbtrNode'] = ET.Element("Dbtr")
ED['Nm_Dbtr_Node'] = ET.Element("Nm")
ED['DbtrAcctNode'] = ET.Element("DbtrAcct")
ED['Id_DbtrAcct_Node'] = ET.Element("Id")
ED['IBAN_DbtrAcct_Node'] = ET.Element("IBAN")
ED['RmtInfNode'] = ET.Element("RmtInf")
ED['UstrdNode'] = ET.Element("Ustrd")
return ED |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case BpsimPackage.NUMERIC_PARAMETER_TYPE__CURRENCY_UNIT:
return getCurrencyUnit();
case BpsimPackage.NUMERIC_PARAMETER_TYPE__TIME_UNIT:
return getTimeUnit();
case BpsimPackage.NUMERIC_PARAMETER_TYPE__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
} |
@param GitUserInterface $user
@param FilePath $relativeFilePath
@param string $commitMessage
@throws \Exception | public function removeFile(GitUserInterface $user, FilePath $relativeFilePath, $commitMessage)
{
$this->assertCommitMessageExists($commitMessage);
$this->createLock($user, $relativeFilePath);
$this->gitService->removeAndCommit($user, $relativeFilePath, $commitMessage);
$this->removeLock($user, $relativeFilePath);
} |