comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Determines whether a module exists with the given modpath. | def find_module(modpath):
""""""
module_path = modpath.replace('.', '/') + '.py'
init_path = modpath.replace('.', '/') + '/__init__.py'
for root_path in sys.path:
path = os.path.join(root_path, module_path)
if os.path.isfile(path):
return path
path = os.path.join(root_path, init_path)
if os.path.isfile(path):
return path |
Download file(s)
@param \gplcart\core\Controller $controller | public function submit($controller)
{
set_time_limit(0);
// Download method calls exit() so clean session here
$this->session->delete('file_manager_selected');
$destination = $this->file->getTempFile();
$files = $controller->getSubmitted('files');
/* @var $file \SplFileInfo */
$file = reset($files);
$path = $file->getRealPath();
$filename = $file->getBasename();
if ($file->isFile()) {
$result = $this->zip->file($path, $destination);
} else if ($file->isDir()) {
$result = $this->zip->directory($path, $destination, $filename);
}
if (!empty($result)) {
$controller->download($destination, "$filename.zip");
}
} |
Get the parameters of bounding box of the UI element.
Returns:
:obj:`list` <:obj:`float`>: 4-list (top, right, bottom, left) coordinates related to the edge of screen in
NormalizedCoordinate system | def get_bounds(self):
size = self.get_size()
top_left = self.get_position([0, 0])
# t, r, b, l
bounds = [top_left[1], top_left[0] + size[0], top_left[1] + size[1], top_left[0]]
return bounds |
FIXME: this and the --include-all doesn't seem to be very happy, redefine one one queries different types of pages | private Predicate<HelpPage> query(final Predicate<HelpPage> predicate) {
Predicate<HelpPage> query = predicate;
if (includeAll == null || !includeAll) {
if (includeAliases != null && !includeAliases) {
query = query.and(TypePredicate.of(AliasHelpPage.class).negate());
}
if (includeMeta != null && !includeMeta) {
query = query.and(TypePredicate.of(MetaHelpPage.class).negate());
}
if (includeCommands != null && !includeCommands) {
query = query.and(TypePredicate.of(CommandHelpPage.class).negate());
}
if (includeGroups != null && !includeGroups) {
query = query.and(TypePredicate.of(GroupHelpPage.class).negate());
}
}
return query;
} |
As per {@link #scoreExamples(DataSet, boolean)} - the outputs (example scores) for all DataSets in the iterator are concatenated | public INDArray scoreExamples(DataSetIterator iter, boolean addRegularizationTerms) {
List<INDArray> out = new ArrayList<>();
while (iter.hasNext()) {
out.add(scoreExamples(iter.next(), addRegularizationTerms));
}
return Nd4j.toFlattened('f', out);
} |
Gets local configuration. For explanation when it could die, see {@link #get()} | @Restricted(NoExternalUse.class)
public static @Nonnull JenkinsLocationConfiguration getOrDie(){
JenkinsLocationConfiguration config = JenkinsLocationConfiguration.get();
if (config == null) {
throw new IllegalStateException("JenkinsLocationConfiguration instance is missing. Probably the Jenkins instance is not fully loaded at this time.");
}
return config;
} |
// New returns a generated name based on the provided id, and its matching label.
// Names are title cased with spaces between words.
// Labels are lowercased with hyphens between words
// Deprecated: for resource names use `ForResource` instead | func New(id manifold.ID) (string, string) {
idBytes := id[2:]
offset := 0
adj, offset := fetchWord(idBytes, data.Adjectives, offset, aShare)
color, offset := fetchWord(idBytes, data.Colors, offset, cShare)
shape, _ := fetchWord(idBytes, data.Shapes, offset, sShare)
name := strings.Title(adj + " " + color + " " + shape)
label := strings.Replace(strings.ToLower(name), " ", "-", -1)
return name, label
} |
{@inheritDoc}
@param observer {@inheritDoc} | @Override
public void addDataObserver(Observer<DataProvider<M>, M> observer) {
dataObserver.addObserver(observer);
} |
Computes the cost of this point with centre centre | public double costOfPointToCenter(Point centre){
if(this.weight == 0.0){
return 0.0;
}
//stores the distance between p and centre
double distance = 0.0;
//loop counter
for(int l=0; l<this.dimension; l++){
//Centroid coordinate of the point
double centroidCoordinatePoint;
if(this.weight != 0.0){
centroidCoordinatePoint = this.coordinates[l] / this.weight;
} else {
centroidCoordinatePoint = this.coordinates[l];
}
//Centroid coordinate of the centre
double centroidCoordinateCentre;
if(centre.weight != 0.0){
centroidCoordinateCentre = centre.coordinates[l] / centre.weight;
} else {
centroidCoordinateCentre = centre.coordinates[l];
}
distance += (centroidCoordinatePoint-centroidCoordinateCentre) *
(centroidCoordinatePoint-centroidCoordinateCentre) ;
}
return distance * this.weight;
} |
Sets whether trace logging should be enabled.
Enabling trace logging automatically enables debug logging, too.
@param trace Whether trace logging should be enabled or not. | public static void setTrace(boolean trace) {
FallbackLoggerConfiguration.trace.set(trace);
if (trace) {
debug.set(true);
}
} |
Force save the model even if validation fails.
@param array $rules
@param array $customMessages
@param array $options
@param Closure $beforeSave
@param Closure $afterSave
@return bool
@see SmartModel::save() | public function forceSave(array $rules = array(),
array $customMessages = array(),
array $options = array(),
Closure $beforeSave = null,
Closure $afterSave = null
) {
return $this->internalSave($rules, $customMessages, $options, $beforeSave, $afterSave, true);
} |
TODO: Support case-insensitive models | public DataType resolveProperty(DataType sourceType, String identifier, boolean mustResolve) {
DataType currentType = sourceType;
while (currentType != null) {
if (currentType instanceof ClassType) {
ClassType classType = (ClassType)currentType;
for (ClassTypeElement e : classType.getElements()) {
if (e.getName().equals(identifier)) {
if (e.isProhibited()) {
throw new IllegalArgumentException(String.format("Element %s cannot be referenced because it is marked prohibited in type %s.", e.getName(), ((ClassType) currentType).getName()));
}
return e.getType();
}
}
}
else if (currentType instanceof TupleType) {
TupleType tupleType = (TupleType)currentType;
for (TupleTypeElement e : tupleType.getElements()) {
if (e.getName().equals(identifier)) {
return e.getType();
}
}
}
else if (currentType instanceof IntervalType) {
IntervalType intervalType = (IntervalType)currentType;
switch (identifier) {
case "low":
case "high":
return intervalType.getPointType();
case "lowClosed":
case "highClosed":
return resolveTypeName("System", "Boolean");
default:
// ERROR:
throw new IllegalArgumentException(String.format("Invalid interval property name %s.", identifier));
}
}
else if (currentType instanceof ChoiceType) {
ChoiceType choiceType = (ChoiceType)currentType;
// TODO: Issue a warning if the property does not resolve against every type in the choice
// Resolve the property against each type in the choice
Set<DataType> resultTypes = new HashSet<>();
for (DataType choice : choiceType.getTypes()) {
DataType resultType = resolveProperty(choice, identifier, false);
if (resultType != null) {
resultTypes.add(resultType);
}
}
// The result type is a choice of all the resolved types
if (resultTypes.size() > 1) {
return new ChoiceType(resultTypes);
}
if (resultTypes.size() == 1) {
for (DataType resultType : resultTypes) {
return resultType;
}
}
}
else if (currentType instanceof ListType && listTraversal) {
// NOTE: FHIRPath path traversal support
// Resolve property as a list of items of property of the element type
ListType listType = (ListType)currentType;
DataType resultType = resolveProperty(listType.getElementType(), identifier);
return new ListType(resultType);
}
if (currentType.getBaseType() != null) {
currentType = currentType.getBaseType();
}
else {
break;
}
}
if (mustResolve) {
// ERROR:
throw new IllegalArgumentException(String.format("Member %s not found for type %s.", identifier, sourceType != null ? sourceType.toLabel() : null));
}
return null;
} |
Images should be a (N_images x pixels) matrix. | def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),
cmap=matplotlib.cm.binary, vmin=None, vmax=None):
""""""
N_images = images.shape[0]
N_rows = (N_images - 1) // ims_per_row + 1
pad_value = np.min(images.ravel())
concat_images = np.full(((digit_dimensions[0] + padding) * N_rows + padding,
(digit_dimensions[1] + padding) * ims_per_row + padding), pad_value)
for i in range(N_images):
cur_image = np.reshape(images[i, :], digit_dimensions)
row_ix = i // ims_per_row
col_ix = i % ims_per_row
row_start = padding + (padding + digit_dimensions[0]) * row_ix
col_start = padding + (padding + digit_dimensions[1]) * col_ix
concat_images[row_start: row_start + digit_dimensions[0],
col_start: col_start + digit_dimensions[1]] = cur_image
cax = ax.matshow(concat_images, cmap=cmap, vmin=vmin, vmax=vmax)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
return cax |
Checks to see if all the provided matrices are the expected size for an SVD. If an error is encountered
then an exception is thrown. This automatically handles compact and non-compact formats | public static void checkSvdMatrixSize(DMatrixRMaj U, boolean tranU, DMatrixRMaj W, DMatrixRMaj V, boolean tranV ) {
int numSingular = Math.min(W.numRows,W.numCols);
boolean compact = W.numRows == W.numCols;
if( compact ) {
if( U != null ) {
if( tranU && U.numRows != numSingular )
throw new IllegalArgumentException("Unexpected size of matrix U");
else if( !tranU && U.numCols != numSingular )
throw new IllegalArgumentException("Unexpected size of matrix U");
}
if( V != null ) {
if( tranV && V.numRows != numSingular )
throw new IllegalArgumentException("Unexpected size of matrix V");
else if( !tranV && V.numCols != numSingular )
throw new IllegalArgumentException("Unexpected size of matrix V");
}
} else {
if( U != null && U.numRows != U.numCols )
throw new IllegalArgumentException("Unexpected size of matrix U");
if( V != null && V.numRows != V.numCols )
throw new IllegalArgumentException("Unexpected size of matrix V");
if( U != null && U.numRows != W.numRows )
throw new IllegalArgumentException("Unexpected size of W");
if( V != null && V.numRows != W.numCols )
throw new IllegalArgumentException("Unexpected size of W");
}
} |
// Reset stores the new reader and resets its bytes.Buffer and proto.Buffer | func (dec *ProtoDecoder) Reset(r io.Reader) {
dec.pBuf.Reset()
dec.bBuf.Reset()
dec.r = r
} |
// isAuditedAtProxy returns true if sessions are being recorded at the proxy
// and this is a Teleport node. | func (s *Server) isAuditedAtProxy() bool {
// always be safe, better to double record than not record at all
clusterConfig, err := s.GetAccessPoint().GetClusterConfig()
if err != nil {
return false
}
isRecordAtProxy := clusterConfig.GetSessionRecording() == services.RecordAtProxy
isTeleportNode := s.Component() == teleport.ComponentNode
if isRecordAtProxy && isTeleportNode {
return true
}
return false
} |
Lazy load, create or adapt the table structure in the database. | def _sync_table(self, columns):
""""""
if self._table is None:
# Load an existing table from the database.
self._reflect_table()
if self._table is None:
# Create the table with an initial set of columns.
if not self._auto_create:
raise DatasetException("Table does not exist: %s" % self.name)
# Keep the lock scope small because this is run very often.
with self.db.lock:
self._threading_warn()
self._table = SQLATable(self.name,
self.db.metadata,
schema=self.db.schema)
if self._primary_id is not False:
# This can go wrong on DBMS like MySQL and SQLite where
# tables cannot have no columns.
primary_id = self._primary_id or self.PRIMARY_DEFAULT
primary_type = self._primary_type or Types.integer
increment = primary_type in [Types.integer, Types.bigint]
column = Column(primary_id, primary_type,
primary_key=True,
autoincrement=increment)
self._table.append_column(column)
for column in columns:
if not column.name == self._primary_id:
self._table.append_column(column)
self._table.create(self.db.executable, checkfirst=True)
elif len(columns):
with self.db.lock:
self._reflect_table()
self._threading_warn()
for column in columns:
if not self.has_column(column.name):
self.db.op.add_column(self.name, column, self.db.schema)
self._reflect_table() |
// NewCiliumHealthAPI creates a new CiliumHealth instance | func NewCiliumHealthAPI(spec *loads.Document) *CiliumHealthAPI {
return &CiliumHealthAPI{
handlers: make(map[string]map[string]http.Handler),
formats: strfmt.Default,
defaultConsumes: "application/json",
defaultProduces: "application/json",
customConsumers: make(map[string]runtime.Consumer),
customProducers: make(map[string]runtime.Producer),
ServerShutdown: func() {},
spec: spec,
ServeError: errors.ServeError,
BasicAuthenticator: security.BasicAuth,
APIKeyAuthenticator: security.APIKeyAuth,
BearerAuthenticator: security.BearerAuth,
JSONConsumer: runtime.JSONConsumer(),
JSONProducer: runtime.JSONProducer(),
GetHealthzHandler: GetHealthzHandlerFunc(func(params GetHealthzParams) middleware.Responder {
return middleware.NotImplemented("operation GetHealthz has not yet been implemented")
}),
GetHelloHandler: GetHelloHandlerFunc(func(params GetHelloParams) middleware.Responder {
return middleware.NotImplemented("operation GetHello has not yet been implemented")
}),
ConnectivityGetStatusHandler: connectivity.GetStatusHandlerFunc(func(params connectivity.GetStatusParams) middleware.Responder {
return middleware.NotImplemented("operation ConnectivityGetStatus has not yet been implemented")
}),
ConnectivityPutStatusProbeHandler: connectivity.PutStatusProbeHandlerFunc(func(params connectivity.PutStatusProbeParams) middleware.Responder {
return middleware.NotImplemented("operation ConnectivityPutStatusProbe has not yet been implemented")
}),
}
} |
Change password.
@return boolean Whether the password changed. | public function changePassword()
{
if ($this->validate()) {
if (!($user = $this->getUser())) {
return false;
}
if (!$user->applyForNewPassword()) {
return false;
}
return $user->resetPassword($this->new_password, $user->getPasswordResetToken());
}
return false;
} |
// Errorf2 is part of the Logger interface | func (tl *TeeLogger) Errorf2(err error, format string, v ...interface{}) {
tl.ErrorDepth(1, fmt.Sprintf(format+": %+v", append(v, err)))
} |
Parses class property
@param string $fullClassName Name of the class
@param string $propertyName Name of the property
@return array Pair of [Property and PropertyProperty] nodes | public static function parseClassProperty($fullClassName, $propertyName)
{
$class = self::parseClass($fullClassName);
$classNodes = $class->stmts;
foreach ($classNodes as $classLevelNode) {
if ($classLevelNode instanceof Property) {
foreach ($classLevelNode->props as $classProperty) {
if ($classProperty->name->toString() == $propertyName) {
return [$classLevelNode, $classProperty];
}
}
}
}
throw new \InvalidArgumentException("Property $propertyName was not found in the $fullClassName");
} |
// NewStaticIterator constructs a random iterator from a list of nodes | func NewStaticIterator(ctx Context, nodes []*structs.Node) *StaticIterator {
iter := &StaticIterator{
ctx: ctx,
nodes: nodes,
}
return iter
} |
Creates the client object using the specified parameters.
@return The build client
@since 1.0.0 | public Client build() {
validate();
Client client = new Client(database, credentials, host, scheme);
return client;
} |
// Trace adds a TRACE route > handler to the router. | func Trace(path string, h interface{}, m ...interface{}) {
Default.Trace(path, h, m...)
} |
{@inheritDoc}
Try to authenticate a pre-authenticated user with Spring Security if the user has not yet been authenticated. | @Override
protected void doCommonFilter(PortletRequest request, PortletResponse response,
javax.portlet.filter.FilterChain chain) throws IOException, PortletException {
if (logger.isDebugEnabled()) {
logger.debug("Checking secure context token: " + SecurityContextHolder.getContext().getAuthentication());
}
if (requiresAuthentication((PortletRequest) request)) {
doAuthenticate((PortletRequest) request, (PortletResponse) response);
}
PortletFilterUtils.doFilter(request, response, chain);
} |
// GetTrafficMonitoringConfig トラフィックコントロール 取得 | func (api *MobileGatewayAPI) GetTrafficMonitoringConfig(id int64) (*sacloud.TrafficMonitoringConfig, error) {
var (
method = "GET"
uri = fmt.Sprintf("%s/%d/mobilegateway/traffic_monitoring", api.getResourceURL(), id)
)
res := &trafficMonitoringBody{}
err := api.baseAPI.request(method, uri, nil, res)
if err != nil {
return nil, err
}
return res.TrafficMonitoring, nil
} |
Hook that allows actions when data was saved
When not rerouted, the form will be populated afterwards
@param int $changed The number of changed rows (0 or 1 usually, but can be more) | protected function afterSave($changed)
{
if ($changed) {
$this->accesslog->logChange($this->request, null, $this->formData);
// Reload the current user data
$user = $this->currentUser;
$currentOrg = $user->getCurrentOrganizationId();
$this->loader->getUserLoader()->unsetCurrentUser();
$user = $this->loader->getUser($user->getLoginName(), $user->getBaseOrganizationId())->setAsCurrentUser();
$user->setCurrentOrganization($currentOrg);
// In case locale has changed, set it in a cookie
\Gems_Cookies::setLocale($this->formData['gsf_iso_lang'], $this->basepath);
$this->addMessage($this->_('Saved your setup data', $this->formData['gsf_iso_lang']));
} else {
$this->addMessage($this->_('No changes to save!'));
}
if ($this->cacheTags && ($this->cache instanceof \Zend_Cache_Core)) {
$this->cache->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, (array) $this->cacheTags);
}
} |
// InsertCIDR inserts an entry to 'cm' with key 'cidr'. Value is currently not
// used. | func (cm *CIDRMap) InsertCIDR(cidr net.IPNet) error {
key := cm.cidrKeyInit(cidr)
entry := [LPM_MAP_VALUE_SIZE]byte{}
if err := cm.checkPrefixlen(&key, "update"); err != nil {
return err
}
log.WithField(logfields.Path, cm.path).Debugf("Inserting CIDR entry %s", cidr.String())
return bpf.UpdateElement(cm.Fd, unsafe.Pointer(&key), unsafe.Pointer(&entry), 0)
} |
Returns true if there is a permission for the given id
@access public
@param integer $id
@return boolean
@throws \Zepi\Core\AccessControl\Exception Cannot check if there is a permission for the given id "{id}". | public function hasPermissionForId($id)
{
try {
$em = $this->entityManager->getDoctrineEntityManager();
$permission = $em->getRepository('\\Zepi\\Core\\AccessControl\\Entity\\Permission')->find($id);
if ($permission !== null) {
return true;
}
return false;
} catch (\Exception $e) {
throw new Exception('Cannot check if there is a permission for the given id "' . $id . '".', 0, $e);
}
} |
// EncodeJSON encodes a transaction into a JSON data dump. | func (tx *Transaction) EncodeJSON() (string, error) {
data, err := json.Marshal(tx.tx)
return string(data), err
} |
// hasKeyPath - if the map 'key' exists append it to KeyPath.path and increment KeyPath.depth
// This is really just a breadcrumber that saves all trails that hit the prescribed 'key'. | func hasKeyPath(crumb string, iv interface{}, key string, basket *map[string]bool) {
switch iv.(type) {
case map[string]interface{}:
vv := iv.(map[string]interface{})
if _, ok := vv[key]; ok {
if crumb == "" {
crumb = key
} else {
crumb += "." + key
}
// *basket = append(*basket, crumb)
(*basket)[crumb] = true
}
// walk on down the path, key could occur again at deeper node
for k, v := range vv {
// create a new breadcrumb, add the one we're at to the crumb-trail
var nbc string
if crumb == "" {
nbc = k
} else {
nbc = crumb + "." + k
}
hasKeyPath(nbc, v, key, basket)
}
case []interface{}:
// crumb-trail doesn't change, pass it on
for _, v := range iv.([]interface{}) {
hasKeyPath(crumb, v, key, basket)
}
}
} |
helpers.
@param [type] $string [description]
@param [type] $event [description]
@return [type] [description] | public function alert($string, $event)
{
$this->comment(str_repeat('*', strlen($string) + 12), $event);
$this->comment('* ' . $string . ' *', $event);
$this->comment(str_repeat('*', strlen($string) + 12), $event);
} |
// SetSizeConstraints sets the SizeConstraints field's value. | func (s *SizeConstraintSet) SetSizeConstraints(v []*SizeConstraint) *SizeConstraintSet {
s.SizeConstraints = v
return s
} |
Add metadata filters to metadata resolver.
@param metadataProvider the metadata provider
@param metadataFilterList the metadata filter list | protected void addMetadataFiltersToMetadataResolver(final AbstractMetadataResolver metadataProvider, final MetadataFilter... metadataFilterList) {
addMetadataFiltersToMetadataResolver(metadataProvider, Arrays.stream(metadataFilterList).collect(Collectors.toList()));
} |
Shows collections with ACL. | def access_storage_list(**kwargs):
ctx = Context(**kwargs)
ctx.execute_action('access:storage:list', **{
'storage': ctx.repo.create_secure_service('storage'),
}) |
escape quotes by doubling them when we need a string inside quotes
@param o
@return | protected String escapeQuotes(Object o) {
if (o != null) {
return o.toString().replace("'", "''");
}
return null;
} |
// ImageWxH returns a screenshot at the ts milliseconds, scaled to the specified width and height. | func (g *Generator) ImageWxH(ts int64, width, height int) (image.Image, error) {
frameNum := C.av_rescale(
C.int64_t(ts),
C.int64_t(g.streams[g.vStreamIndex].time_base.den),
C.int64_t(g.streams[g.vStreamIndex].time_base.num),
) / 1000
if C.avformat_seek_file(
g.avfContext,
C.int(g.vStreamIndex),
0,
frameNum,
frameNum,
C.AVSEEK_FLAG_FRAME,
) < 0 {
if C.avformat_seek_file(
g.avfContext,
C.int(g.vStreamIndex),
0,
frameNum,
frameNum,
C.AVSEEK_FLAG_ANY,
) < 0 {
return nil, errors.New("can't seek to timestamp")
}
}
img := image.NewRGBA(image.Rect(0, 0, width, height))
frame := C.av_frame_alloc()
defer C.av_frame_free(&frame)
C.avcodec_flush_buffers(g.avcContext)
pkt := C.av_packet_alloc()
for C.av_read_frame(g.avfContext, pkt) == 0 {
if int(pkt.stream_index) != g.vStreamIndex {
C.av_packet_unref(pkt)
continue
}
if C.avcodec_send_packet(g.avcContext, pkt) != 0 {
C.av_packet_unref(pkt)
return nil, errors.New("avcodec_send_packet failed")
}
dts := pkt.dts
C.av_packet_unref(pkt)
if ret := C.avcodec_receive_frame(g.avcContext, frame); ret != 0 {
if ret != C.AVERROR_EAGAIN {
return nil, errors.New("avcodec_receive_frame failed")
}
continue
}
if !g.Fast && dts < frameNum {
continue
}
ctx := C.sws_getContext(
C.int(g.width),
C.int(g.height),
g.avcContext.pix_fmt,
C.int(width),
C.int(height),
C.AV_PIX_FMT_RGBA,
C.SWS_BICUBIC,
nil,
nil,
nil,
)
if ctx == nil {
return nil, errors.New("can't allocate scaling context")
}
srcSlice := (**C.uint8_t)(&frame.data[0])
srcStride := (*C.int)(&frame.linesize[0])
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&img.Pix))
dst := (*C.uint8_t)(unsafe.Pointer(hdr.Data))
dstStride := (*C.int)(unsafe.Pointer(&[1]int{img.Stride}))
C.sws_scale_wrapper(
ctx,
srcSlice,
srcStride,
0,
g.avcContext.height,
dst,
dstStride,
)
C.sws_freeContext(ctx)
break
}
return img, nil
} |
Returns true if the property exists on the wrapped object.
@param string $property The name of the property to search for.
@return boolean True if the property exists. | public function __isset($property)
{
if ($propertyReflector = $this->liberatorPropertyReflector($property)) {
return null !== $propertyReflector->getValue($this->popsValue());
}
return parent::__isset($property);
} |
Check if value/values are not empty
This method uses func_get_args() so you can pass in as many variables/items as you want!
@return boolean True if all value/values are not empty, false if one of the elements are empty | public static function isNotEmpty() {
$args = func_get_args();
foreach ($args as $item) {
if (is_array($item) && empty($item)) {
return false;
}
else {
$item = trim($item);
if (empty($item) && $item !== "0") //0 as string is allowed, a field can be zero as string
return false;
}
}
return true;
} |
Adds a tablespace to the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.tablespace_create tablespacename '/path/datadir'
.. versionadded:: 2015.8.0 | def tablespace_create(name, location, options=None, owner=None, user=None,
host=None, port=None, maintenance_db=None, password=None,
runas=None):
'''
'''
owner_query = ''
options_query = ''
if owner:
owner_query = 'OWNER "{0}"'.format(owner)
# should come out looking like: 'OWNER postgres'
if options:
optionstext = ['{0} = {1}'.format(k, v) for k, v in six.iteritems(options)]
options_query = 'WITH ( {0} )'.format(', '.join(optionstext))
# should come out looking like: 'WITH ( opt1 = 1.0, opt2 = 4.0 )'
query = 'CREATE TABLESPACE "{0}" {1} LOCATION \'{2}\' {3}'.format(name,
owner_query,
location,
options_query)
# Execute the command
ret = _psql_prepare_and_run(['-c', query],
user=user, host=host, port=port,
maintenance_db=maintenance_db,
password=password, runas=runas)
return ret['retcode'] == 0 |
Get the blocks around the one given.
Returns: a list of all of those blocks. | def get_surrounding_blocks(self):
next = self.next_blocks()
prev = self.previous_blocks()
surrounding_blocks = list(chain(prev, [self], next))
return surrounding_blocks |
// Generate create a pid file for own process. | func Generate(pidfile string, chDel <-chan struct{}) error {
f, err := os.OpenFile(pidfile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
fmt.Fprintln(f, os.Getpid())
if chDel != nil {
go func() {
select {
case <-chDel:
os.Remove(pidfile)
}
}()
}
return nil
} |
移除事件监听
@param string $type 事件类型
@param string $plugin 监听器 | public function removeEventListener($type, $plugin) {
$type = strtolower($type);
if (isset($this->eventsListeners[$type]) && in_array($plugin, $this->eventsListeners[$type])) {
$index = array_search($plugin, $this->eventsListeners[$type]);
array_splice($this->eventsListeners[$type], $index, 1);
}
} |
Decrement a raw value
@param string $id Cache ID
@param int $offset Step/value to reduce by
@return mixed New value on success or FALSE on failure | public function decrement($id, $offset = 1)
{
$success = FALSE;
$value = wincache_ucache_dec($id, $offset, $success);
return ($success === TRUE) ? $value : FALSE;
} |
Evaluate text passed by L{_partialParseDateStd()} | def _evalDateStd(self, datetimeString, sourceTime):
s = datetimeString.strip()
sourceTime = self._evalDT(datetimeString, sourceTime)
# Given string is in the format 07/21/2006
return self.parseDate(s, sourceTime) |
Returns an instance of Month for the given month value.
@param int $value The month number, from 1 (January) to 12 (December).
@return Month The Month instance.
@throws DateTimeException | public static function of(int $value) : Month
{
Field\MonthOfYear::check($value);
return Month::get($value);
} |
Build the syntax tree for kubectl command line | def build(self, root, schema):
if schema.get("subcommands") and schema["subcommands"]:
for subcmd, childSchema in schema["subcommands"].items():
child = CommandTree(node=subcmd)
child = self.build(child, childSchema)
root.children.append(child)
# {args: {}, options: {}, help: ""}
root.help = schema.get("help")
for name, desc in schema.get("options").items():
if root.node == "kubectl": # register global flags
self.globalFlags.append(Option(name, desc["help"]))
root.localFlags.append(Option(name, desc["help"]))
for arg in schema.get("args"):
node = CommandTree(node=arg)
root.children.append(node)
return root |
convertSlice
Convert a slice.
@access protected
@param array $values
@param string $name
@return array | protected function convertSlice(array $values, $name)
{
$type = $this->projection->getFieldType($name);
$converter = $this->hydration_plan->getConverterForField($name);
return array_map(
function ($val) use ($converter, $type) {
return $converter->fromPg($val, $type, $this->session);
},
$values
);
} |
Checks a field signature.
@param signature
a string containing the signature that must be checked. | public static void checkFieldSignature(final String signature) {
int pos = checkFieldTypeSignature(signature, 0);
if (pos != signature.length()) {
throw new IllegalArgumentException(signature + ": error at index "
+ pos);
}
} |
Serialize model to filename. | def save(self, filename):
with open(filename, 'wb') as savefile:
pickle.dump(self.__dict__,
savefile,
protocol=pickle.HIGHEST_PROTOCOL) |
Equal to calling parseInt(cs, 10).
@param cs
@return
@throws java.lang.NumberFormatException if input cannot be parsed to proper
int.
@see java.lang.Integer#parseInt(java.lang.String)
@see java.lang.Character#digit(int, int) | public static final int parseInt(CharSequence cs)
{
if (CharSequences.startsWith(cs, "0b"))
{
return parseInt(cs, 2, 2, cs.length());
}
if (CharSequences.startsWith(cs, "0x"))
{
return parseInt(cs, 16, 2, cs.length());
}
return parseInt(cs, 10);
} |
// SetCenter positions the space component according to its center instead of its
// top-left point (this avoids doing the same math each time in your systems) | func (sc *SpaceComponent) SetCenter(p engo.Point) {
xDelta := sc.Width / 2
yDelta := sc.Height / 2
// update position according to point being used as our center
if sc.Rotation == 0 {
sc.Position.X = p.X - xDelta
sc.Position.Y = p.Y - yDelta
return
}
sin, cos := math.Sincos(sc.Rotation * math.Pi / 180)
xDelta = (sc.Width*cos - sc.Height*sin) / 2
yDelta = (sc.Height*cos + sc.Width*sin) / 2
sc.Position.X = p.X - xDelta
sc.Position.Y = p.Y - yDelta
} |
Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
8 bit unsigned version | def _leu8(ins):
output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True)
output.append('sub h') # Carry if H > A
output.append('ccf') # Negates => Carry if H <= A
output.append('sbc a, a')
output.append('push af')
return output |
// SetQuantity sets the Quantity field's value. | func (s *GeoRestriction) SetQuantity(v int64) *GeoRestriction {
s.Quantity = &v
return s
} |
Just run the checks for our modules | def run_checks(collector):
""""""
artifact = collector.configuration["dashmat"].artifact
chosen = artifact
if chosen in (None, "", NotSpecified):
chosen = None
dashmat = collector.configuration["dashmat"]
modules = collector.configuration["__active_modules__"]
config_root = collector.configuration["config_root"]
module_options = collector.configuration["modules"]
datastore = JsonDataStore(os.path.join(config_root, "data.json"))
if dashmat.redis_host:
datastore = RedisDataStore(redis.Redis(dashmat.redis_host))
scheduler = Scheduler(datastore)
for name, module in modules.items():
if chosen is None or name == chosen:
server = module.make_server(module_options[name].server_options)
scheduler.register(module, server, name)
scheduler.twitch(force=True) |
Writes an unsigned value whose size is, in maximum, {@value Byte#SIZE}.
@param size the number of lower bits to write; between {@code 1} and {@value Byte#SIZE}, both inclusive.
@param value the value to write
@throws IOException if an I/O error occurs. | protected void unsigned8(final int size, int value) throws IOException {
requireValidSizeUnsigned8(size);
final int required = size - available;
if (required > 0) {
unsigned8(available, value >> required);
unsigned8(required, value);
return;
}
octet <<= size;
octet |= (value & ((1 << size) - 1));
available -= size;
if (available == 0) {
write(octet);
count++;
octet = 0x00;
available = Byte.SIZE;
}
} |
Obtains the super type element for a given type element.
@param element The type element
@return The super type element or null if none exists | TypeElement superClassFor(TypeElement element) {
TypeMirror superclass = element.getSuperclass();
if (superclass.getKind() == TypeKind.NONE) {
return null;
}
DeclaredType kind = (DeclaredType) superclass;
return (TypeElement) kind.asElement();
} |
Execute a block of code within a given scope. If `locator` begins with
`/` or `./`, then it's assumed to be an XPath selector; otherwise, it's
assumed to be a CSS selector. | def scope_within(locator)
if locator
# Use the selector_for method if it's defined. This may be provided
# by features/support/selectors.rb, generated by cucumber-rails.
if defined? selector_for
kelp_within(*selector_for(locator)) { yield }
# Otherwise, fall back on the Capybara locator syntax (CSS or XPath)
else
if locator =~ /\.?\//
kelp_within(:xpath, locator) { yield }
else
kelp_within(:css, locator) { yield }
end
end
else
yield
end
end |
Segment all the pofiles for `locale`.
Returns a set of filenames, all the segment files written. | def segment_pofiles(configuration, locale):
files_written = set()
for filename, segments in configuration.segment.items():
filename = configuration.get_messages_dir(locale) / filename
files_written.update(segment_pofile(filename, segments))
return files_written |
防止csrf跨站攻击
@param int $type 检测类型 0不检查,1、只检查post,2、post get都检查 | public static function checkCsrf($type = 1)
{
if ($type !== 0 && isset($_SERVER['HTTP_REFERER']) && !strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'])) {
if ($type == 1) {
if (!empty($_POST)) {
Response::sendHttpStatus(403);
throw new \UnexpectedValueException(Lang::get('_ILLEGAL_REQUEST_'));
}
} else {
Response::sendHttpStatus(403);
throw new \UnexpectedValueException(Lang::get('_ILLEGAL_REQUEST_'));
}
}
} |
[DEPRECATED] Compute the maximum number of record pairs possible. | def max_pairs(shape):
""""""
if not isinstance(shape, (tuple, list)):
x = get_length(shape)
n = int(x * (x - 1) / 2)
elif (isinstance(shape, (tuple, list)) and len(shape) == 1):
x = get_length(shape[0])
n = int(x * (x - 1) / 2)
else:
n = numpy.prod([get_length(xi) for xi in shape])
return n |
Retrieves the index of a link with a specified ID.
<p>Link indexes are consecutive integers starting from 1.
@param id link ID label.
@return the link index.
@throws EpanetException | public int ENgetlinkindex( String id ) throws EpanetException {
int[] index = new int[1];
int error = epanet.ENgetlinkindex(id, index);
checkError(error);
return index[0];
} |
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects | def clustal_align_protein(recs, work_dir, outfmt="fasta"):
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
clustal_cl = ClustalwCommandline(cmd=CLUSTALW_BIN("clustalw2"),
infile=fasta_file, outfile=align_file, outorder="INPUT",
type="PROTEIN")
stdout, stderr = clustal_cl()
aln_file = file(clustal_cl.outfile)
alignment = AlignIO.read(aln_file, "clustal")
print("\tDoing clustalw alignment: %s" % clustal_cl, file=sys.stderr)
if outfmt == "fasta":
return alignment.format("fasta")
if outfmt == "clustal":
return alignment |
// NewRangeScanner initializes a new range scanner. It takes a `min` and a
// `max` key for specifying the range paramaters. | func (bk *Bucket) NewRangeScanner(min, max []byte) *RangeScanner {
return &RangeScanner{bk.db, bk.Name, min, max}
} |
Dispatches a Route, executing its action.
@param Route $route The route to be executed.
@param Request $request The request information, if available. Used for mapping route variables.
@return mixed Route target function return value, if any. | public function dispatch(Route $route, Request $request = null)
{
$context = $this->context;
if (empty($this->context) && !empty($request)) {
// If we have no context, but do have a request, prepare a context to store path variables in.
// Otherwise routing path variables would be lost for no good reason.
$context = new Context();
$context->registerInstance($request);
}
if (!empty($context)) {
// If we have a context, ensure that the route is made available in it.
$context->registerInstance($route);
if (!empty($request)) {
// If we have a request, map the path variables and pass them to the context as primitive types by name.
// This will allow us to inject info from a route e.g. "/view/$userId" to a $userId variable.
$pathVariables = VariableUrl::extractUrlVariables($request->getRequestUri(), $route->getPattern());
foreach ($pathVariables as $name => $value) {
$context->registerVariable($name, $value);
}
}
}
return $route->action($context);
} |
// WithMaxConcurrentDownloads sets max concurrent download limit. | func WithMaxConcurrentDownloads(max int) RemoteOpt {
return func(client *Client, c *RemoteContext) error {
c.MaxConcurrentDownloads = max
return nil
}
} |
Verifies the signature for the response.
@throws InvalidResponseException if the signature doesn't match
@return void | public function verifySignature()
{
if ( isset($this->data['CreditCardTransactionResults']['ResponseCode']) && (
'1' == $this->data['CreditCardTransactionResults']['ResponseCode'] ||
'2' == $this->data['CreditCardTransactionResults']['ResponseCode']) )
{
$signature = $this->request->getMerchantPassword();
$signature .= $this->request->getMerchantId();
$signature .= $this->request->getAcquirerId();
$signature .= $this->request->getTransactionId();
$signature = base64_encode( sha1($signature, true) );
if ( $signature !== $this->data['Signature'] ) {
throw new InvalidResponseException('Signature verification failed');
}
}
} |
Creates {@link KeyManager} instances based on the given parameters.
@param keyStoreFile path to keyStore file
@param pass password for keyStore
@return an array of {@link KeyManager} instances
@throws InitializationException | public static KeyManager[] getKeyManagers(String keyStoreFile, String pass)
throws InitializationException {
return getKeyManagers(getFileAsInputStream(keyStoreFile), pass);
} |
Query widget option.
:param key: option name
:type key: str
:return: value of the option
To get the list of options for this widget, call the method :meth:`~LinkLabel.keys`. | def cget(self, key):
if key is "link":
return self._link
elif key is "hover_color":
return self._hover_color
elif key is "normal_color":
return self._normal_color
elif key is "clicked_color":
return self._clicked_color
else:
return ttk.Label.cget(self, key) |
// IsDir checks if the given path is a directory | func (u *volumeUtil) IsDir(fullPath string) (bool, error) {
dir, err := os.Open(fullPath)
if err != nil {
return false, err
}
defer dir.Close()
stat, err := dir.Stat()
if err != nil {
return false, err
}
return stat.IsDir(), nil
} |
:param acs: List of AttributeConverter instances
:param attr: an Attribute instance
:return: The local attribute name | def to_local_name(acs, attr):
for aconv in acs:
lattr = aconv.from_format(attr)
if lattr:
return lattr
return attr.friendly_name |
Remove all joins linked to a specific attachment.
@return boolean | public function removeAttachmentJoins()
{
$joinProto = $this->modelFactory()->get(Join::class);
$loader = $this->collectionLoader();
$loader
->setModel($joinProto)
->addFilter('object_type', $this->objType())
->addFilter('object_id', $this->id());
$collection = $loader->load();
foreach ($collection as $obj) {
$obj->delete();
}
return true;
} |
// Filter based on extender implemented predicate functions. The filtered list is
// expected to be a subset of the supplied list. failedNodesMap optionally contains
// the list of failed nodes and failure reasons. | func (h *HTTPExtender) Filter(
pod *v1.Pod,
nodes []*v1.Node, nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
) ([]*v1.Node, schedulerapi.FailedNodesMap, error) {
var (
result schedulerapi.ExtenderFilterResult
nodeList *v1.NodeList
nodeNames *[]string
nodeResult []*v1.Node
args *schedulerapi.ExtenderArgs
)
if h.filterVerb == "" {
return nodes, schedulerapi.FailedNodesMap{}, nil
}
if h.nodeCacheCapable {
nodeNameSlice := make([]string, 0, len(nodes))
for _, node := range nodes {
nodeNameSlice = append(nodeNameSlice, node.Name)
}
nodeNames = &nodeNameSlice
} else {
nodeList = &v1.NodeList{}
for _, node := range nodes {
nodeList.Items = append(nodeList.Items, *node)
}
}
args = &schedulerapi.ExtenderArgs{
Pod: pod,
Nodes: nodeList,
NodeNames: nodeNames,
}
if err := h.send(h.filterVerb, args, &result); err != nil {
return nil, nil, err
}
if result.Error != "" {
return nil, nil, fmt.Errorf(result.Error)
}
if h.nodeCacheCapable && result.NodeNames != nil {
nodeResult = make([]*v1.Node, 0, len(*result.NodeNames))
for i := range *result.NodeNames {
nodeResult = append(nodeResult, nodeNameToInfo[(*result.NodeNames)[i]].Node())
}
} else if result.Nodes != nil {
nodeResult = make([]*v1.Node, 0, len(result.Nodes.Items))
for i := range result.Nodes.Items {
nodeResult = append(nodeResult, &result.Nodes.Items[i])
}
}
return nodeResult, result.FailedNodes, nil
} |
Adds an annotated Class to xmlJmapper structure.
@param aClass Class to convert to XmlClass
@return this instance of XML | private XML addClass(Class<?> aClass){
xmlJmapper.classes.add(Converter.toXmlClass(aClass));
return this;
} |
Merge two PDFs one after the other.
@param $firstPDFPath
@param $secondPDFPath
@param null $outputDestination | public function joinTwoPDFs($firstPDFPath, $secondPDFPath, $outputDestination = null)
{
$firstPDF = new \PDFDoc($firstPDFPath);
$firstPDF->InitSecurityHandler();
$secondPDF = new \PDFDoc($secondPDFPath);
$firstPDF->InsertPages(1, $secondPDF, 1, $secondPDF->GetPageCount(), \PDFDoc::e_none);
$secondPDF->Close();
if (!empty($outputDestination)) {
$firstPDF->Save($outputDestination, \SDFDoc::e_remove_unused);
} else {
$firstPDF->Save($firstPDFPath, \SDFDoc::e_remove_unused);
}
} |
A trivial int-to-hex converter | public static void main(String[] args) {
System.err.println(toString(new int[] { Integer.parseInt(args[0]) }));
} |
create name before creating a new role instance.
@param array $data
@return EloquentRole | public function create(array $data)
{
if (! array_key_exists('name', $data)) {
$data['name'] = Str::slug($data['display_name']);
}
return parent::create($data);
} |
Get primary key
@param bool $require
@return mixed
@throws NoPkException | public function getPK($require = true)
{
foreach ($this->fields as $field) {
if ($field->pk()) {
return $field;
}
}
if ($require) {
throw new NoPKException();
}
} |
裁剪图片,如果不传入$startX, $startY, 则默认从图片正中间开始裁剪
@param int $width 裁剪高度
@param int $height 裁剪宽度
@param int $startX 裁剪起始位置横坐标
@param int $startY 裁剪起始位置纵坐标
@return $this | public function crop($width, $height, $startX=null, $startY=null)
{
$sizeSrc = $this->getImageSize($this->imgSrc);
if ( $startX === null ) {
$startX = ($sizeSrc[0] - $width)/2;
}
if ( $startY === null ) {
$startY = ($sizeSrc[1] - $height)/2;
}
$this->imgDst = imagecrop($this->imgDst,
['x' => $startX, 'y' => $startY, 'width' => $width, 'height' => $height]);
return $this;
} |
Generates the button dropdown.
@return string the rendering result. | protected function renderButton($dropdown) {
$dropdownId = $dropdown->getId();
$label = $this->label;
if ($this->encodeLabel) {
$label = Html::encode($label);
}
if ($this->split) {
$this->tagName = 'a';
Html::addCssClass($this->options, 'button');
Html::addCssClass($this->options, 'split');
$options = $this->options;
$label .= Html::tag('span', '', ['data-dropdown' => $dropdownId]);
} else {
Html::addCssClass($this->options, 'dropdown');
$options = $this->options;
$options['data-dropdown'] = $dropdownId;
}
return Button::widget([
'tagName' => $this->tagName,
'label' => $label,
'options' => $options,
'url' => $this->url,
'encodeLabel' => false,
]) . "<br />\n";
} |
// IsStrictSuperSet returns true if this is a strict superset of the other set | func (b *BitSet) IsStrictSuperSet(other *BitSet) bool {
return b.Count() > other.Count() && b.IsSuperSet(other)
} |
Raises an exception if the given app setting is not defined. | def require_setting(self, name: str, feature: str = "this feature") -> None:
""""""
if not self.application.settings.get(name):
raise Exception(
"You must define the '%s' setting in your "
"application to use %s" % (name, feature)
) |
Retry this factory's connection. It is assumed that a previous
connection was attempted and failed- either before or after a
successful connection. | def retry(self):
if self.connector is None:
raise ValueError("No connector to retry")
if self.service is None:
return
self.connector.connect() |
Find data with specified criteria
@param array $criteria
@return Norm\Cursor | public function find($criteria = array())
{
if (!is_array($criteria)) {
$criteria = array(
'$id' => $criteria,
);
}
// wrap criteria as NObject instance to make sure it can be override by hooks
$criteria = new NObject($criteria);
$this->applyHook('searching', $criteria);
$cursor = $this->connection->query($this, $criteria->toArray());
$this->applyHook('searched', $cursor);
return $cursor;
} |
Set gender.
@param \Innova\LexiconBundle\Entity\Gender $gender
@return Inflection | public function setGender(\Innova\LexiconBundle\Entity\Gender $gender = null)
{
$this->gender = $gender;
return $this;
} |
// SetValue sets the Value field's value. | func (s *HistoricalMetricData) SetValue(v float64) *HistoricalMetricData {
s.Value = &v
return s
} |
// SetCodeBuildServiceRole sets the CodeBuildServiceRole field's value. | func (s *BuildConfiguration) SetCodeBuildServiceRole(v string) *BuildConfiguration {
s.CodeBuildServiceRole = &v
return s
} |
Adds the panel's CSS and JavaScript to the <head>. | public function head()
{
global $event, $theme;
if ($event != 'rah_backup') {
return;
}
gTxtScript(array(
'rah_backup_confirm_backup',
));
$msg = array(
'backup' => escape_js($theme->announce_async(gTxt('rah_backup_taking'))),
'error' => escape_js($theme->announce_async(gTxt('rah_backup_task_error'))),
);
$js = <<<EOF
$(function ()
{
$('.rah_backup_take').on('click', function (e)
{
e.preventDefault();
var obj = $(this), href, spinner;
if (obj.hasClass('disabled') || !verify(textpattern.gTxt('rah_backup_confirm_backup'))) {
return false;
}
$.globalEval('{$msg['backup']}');
spinner = $('<span> <span class="spinner"></span> </span>');
href = obj.attr('href');
obj.addClass('disabled').attr('href', '#').after(spinner);
$.ajax('index.php', {
data: href.substr(1) + '&app_mode=async',
dataType: 'script',
timeout: 1800000
}).fail(function ()
{
$.globalEval('{$msg['error']}');
}).always(function ()
{
obj.removeClass('disabled').attr('href', href);
spinner.remove();
});
});
});
EOF;
echo script_js($js);
} |
Return the JSON string of the response cache. Leverage the Gson nature of
the domain wireline classes
@return the JSON string | public String asJSON() {
Gson gson = new Gson();
clearExpired();
Cache jsonCache = new Cache();
for (ExpiringService svc : cache.values()) {
jsonCache.cache.add(svc.getService());
}
String json = gson.toJson(jsonCache);
return json;
} |
Get the series' symbol in the legend. This method should be overridable to create custom
symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
@param {Object} legend The legend object | function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendOptions = legend.options,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
} |
<p>
User-supplied properties in key-value form.
</p>
@param parameters
User-supplied properties in key-value form.
@return Returns a reference to this object so that method calls can be chained together. | public StorageDescriptor withParameters(java.util.Map<String, String> parameters) {
setParameters(parameters);
return this;
} |
Determines whether or not a command definition has options.
@param array $commandDef The command definition as returned from {@link Cli::getSchema()}.
@return bool Returns true if the command def has options or false otherwise. | protected function hasOptionsDef($commandDef) {
return count($commandDef) > 1 || (count($commandDef) > 0 && !isset($commandDef[Cli::META]));
} |
/* Compile a link. | function link(node, href) {
var self = this
var value = 'children' in node ? self.all(node).join('') : node.alt
var url = escape(typeof href === 'string' ? href : node.url || '')
var head
if (url && url.slice(0, mailto.length) === mailto) {
url = url.slice(mailto.length)
}
head = url.charAt(0) === '#' && self.headings[url.slice(1)]
if (head) {
url = '(' + escape(toString(head)) + ')'
} else {
if (value && escape(url) === value) {
value = ''
}
if (url) {
url = '\\(la' + escape(url) + '\\(ra'
}
}
if (value) {
value = bold.call(self, value)
if (url) {
value += ' '
}
}
return value + (url ? italic.call(self, url) : '')
} |
// Reverse reverses the given byte slice. | func Reverse(a []byte) []byte {
for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {
a[left], a[right] = a[right], a[left]
}
return a
} |
{@inheritDoc} check if given string is a not empty after strip.
@see javax.validation.ConstraintValidator#isValid(java.lang.Object,
javax.validation.ConstraintValidatorContext) | @Override
public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) {
final String valueAsString = StringUtils.strip(Objects.toString(pvalue, null), stripcharacters);
return StringUtils.isNotEmpty(valueAsString);
} |
Load a system from the remote location specified by *url*.
**Example**
::
load_remote_system('https://raw.github.com/chemlab/chemlab-testdata/master/naclwater.gro') | def load_remote_system(url, format=None):
'''
'''
filename, headers = urlretrieve(url)
return load_system(filename, format=format) |
Checks if the file is a MKA.
@return boolean|null | protected function leadMKA()
{
$lead = $this->ffprobeFormat("matroska", "webm");
if ($lead === true)
{
if ($this->ffprobeHasAudio() !== false)
{
return $this->closeCase("mka", "audio/x-matroska", $this->metadata);
}
else
{
return false;
}
}
return null;
} |
Main init method | public function init()
{
$host =getenv('PDO_HOST');
if($host) {
$this->setHost(trim($host));
}
$database = getenv('PDO_DATABASE');
if($database) {
$this->setDatabase(trim($database));
}
$user = getenv('PDO_USER');
if($user) {
$this->setUser($user);
}
$password = getenv('PDO_PASSWORD');
if($password) {
$this->setPassword($password);
}
} |
Populate with thanks | private void populateStep4() {
this.insertRoadmapItem(3, true, I18nLabelsLoader.REPORT_STEP_THANKS, 4);
int y = 6;
// thanks
this.insertFixedTextBold(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_THANKS, I18nLabelsLoader.REPORT_STEP_THANKS);
y += 12; // plus one line
// thanks msg
this.insertMultilineFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, 8*5, STEP_THANKS, I18nLabelsLoader.ADDON_THANKS_MESSAGE);
y += 8*5 + 12; // plus 15 lines
// status
this.insertFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_THANKS, I18nLabelsLoader.ADDON_THANKS_STATUS);
this.thanksStatusLabel = this.insertHiddenFixedStatusText(this, DEFAULT_PosX + 40, y, DEFAULT_WIDTH_LARGE, STEP_THANKS, I18nLabelsLoader.ADDON_THANKS_STATUS, false);
y += 12;
// link
this.thanksReportLink = this.insertFixedHyperlink(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_THANKS, I18nLabelsLoader.ADDON_THANKS_LINK, Resources.getProperty("COMMUNITY_ROOT") + "/reports");
this.thanksProgressBar = this.insertProgressBar(DEFAULT_PosX, DEFAULT_DIALOG_HEIGHT - 26 - 8, DEFAULT_WIDTH_LARGE, STEP_THANKS, 100);
} |
Get the listener options for the command.
@return \Illuminate\Queue\ListenerOptions | protected function gatherOptions()
{
return new ListenerOptions(
$this->option('env'), $this->option('delay'),
$this->option('memory'), $this->option('timeout'),
$this->option('sleep'), $this->option('tries'),
$this->option('force')
);
} |