comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Creates a new object
@param array $aData The data to create the object with
@param bool $bReturnObject Whether to return just the new ID or the full object
@return bool|mixed
@throws FactoryException | public function create(array $aData = [], $bReturnObject = false)
{
$oDb = Factory::service('Database');
try {
if (empty($aData['customer_id']) && empty($aData['email'])) {
throw new InvoiceException('Either "customer_id" or "email" field must be supplied.', 1);
}
$oDb->trans_begin();
$this->prepareInvoice($aData);
if (empty($aData['ref'])) {
$aData['ref'] = $this->generateValidRef();
}
$aData['token'] = $this->generateToken();
$aItems = $aData['items'];
unset($aData['items']);
$oInvoice = parent::create($aData, true);
if (!$oInvoice) {
throw new InvoiceException('Failed to create invoice.', 1);
}
if (!empty($aItems)) {
$this->updateLineItems($oInvoice->id, $aItems);
}
$oDb->trans_commit();
$this->triggerEvent(
Events::INVOICE_CREATED,
[$this->getInvoiceForEvent($oInvoice->id)]
);
return $bReturnObject ? $oInvoice : $oInvoice->id;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} |
Load by product id.
@param int $productId
@return \Dotdigitalgroup\Email\Model\Catalog | public function loadProductById($productId)
{
$collection = $this->catalogCollection->create()
->addFieldToFilter('product_id', $productId)
->setPageSize(1);
return $collection->getFirstItem();
} |
Program entry point. | def main(opts):
""""""
term = Terminal()
style = Style()
# if the terminal supports colors, use a Style instance with some
# standout colors (magenta, cyan).
if term.number_of_colors:
style = Style(attr_major=term.magenta,
attr_minor=term.bright_cyan,
alignment=opts['--alignment'])
style.name_len = term.width - 15
screen = Screen(term, style, wide=opts['--wide'])
pager = Pager(term, screen, opts['character_factory'])
with term.location(), term.cbreak(), \
term.fullscreen(), term.hidden_cursor():
pager.run(writer=echo, reader=term.inkey)
return 0 |
Merge an entire map into the current map.
@param array $values
@return void | public function mergeAll(array $values)
{
foreach ($values as $key => $value) {
$this->merge($key, $value);
}
} |
Rerun last example code block with specified version of python. | def rerun(version="3.7.0"):
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).run() |
Select the first shape created which contains this point. | def selectShapePoint(self, point):
""""""
self.deSelectShape()
if self.selectedVertex(): # A vertex is marked for selection.
index, shape = self.hVertex, self.hShape
shape.highlightVertex(index, shape.MOVE_VERTEX)
self.selectShape(shape)
return
for shape in reversed(self.shapes):
if self.isVisible(shape) and shape.containsPoint(point):
self.selectShape(shape)
self.calculateOffsets(shape, point)
return |
return encoded representation | def binary(self):
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PID_EXT) +
self.node.binary() + self.id + self.serial + self.creation
)
elif creation_size == 4:
return (
b_chr(_TAG_NEW_PID_EXT) +
self.node.binary() + self.id + self.serial + self.creation
)
else:
raise OutputException('unknown pid type') |
// Index is the name of the index to open. | func (s *OpenIndexService) Index(index string) *OpenIndexService {
s.index = index
return s
} |
Convert this selector to a DataStream.
This function will only work if this is a singular selector that
matches exactly one DataStream. | def as_stream(self):
if not self.singular:
raise ArgumentError("Attempted to convert a non-singular selector to a data stream, it matches multiple", selector=self)
return DataStream(self.match_type, self.match_id, self.match_spec == DataStreamSelector.MatchSystemOnly) |
// DescribeVRouters describes Virtual Routers
//
// You can read doc at http://docs.aliyun.com/#/pub/ecs/open-api/vrouter&describevrouters | func (client *Client) DescribeVRouters(args *DescribeVRoutersArgs) (vrouters []VRouterSetType, pagination *common.PaginationResult, err error) {
response, err := client.DescribeVRoutersWithRaw(args)
if err == nil {
return response.VRouters.VRouter, &response.PaginationResult, nil
}
return nil, nil, err
} |
This function is used to read from a raw Bitcoin block some identifier. Note: Does not change ByteBuffer position
@param rawByteBuffer ByteBuffer as read by readRawBlock
@return byte array containing hashMerkleRoot and prevHashBlock | public byte[] getKeyFromRawBlock (ByteBuffer rawByteBuffer) {
rawByteBuffer.mark();
byte[] magicNo=new byte[4];
byte[] hashMerkleRoot=new byte[32];
byte[] hashPrevBlock=new byte[32];
// magic no (skip)
rawByteBuffer.get(magicNo,0,4);
// blocksize (skip)
rawByteBuffer.getInt();
// version (skip)
rawByteBuffer.getInt();
// hashPrevBlock
rawByteBuffer.get(hashPrevBlock,0,32);
// hashMerkleRoot
rawByteBuffer.get(hashMerkleRoot,0,32);
byte[] result=new byte[hashMerkleRoot.length+hashPrevBlock.length];
for (int i=0;i<hashMerkleRoot.length;i++) {
result[i]=hashMerkleRoot[i];
}
for (int j=0;j<hashPrevBlock.length;j++) {
result[j+hashMerkleRoot.length]=hashPrevBlock[j];
}
rawByteBuffer.reset();
return result;
} |
Used to set up the cache within the SESSION.
This is called for each access and ensure that we don't put anything into the session before
it is required. | protected function ensure_session_cache_initialised() {
global $SESSION;
if (empty($this->session)) {
if (!isset($SESSION->navcache)) {
$SESSION->navcache = new stdClass;
}
if (!isset($SESSION->navcache->{$this->area})) {
$SESSION->navcache->{$this->area} = array();
}
$this->session = &$SESSION->navcache->{$this->area}; // pointer to array, =& is correct here
}
} |
Print an entire status line including bar and stats. | def _print_status(self):
''''''
self._clear_line()
self._print(' ')
if self.max_value:
self._print_percent()
self._print(' ')
self._print_bar()
else:
self._print_throbber()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_size_downloaded()
else:
self._print(self.current_value)
self._print(' ')
self._print_duration()
self._print(' ')
if self.measurement == Measurement.bytes:
self._print_speed()
self._flush() |
Converts properties to a String-String map
@param props Properties
@return String-String map of properties | public static Map<String, String> fromProperties(final Properties props) {
Map<String, String> propMap = new HashMap<String, String>();
for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
propMap.put(key, props.getProperty(key));
}
return Collections.unmodifiableMap(propMap);
} |
Create a custom trust manager which will prompt for trust acceptance.
@return | private X509TrustManager createPromptingTrustManager() {
TrustManager[] trustManagers = null;
try {
String defaultAlg = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlg);
tmf.init((KeyStore) null);
trustManagers = tmf.getTrustManagers();
} catch (KeyStoreException e) {
// Unable to initialize the default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
} catch (NoSuchAlgorithmException e) {
// Unable to get default trust managers.
// This is not a problem as PromptX509rustManager can handle null.
}
boolean autoAccept = Boolean.valueOf(System.getProperty(SYS_PROP_AUTO_ACCEPT, "false"));
return new PromptX509TrustManager(stdin, stdout, trustManagers, autoAccept);
} |
Clears all the collected data | function clear()
{
$index['index'] = $this->config->index;
$index['type'] = $this->config->type;
$index['body']['query']['bool']['must']= [
['match_phrase'=>[ '__meta.sid'=>$this->sid, ]]
];
$this->client->deleteByQuery($index);
} |
Find common give names of males.
@param int $threshold
@param int $maxtoshow
@return string | public function commonGivenMaleTotals(int $threshold = 1, int $maxtoshow = 10): string
{
return $this->commonGivenQuery('M', 'nolist', true, $threshold, $maxtoshow);
} |
Adds multiple handlers for node.
@param {Node|Window|string} node
@param {object} handlers
@param {object=} thisObject Context for handlers | function addHandlers(node, handlers, thisObject){
node = getNode(node);
for (var eventType in handlers)
addHandler(node, eventType, handlers[eventType], thisObject);
} |
buildExpression
@param string $name
@return mixed|QueryElement | public function buildExpression($name)
{
$args = func_get_args();
array_shift($args);
if (is_callable([$this, $name])) {
return call_user_func_array([$this, $name], $args);
}
return (string) strtoupper($name) . '(' . implode(', ', $args) . ')';
} |
// SetReservationId sets the ReservationId field's value. | func (s *DeleteReservationOutput) SetReservationId(v string) *DeleteReservationOutput {
s.ReservationId = &v
return s
} |
Removes a triple from the store. | def remove(self, (s, p, o), context=None):
named_graph = _get_named_graph(context)
query_sets = _get_query_sets_for_object(o)
filter_parameters = dict()
if named_graph is not None:
filter_parameters['context_id'] = named_graph.id
if s:
filter_parameters['subject'] = s
if p:
filter_parameters['predicate'] = p
if o:
filter_parameters['object'] = o
query_sets = [qs.filter(**filter_parameters) for qs in query_sets] # pylint: disable=W0142
for qs in query_sets:
qs.delete() |
Add some transforms. | def add_on_cpu(self, transforms):
""""""
if not isinstance(transforms, list):
transforms = [transforms]
self.cpu_transforms.extend(transforms or [])
return self |
/*
(non-Javadoc)
@see
org.fcrepo.kernel.api.services.RepositoryService#restoreRepository(javax.
jcr.Session, java.io.File) | @Override
public Collection<Throwable> restoreRepository(final FedoraSession session,
final File backupDirectory) {
final Session jcrSession = getJcrSession(session);
try {
final RepositoryManager repoMgr = ((org.modeshape.jcr.api.Session) jcrSession)
.getWorkspace()
.getRepositoryManager();
final Collection<Throwable> problems = new ArrayList<>();
repoMgr.restoreRepository(backupDirectory).forEach(x -> problems.add(x.getThrowable()));
return problems;
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
} |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | public EClass getIfcRelAssociatesMaterial() {
if (ifcRelAssociatesMaterialEClass == null) {
ifcRelAssociatesMaterialEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
.getEClassifiers().get(454);
}
return ifcRelAssociatesMaterialEClass;
} |
Create a new {@link Client} instance with the given name and groups.
You own the returned client and are responsible for managing its cleanup. | public Client newClient(String clientName, JaxRsFeatureGroup feature, JaxRsFeatureGroup... moreFeatures) {
return newBuilder(clientName, feature, moreFeatures).build();
} |
Parse command line arguments and return options
@param [Array<String>] argv the command lines arguments
@return [Hash] the command line options | def parse_options(argv:)
input_path = nil
benchmark_time = 30
benchmark_warmup = 5
lines_multipliers = [1]
verbose = false
OptionParser.new do |parser|
parser.banner = 'Usage: bin/benchmark [file.csv] [options]'
parser.default_argv = argv
parser.on('--csv=[file1.csv]', String, 'CSV file(s)') do |value|
input_path = value
end
parser.on('--[no-]verbose', 'Verbose output') do |value|
verbose = value
end
parser.on('--lines-multipliers=[1,10,50]', Array, 'Multiply the rows in the CSV file (default: 1)') do |value|
lines_multipliers = value.map do |v|
Integer(v).tap do |int|
unless int >= 1
raise(ArgumentError, '--lines-multiplier must be 1 or greater')
end
end
end
end
parser.on('--time=[30]', String, 'Benchmark time (default: 30)') do |value|
benchmark_time = Integer(value)
end
parser.on('--warmup=[30]', String, 'Benchmark warmup (default: 30)') do |value|
benchmark_warmup = Integer(value)
end
parser.on('-h', '--help', 'How to use') do
puts parser
exit
end
# No argument, shows at tail. This will print an options summary.
parser.on_tail('-h', '--help', 'Show this message') do
puts parser
exit
end
end.parse!
{
input_path: input_path,
benchmark_time: benchmark_time,
benchmark_warmup: benchmark_warmup,
lines_multipliers: lines_multipliers,
verbose: verbose,
}
end |
// SetServiceRole sets the ServiceRole field's value. | func (s *Project) SetServiceRole(v string) *Project {
s.ServiceRole = &v
return s
} |
Checks if small elements in a container page should be initially editable.<p>
@param request the current request
@param cms the current CMS context
@return true if small elements should be initially editable | private boolean isEditSmallElements(HttpServletRequest request, CmsObject cms) {
CmsUser user = cms.getRequestContext().getCurrentUser();
String editSmallElementsStr = (String)(user.getAdditionalInfo().get(ADDINFO_EDIT_SMALL_ELEMENTS));
if (editSmallElementsStr == null) {
return true;
} else {
return Boolean.valueOf(editSmallElementsStr).booleanValue();
}
} |
Saves execution state to `self._metadata_checkpoint_dir`.
Overwrites the current session checkpoint, which starts when self
is instantiated. | def checkpoint(self):
if not self._metadata_checkpoint_dir:
return
metadata_checkpoint_dir = self._metadata_checkpoint_dir
if not os.path.exists(metadata_checkpoint_dir):
os.makedirs(metadata_checkpoint_dir)
runner_state = {
"checkpoints": list(
self.trial_executor.get_checkpoints().values()),
"runner_data": self.__getstate__(),
"timestamp": time.time()
}
tmp_file_name = os.path.join(metadata_checkpoint_dir,
".tmp_checkpoint")
with open(tmp_file_name, "w") as f:
json.dump(runner_state, f, indent=2, cls=_TuneFunctionEncoder)
os.rename(
tmp_file_name,
os.path.join(metadata_checkpoint_dir,
TrialRunner.CKPT_FILE_TMPL.format(self._session_str)))
return metadata_checkpoint_dir |
Handle a reconnect. | def _reconnect_handler(self):
""""""
for channel_name, channel in self.channels.items():
data = {'channel': channel_name}
if channel.auth:
data['auth'] = channel.auth
self.connection.send_event('pusher:subscribe', data) |
Get the arguments for the requested URI.
@param string $uri
@param string $routeUri
@return array|null | private function getArguments(string $uri, string $routeUri): ?array
{
if (preg_match_all('/({[a-z]+:)/i', $routeUri, $matches)) {
$regex = str_replace('/', '\/',
str_replace('}', ')',
preg_replace('/{([a-z]+):/i', '(?<$1>', $routeUri)
)
);
return $this->matchUri($regex, $uri);
}
return null;
} |
Saves the state for this item to the scaffold. | def save(self):
enabled = self.checkState(0) == QtCore.Qt.Checked
self._element.set('name', nativestring(self.text(0)))
self._element.set('enabled', nativestring(enabled))
for child in self.children():
child.save() |
triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable | function ajaxBeforeSend(xhr, settings) {
var context = settings.context;
if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [
xhr,
settings
]) === false)
return false;
triggerGlobal(settings, context, 'ajaxSend', [
xhr,
settings
]);
} |
@param Request $request
@param Response $response
@return Response | public function run(Request $request, Response $response)
{
$this->initController($request, $response);
$event = $this->eventDispatcher->raiseEvent(
$this->createLoadedEvent()
);
if ($event->isHandled() && $event->getResponse() instanceof Response) {
return $event->getResponse();
}
$this->eventDispatcher->raiseEvent(
$this->createFinishedEvent(
$this->runController($request, $response)
)
);
return $response;
} |
Used to mark a method on a ResourceBinding that should be routed for list actions. | def list_action(**kwargs):
def decorator(func):
func.action = True
func.detail = False
func.kwargs = kwargs
return func
return decorator |
Run the database seeds.
@return void | public function run()
{
foreach (['super', 'admin', 'banned', 'author', 'registered'] as $role) {
if (DB::table('roles')->where(compact('role'))->first()) {
continue;
}
DB::table('roles')->insert(compact('role'));
}
} |
Gets the content of this <CODE>Annotation</CODE>.
@return a reference | public String content() {
String s = (String) annotationAttributes.get(CONTENT);
if (s == null)
s = "";
return s;
} |
Add the modules of the given package without their members. | def add_modules(self, package):
""""""
for name in os.listdir(package.__path__[0]):
if name.startswith('_'):
continue
name = name.split('.')[0]
short = '|%s|' % name
long = ':mod:`~%s.%s`' % (package.__package__, name)
self._short2long[short] = long |
// Warningf logs a warning if not throttled. | func (tl *ThrottledLogger) Warningf(format string, v ...interface{}) {
tl.log(warningDepth, format, v...)
} |
Obtains the theme, which should be used by the preference's dialog, from a specific typed
array.
@param typedArray
The typed array, the theme should be obtained from, as an instance of the class
{@link TypedArray}. The typed array may not be null | private void obtainDialogTheme(@NonNull final TypedArray typedArray) {
int themeId = typedArray.getResourceId(R.styleable.DialogPreference_dialogThemeResource, 0);
if (themeId == 0) {
TypedValue typedValue = new TypedValue();
getContext().getTheme()
.resolveAttribute(R.attr.preferenceDialogTheme, typedValue, true);
themeId = typedValue.resourceId;
}
dialogTheme = themeId != 0 ? themeId : R.style.MaterialDialog_Light;
} |
Builds Proxy parameters Dict from
client options. | def _proxy_parameters(self):
proxy_protocol = ''
if self.proxy_host.startswith('https'):
proxy_protocol = 'https'
else:
proxy_protocol = 'http'
proxy = '{0}://'.format(proxy_protocol)
if self.proxy_username and self.proxy_password:
proxy += '{0}:{1}@'.format(self.proxy_username, self.proxy_password)
proxy += sub(r'https?(://)?', '', self.proxy_host)
if self.proxy_port:
proxy += ':{0}'.format(self.proxy_port)
return {
'http': proxy,
'https': proxy
} |
Deletes this model instance from the database.
@return bool | protected function delete_self()
{
// Create the query and limit to primary key(s)
$query = Query::forge(get_called_class(), static::connection(true))->limit(1);
$primary_key = static::primary_key();
foreach ($primary_key as $pk)
{
$query->where($pk, '=', $this->{$pk});
}
// Return success of update operation
return $query->delete();
} |
Parse the XML from Monit into a hash and into a Ruby representation. | def parse(xml)
@hash = Hash.from_xml(xml)
@server = Server.new(@hash["monit"]["server"])
@platform = Platform.new(@hash["monit"]["platform"])
options = {
:host => @host,
:port => @port,
:ssl => @ssl,
:auth => @auth,
:username => @username,
:password => @password
}
if @hash["monit"]["service"].is_a? Array
@services = @hash["monit"]["service"].map do |service|
Service.new(service, options)
end
else
@services = [Service.new(@hash["monit"]["service"], options)]
end
true
rescue
false
end |
postpone writing initialization since we can do only reading so there's no need to allocate buffers | private void lazyInitWriting() {
if (!writeInitialized) {
this.writeInitialized = true;
this.bulkProcessor = new BulkProcessor(client, resources.getResourceWrite(), settings);
this.trivialBytesRef = new BytesRef();
this.bulkEntryWriter = new BulkEntryWriter(settings, BulkCommands.create(settings, metaExtractor, client.clusterInfo.getMajorVersion()));
}
} |
Write the contents of the reflog instance to a file at the given filepath.
:param filepath: path to file, parent directories are assumed to exist | def to_file(self, filepath):
""""""
lfd = LockedFD(filepath)
assure_directory_exists(filepath, is_file=True)
fp = lfd.open(write=True, stream=True)
try:
self._serialize(fp)
lfd.commit()
except Exception:
# on failure it rolls back automatically, but we make it clear
lfd.rollback()
raise |
Factory method
@param string $repositoryPath the path of the git repository
@param string|null $binary the path to the git binary
@param string $name a repository name
@return \GitElephant\Repository | public static function open($repositoryPath, string $binary = null, $name = null)
{
return new self($repositoryPath, $binary, $name);
} |
Fisher–Yates shuffle
@param ar | public static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
} |
Set the header that defines which sources are allowed to embed the pages.
@return void | public function setFrameAncestorsHeader()
{
/** @var SettingsStorage $settingsStorage */
$settingsStorage = $this->getServiceLocator()->get(SettingsStorage::SERVICE_ID);
$whitelistedSources = $settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_SETTING);
if ($whitelistedSources === null) {
$whitelistedSources = ["'none'"];
}
// Wrap directives in quotes
if (in_array($whitelistedSources, ['self', 'none'])) {
$whitelistedSources = ["'" . $whitelistedSources . "'"];
}
if ($whitelistedSources === 'list') {
$whitelistedSources = json_decode($settingsStorage->get(CspHeaderSettingsInterface::CSP_HEADER_LIST), true);
}
if (!is_array($whitelistedSources)) {
$whitelistedSources = [$whitelistedSources];
}
header(sprintf(
'Content-Security-Policy: frame-ancestors %s',
implode(' ', $whitelistedSources)
));
} |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | public void setXpgBase(Integer newXpgBase) {
Integer oldXpgBase = xpgBase;
xpgBase = newXpgBase;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.PGD__XPG_BASE, oldXpgBase, xpgBase));
} |
Get all comments of offer
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param offer_id: the offer id
:return: list | def get_all_comments_of_offer(self, offer_id):
return self._iterate_through_pages(
get_function=self.get_comments_of_offer_per_page,
resource=OFFER_COMMENTS,
**{'offer_id': offer_id}
) |
set center of view | def set_center(self, lat, lon):
''''''
self.object_queue.put(SlipCenter((lat,lon))) |
Compute Doc object for file text.
@param {String} text File text
@param {String} type File type
@returns {dox.JSDoc|dox.MDDoc} | function ( text, type ) {
switch ( type ) {
case "js" :
return new dox.JSDoc ({
title : document.title,
chapters : this._chapters ( text )
});
case "md" :
return new dox.MDDoc ({
title : document.title,
markup : this._markup ( text )
});
}
} |
Entry point for the `simpl` command. | def main(argv=None):
""""""
#
# `simpl server`
#
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
# the following code shouldn't need to change when
# we add a new subcommand.
args = default_parser().parse_args(argv)
args._func() |
A non-terminating assertion for an element on a page.
Failures will be saved until the process_delayed_asserts()
method is called from inside a test, likely at the end of it. | def delayed_assert_element(self, selector, by=By.CSS_SELECTOR,
timeout=settings.MINI_TIMEOUT):
self.__delayed_assert_count += 1
try:
url = self.get_current_url()
if url == self.__last_url_of_delayed_assert:
timeout = 1
else:
self.__last_url_of_delayed_assert = url
except Exception:
pass
try:
self.wait_for_element_visible(selector, by=by, timeout=timeout)
return True
except Exception:
self.__add_delayed_assert_failure()
return False |
::
<!ELEMENT PARAMETER.ARRAY (QUALIFIER*)>
<!ATTLIST PARAMETER.ARRAY
%CIMName;
%CIMType; #REQUIRED
%ArraySize;> | def parse_parameter_array(self, tup_tree):
self.check_node(tup_tree, 'PARAMETER.ARRAY', ('NAME', 'TYPE'),
('ARRAYSIZE',), ('QUALIFIER',))
attrl = attrs(tup_tree)
array_size = attrl.get('ARRAYSIZE', None)
if array_size is not None:
# Issue #1044: Clarify if hex support is needed
array_size = int(array_size)
qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',))
return CIMParameter(attrl['NAME'],
type=attrl['TYPE'],
is_array=True,
array_size=array_size,
qualifiers=qualifiers,
embedded_object=False) |
@param ChannelInterface $channel
@return bool | public function addChannel(ChannelInterface $channel): bool
{
if (!$this->getChannels()->contains($channel)) {
$this->channels->add($channel);
}
return true;
} |
Revengeful arguments validator.
Throws an exception if no match. | function(/* ...types */) {
var types = gui.Array.from(arguments);
return function(action) {
return function() {
if (gui.Arguments._validate(arguments, types)) {
return action.apply(this, arguments);
} else {
gui.Arguments._abort(this);
}
};
};
} |
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist. | def generateImplicitParameters(cls, obj):
for comp in obj.components():
if comp.behavior is not None:
comp.behavior.generateImplicitParameters(comp)
if not hasattr(obj, 'prodid'):
obj.add(ContentLine('PRODID', [], PRODID))
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION', [], cls.versionString))
tzidsUsed = {}
def findTzids(obj, table):
if isinstance(obj, ContentLine) and (obj.behavior is None or
not obj.behavior.forceUTC):
if getattr(obj, 'tzid_param', None):
table[obj.tzid_param] = 1
else:
if type(obj.value) == list:
for item in obj.value:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
else:
tzinfo = getattr(obj.value, 'tzinfo', None)
tzid = TimezoneComponent.registerTzinfo(tzinfo)
if tzid:
table[tzid] = 1
for child in obj.getChildren():
if obj.name != 'VTIMEZONE':
findTzids(child, table)
findTzids(obj, tzidsUsed)
oldtzids = [toUnicode(x.tzid.value) for x in getattr(obj, 'vtimezone_list', [])]
for tzid in tzidsUsed.keys():
tzid = toUnicode(tzid)
if tzid != u'UTC' and tzid not in oldtzids:
obj.add(TimezoneComponent(tzinfo=getTzid(tzid))) |
Evaluates the attribute value and assigns it to the current attributes.
@param Event $event | public function evaluateAttributes($event)
{
if ($this->skipUpdateOnClean
&& $event->name == ActiveRecordSaveEvent::BEFORE_UPDATE
&& empty($this->owner->dirtyAttributes)
) {
return;
}
if (!empty($this->attributes[$event->name])) {
$attributes = (array) $this->attributes[$event->name];
$value = $this->getValue($event);
foreach ($attributes as $attribute) {
// ignore attribute names which are not string (e.g. when set by TimestampBehavior::updatedAtAttribute)
if (is_string($attribute)) {
if ($this->preserveNonEmptyValues && !empty($this->owner->$attribute)) {
continue;
}
$this->owner->$attribute = $value;
}
}
}
} |
Set all the necessary header settings
@author Markus Schober | protected function headerSettings()
{
$this->setPrintHeader(
Config::get('laravel-tcpdf::header_on')
);
$this->setHeaderFont(array(
Config::get('laravel-tcpdf::header_font'),
'',
Config::get('laravel-tcpdf::header_font_size')
));
$this->setHeaderMargin(
Config::get('laravel-tcpdf::header_margin')
);
$this->SetHeaderData(
Config::get('laravel-tcpdf::header_logo'),
Config::get('laravel-tcpdf::header_logo_width'),
Config::get('laravel-tcpdf::header_title'),
Config::get('laravel-tcpdf::header_string')
);
} |
// GetContainerIDs returns all the container ids in the system, panics when error occurs | func (d *DockerHelper) GetContainerIDs() []string {
containerIDs := []string{}
containers, err := d.client.ContainerList(getContext(), types.ContainerListOptions{All: true})
if err != nil {
panic(fmt.Sprintf("Error list containers: %v", err))
}
for _, container := range containers {
containerIDs = append(containerIDs, container.ID)
}
return containerIDs
} |
Prints a solution
Arguments
---------
solution : BaseSolution
Example
-------
::
[8, 9, 10, 7]: 160
[5, 6]: 131
[3, 4, 2]: 154
Total cost: 445 | def print_solution(solution):
total_cost = 0
for solution in solution.routes():
cost = solution.length()
total_cost = total_cost + cost
print('{}: {}'.format(solution, cost))
#print('xxx')
print('Total cost: {}'.format(total_cost)) |
Project a relative data vector from data space to scaled space.
@param data relative vector in data space
@return relative vector in scaled space | @Override
public double[] projectRelativeDataToScaledSpace(double[] data) {
final int dim = data.length;
double[] dst = new double[dim];
for(int d = 0; d < dim; d++) {
dst[d] = scales[d].getRelativeScaled(data[d]);
}
return dst;
} |
Adds a new column (new_label) to the dataframe with the fraction correct computed over X and Y values. | def add_fraction_correct_values_to_dataframe(dataframe, x_series, y_series, new_label, x_cutoff = 1.0, y_cutoff = 1.0, ignore_null_values = False):
''''''
new_series_values = fraction_correct_values(dataframe.index.values.tolist(), dataframe[x_series].values.tolist(), dataframe[y_series].values.tolist(), x_cutoff = x_cutoff, y_cutoff = y_cutoff, ignore_null_values = ignore_null_values)
if new_label in dataframe.columns.values:
del dataframe[new_label]
dataframe.insert(len(dataframe.columns), new_label, new_series_values) |
If the object is not a Class, get its Class. Otherwise get the object as a Class. If the
class is anonymous, get a non-anonymous enclosing class.
@since 4.0.0 | public static Class<?> getNamedClass(Object obj) {
Class<?> cls = getClass(obj);
while (cls != null && cls.isAnonymousClass()) {
cls = cls.getEnclosingClass();
}
return cls;
} |
Get list of all asset files.
@return AssetFile[] | public function getAssetFileList()
{
$propertyList = $this->_getEntityList('Files');
$result = [];
foreach ($propertyList as $properties) {
$result[] = AssetFile::createFromOptions($properties);
}
return $result;
} |
Creates the automata.
@param prefix the prefix
@param regexp the regexp
@param automatonMap the automaton map
@return the list
@throws IOException Signals that an I/O exception has occurred. | public static List<CompiledAutomaton> createAutomata(String prefix,
String regexp, Map<String, Automaton> automatonMap) throws IOException {
List<CompiledAutomaton> list = new ArrayList<>();
Automaton automatonRegexp = null;
if (regexp != null) {
RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + "\u0000*");
automatonRegexp = re.toAutomaton();
}
int step = 500;
List<String> keyList = new ArrayList<>(automatonMap.keySet());
for (int i = 0; i < keyList.size(); i += step) {
int localStep = step;
boolean success = false;
CompiledAutomaton compiledAutomaton = null;
while (!success) {
success = true;
int next = Math.min(keyList.size(), i + localStep);
List<Automaton> listAutomaton = new ArrayList<>();
for (int j = i; j < next; j++) {
listAutomaton.add(automatonMap.get(keyList.get(j)));
}
Automaton automatonList = Operations.union(listAutomaton);
Automaton automaton;
if (automatonRegexp != null) {
automaton = Operations.intersection(automatonList, automatonRegexp);
} else {
automaton = automatonList;
}
try {
compiledAutomaton = new CompiledAutomaton(automaton);
} catch (TooComplexToDeterminizeException e) {
log.debug(e);
success = false;
if (localStep > 1) {
localStep /= 2;
} else {
throw new IOException("TooComplexToDeterminizeException");
}
}
}
list.add(compiledAutomaton);
}
return list;
} |
Find persistence units.
@param url
the url
@param defaultTransactionType
the default transaction type
@return the list
@throws Exception
the exception | public static List<PersistenceUnitMetadata> findPersistenceUnits(final URL url, final String[] persistenceUnits,
PersistenceUnitTransactionType defaultTransactionType) throws InvalidConfigurationException
{
Document doc;
try
{
doc = getDocument(url);
}
catch (InvalidConfigurationException e)
{
throw e;
}
doc.getXmlVersion();
Element top = doc.getDocumentElement();
String versionName = top.getAttribute("version");
NodeList children = top.getChildNodes();
ArrayList<PersistenceUnitMetadata> units = new ArrayList<PersistenceUnitMetadata>();
// parse for persistenceUnitRootInfoURL.
for (int i = 0; i < children.getLength(); i++)
{
if (children.item(i).getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) children.item(i);
String tag = element.getTagName();
// look for "persistence-unit" element
if (tag.equals("persistence-unit"))
{
PersistenceUnitMetadata metadata = parsePersistenceUnit(url, persistenceUnits, element, versionName);
if (metadata != null)
{
units.add(metadata);
}
}
}
}
return units;
} |
Check if there are blanks in the id field
:param netCDF4.Dataset ds: An open netCDF dataset | def check_id_has_no_blanks(self, ds):
'''
'''
if not hasattr(ds, u'id'):
return
if ' ' in getattr(ds, u'id'):
return Result(BaseCheck.MEDIUM, False, 'no_blanks_in_id',
msgs=[u'There should be no blanks in the id field'])
else:
return Result(BaseCheck.MEDIUM, True, 'no_blanks_in_id', msgs=[]) |
Disassembles a class file, sending the results to standard out.
<pre>
DisassemblyTool [-f <format style>] <file or class name>
</pre>
The format style may be "assembly" (the default) or "builder". | public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("DisassemblyTool [-f <format style>] <file or class name>");
System.out.println();
System.out.println("The format style may be \"assembly\" (the default) or \"builder\"");
return;
}
String style;
String name;
if ("-f".equals(args[0])) {
style = args[1];
name = args[2];
} else {
style = "assembly";
name = args[0];
}
ClassFileDataLoader loader;
InputStream in;
try {
final File file = new File(name);
in = new FileInputStream(file);
loader = new ClassFileDataLoader() {
public InputStream getClassData(String name)
throws IOException
{
name = name.substring(name.lastIndexOf('.') + 1);
File f = new File(file.getParentFile(), name + ".class");
if (f.exists()) {
return new FileInputStream(f);
}
return null;
}
};
} catch (FileNotFoundException e) {
if (name.endsWith(".class")) {
System.err.println(e);
return;
}
loader = new ResourceClassFileDataLoader();
in = loader.getClassData(name);
if (in == null) {
System.err.println(e);
return;
}
}
in = new BufferedInputStream(in);
ClassFile cf = ClassFile.readFrom(in, loader, null);
PrintWriter out = new PrintWriter(System.out);
Printer p;
if (style == null || style.equals("assembly")) {
p = new AssemblyStylePrinter();
} else if (style.equals("builder")) {
p = new BuilderStylePrinter();
} else {
System.err.println("Unknown format style: " + style);
return;
}
p.disassemble(cf, out);
out.flush();
} |
URL to core brand stats.
@since 160625 Brand URLs.
@param string $uri URI to append.
@return string Output URL. | public function toBrandCoreStats(string $uri = ''): string
{
if ($this->App->Parent) { // Looking for the root core.
return $this->App->Parent->Utils->§BrandUrl->toBrandCoreStats($uri);
}
return $this->toBrandStats($uri);
} |
Adds a secondary action to the action menu.
@param action_link|pix_icon|string $action | public function add_secondary_action($action) {
if ($action instanceof action_link || $action instanceof pix_icon) {
$action->attributes['role'] = 'menuitem';
if ($action instanceof action_menu_link) {
$action->actionmenu = $this;
}
}
$this->secondaryactions[] = $action;
} |
create a new migration file based on selected content elements
@param $data
@return bool | public function createContentMigration($data)
{
$manifest = [];
$migration = array(
'content' => array(),
);
$empty = true;
$plugin = MigrationManager::getInstance();
foreach ($this->_contentMigrationTypes as $key => $value) {
$service = $plugin->get($value);
if (array_key_exists($service->getSource(), $data)) {
$migration['content'][$service->getDestination()] = $service->export($data[$service->getSource()], true);
$empty = false;
if ($service->hasErrors()) {
$errors = $service->getErrors();
foreach ($errors as $error) {
Craft::error($error);
}
return false;
}
$manifest = array_merge($manifest, [$key => $service->getManifest()]);
}
}
if ($empty) {
$migration = null;
}
$this->createMigration($migration, $manifest);
return true;
} |
Setup the icinga2 node.
name
The domain name for which this certificate will be saved
master
Icinga2 master node for which this certificate will be saved
ticket
Authentication ticket generated on icinga2 master | def node_setup(name, master, ticket):
'''
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
cert = "{0}{1}.crt.orig".format(get_certs_path(), name)
key = "{0}{1}.key.orig".format(get_certs_path(), name)
# Checking if execution is needed.
if os.path.isfile(cert) and os.path.isfile(cert):
ret['comment'] = 'No execution needed. Node already configured.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Node setup will be executed.'
return ret
# Executing the command.
node_setup = __salt__['icinga2.node_setup'](name, master, ticket)
if not node_setup['retcode']:
ret['comment'] = "Node setup executed."
ret['changes']['cert'] = "Node setup finished successfully."
return ret
ret['comment'] = "FAILED. Node setup failed with outpu: {0}".format(node_setup['stdout'])
ret['result'] = False
return ret |
Get repository raw file
@param string $slug Repository slug
@param string $branch Repository branch
@param string $path File path
@return string | public function getRawFileUrl($slug, $branch, $path)
{
return sprintf(
'%s/%s/%s/%s',
$this->rawHost,
$slug,
$branch,
$path
);
} |
long型索引转换为int[]索引
@param idx
@return 索引 | public int[] getIndices(long idx)
{
int xIndices = (int)idx%this.size()[0];
int yIndices = (int)(idx-xIndices)/this.size()[0];
int []Indices = {xIndices,yIndices};
return Indices;
} |
(non-PHPdoc)
@see tao_helpers_form_elements_MultipleElement::getOptions() | public function getOptions() {
$options = parent::getOptions();
$statusProperty = new core_kernel_classes_Property(TaoOntology::PROPERTY_ABSTRACT_MODEL_STATUS);
$current = $this->getEvaluatedValue();
$options = array();
foreach (parent::getOptions() as $optUri => $optLabel) {
$model = new core_kernel_classes_Resource(tao_helpers_Uri::decode($optUri));
$status = $model->getOnePropertyValue($statusProperty);
if (!is_null($status)) {
$options[$optUri] = $optLabel;
} elseif ($model->getUri() == $current) {
$options[$optUri] = $optLabel.' ('.(is_null($status) ? __('unknown') : $status->getLabel()).')';
}
}
return $options;
} |
Loads translations from a url
@param string $url The translation url
@param bool $override If TRUE override previously loaded translations. Default FALSE.
@return bool TRUE if translations are loaded, FALSE otherwise | public function load($url, $override = false)
{
if (!$this->isLoaded($url))
{
$translations = array();
foreach ($this->find($url) as $file)
{
try {
$loaded = $this->getObject('object.config.factory')->fromFile($file)->toArray();
} catch (Exception $e) {
return false;
}
$translations = array_merge($translations, $loaded);
}
$this->getCatalogue()->add($translations, $override);
$this->setLoaded($url);
}
return true;
} |
Refresh Trees on Site Cache Clear ~
When enabled, will refresh the trees after clearing the site cache.
@param bool $value
@return $this | public function setCoreClearCacheRefreshTrees($value)
{
$this->setFieldName('clear_cache_refresh_trees');
$this->loadObject(true);
$this->setFieldValue($value);
return $this;
} |
Derive key from password, then format.
@param inputPassword The password to derive key from.
@return "salt:iteration-count:derived-key" (depends on effective formatter) | public String deriveKeyFormatted(String inputPassword) {
PBKDF2Parameters p = getParameters();
byte[] salt = generateSalt();
p.setSalt(salt);
p.setDerivedKey(deriveKey(inputPassword));
String formatted = getFormatter().toString(p);
return formatted;
} |
Runs the current wizard. | def runWizard( self ):
plugin = self.currentPlugin()
if ( plugin and plugin.runWizard(self) ):
self.accept() |
Gets the Canberra distance between two points.
@param x1 X1 axis coordinate.
@param y1 Y1 axis coordinate.
@param x2 X2 axis coordinate.
@param y2 Y2 axis coordinate.
@return The Canberra distance between x and y. | public static double Canberra(double x1, double y1, double x2, double y2) {
double distance;
distance = Math.abs(x1 - x2) / (Math.abs(x1) + Math.abs(x2));
distance += Math.abs(y1 - y2) / (Math.abs(y1) + Math.abs(y2));
return distance;
} |
Wait for SSH to be available at given IP address. | def wait_for_ssh(ip):
""""""
for _ in range(12):
with safe_socket() as s:
try:
s.connect((ip, 22))
return True
except socket.timeout:
pass
time.sleep(10)
return False |
// Closes the underlying connection. | func (c *streamClient) closeConn() {
conn := c.decoupleConn()
if conn != nil {
if err := conn.Close(); err != nil {
log.Fields{
log.ErrorKey: err,
}.Warningf(c, "Error on connection close.")
}
}
} |
// CreateMachine on digitalocean | func (p *Provider) CreateMachine() (machine *iaas.Machine, err error) {
err = p.Client.Create(p.Host)
if err != nil {
return
}
config, err := getConfig(p.Client.GetMachinesDir(), p.Name)
if err != nil {
return
}
machine = &iaas.Machine{
ID: config.Driver.InstanceID,
IP: config.Driver.IPAddress,
Image: config.Driver.AMI,
Kind: config.DriverName,
Name: p.Name,
SSHKeysID: []int{config.Driver.SSHKeyID},
CertsDir: p.ClientPath + "/certs",
}
return
} |
Gets a protein groups containing dict pgroups, for each master (key)
there is a list of protein tuples that comprise a proteingroup. This loops
the groups and returns a sorted group. Assumes master is already sorted
as the proper master | def sort_protein_groups(pgroups, evidence):
""""""
sortfnxs = get_sortfnxs(evidence)
pgroups_out = {}
for master, pgroup in pgroups.items():
sorted_pg = sort_protein_group(pgroup, sortfnxs, 0)
pgroups_out[master] = sorted_pg
return pgroups_out |
获取每个方法中的cpu和内存耗费最值点. | def get_each_method_maximun_cpu_mem(self):
""""""
# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点
self.method_exec_info = deepcopy(self.data.get("method_exec_info", []))
method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环
method_index, cpu_max, cpu_max_time, mem_max, mem_max_time = 0, 0, 0, 0, 0 # 临时变量
self.max_mem = 0
for index, timestamp in enumerate(self.timestamp_list):
# method_exec_info是按顺序的,逐个遍历找出每个method_exec_info中的cpu和mem的最值点和timestamp:
start, end = method_exec_info[0]["start_time"], method_exec_info[0]["end_time"]
if timestamp < start:
# 方法正式start之前的数据,不能参与方法内的cpu、mem计算,直接忽略此条数据
continue
elif timestamp <= end:
# 方法执行期间的数据,纳入最值比较:
if self.cpu_axis[index] > cpu_max:
cpu_max, cpu_max_time = self.cpu_axis[index], timestamp
if self.mem_axis[index] > mem_max:
mem_max, mem_max_time = self.mem_axis[index], timestamp
continue
else:
# 本次方法筛选完毕,保存本方法的最值cpu和mem
if cpu_max_time != 0 and mem_max_time != 0:
self.method_exec_info[method_index].update({"cpu_max": cpu_max, "mem_max": mem_max, "cpu_max_time": cpu_max_time, "mem_max_time": mem_max_time})
# 保存最大的内存,后面绘图时用
if mem_max > self.max_mem:
self.max_mem = mem_max
cpu_max, mem_max = 0, 0 # 临时变量
# 准备进行下一个方法的检查,发现已经检查完则正式结束
del method_exec_info[0]
if method_exec_info:
method_index += 1 # 进行下一个方法时:当前方法的序号+1
continue
else:
break |
// ApplyResource performs an apply of a unstructured resource | func (k KubectlCmd) ApplyResource(config *rest.Config, obj *unstructured.Unstructured, namespace string, dryRun, force bool) (string, error) {
log.Infof("Applying resource %s/%s in cluster: %s, namespace: %s", obj.GetKind(), obj.GetName(), config.Host, namespace)
f, err := ioutil.TempFile(util.TempDir, "")
if err != nil {
return "", fmt.Errorf("Failed to generate temp file for kubeconfig: %v", err)
}
_ = f.Close()
err = WriteKubeConfig(config, namespace, f.Name())
if err != nil {
return "", fmt.Errorf("Failed to write kubeconfig: %v", err)
}
defer util.DeleteFile(f.Name())
manifestBytes, err := json.Marshal(obj)
if err != nil {
return "", err
}
var out []string
// If it is an RBAC resource, run `kubectl auth reconcile`. This is preferred over
// `kubectl apply`, which cannot tolerate changes in roleRef, which is an immutable field.
// See: https://github.com/kubernetes/kubernetes/issues/66353
// `auth reconcile` will delete and recreate the resource if necessary
if obj.GetAPIVersion() == "rbac.authorization.k8s.io/v1" {
// `kubectl auth reconcile` has a side effect of auto-creating namespaces if it doesn't exist.
// See: https://github.com/kubernetes/kubernetes/issues/71185. This is behavior which we do
// not want. We need to check if the namespace exists, before know if it is safe to run this
// command. Skip this for dryRuns.
if !dryRun && namespace != "" {
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
return "", err
}
_, err = kubeClient.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
if err != nil {
return "", err
}
}
outReconcile, err := runKubectl(f.Name(), namespace, []string{"auth", "reconcile"}, manifestBytes, dryRun)
if err != nil {
return "", err
}
out = append(out, outReconcile)
// We still want to fallthrough and run `kubectl apply` in order set the
// last-applied-configuration annotation in the object.
}
// Run kubectl apply
applyArgs := []string{"apply"}
if force {
applyArgs = append(applyArgs, "--force")
}
outApply, err := runKubectl(f.Name(), namespace, applyArgs, manifestBytes, dryRun)
if err != nil {
return "", err
}
out = append(out, outApply)
return strings.Join(out, ". "), nil
} |
Import data on the registry.
By default, it reads the data from the standard input. If a positional
argument is given, it will read the data from there. | def run(self, *args):
params = self.parser.parse_args(args)
with params.infile as infile:
try:
stream = self.__read_file(infile)
parser = SortingHatParser(stream)
except InvalidFormatError as e:
self.error(str(e))
return e.code
except (IOError, TypeError, AttributeError) as e:
raise RuntimeError(str(e))
if params.identities:
self.import_blacklist(parser)
code = self.import_identities(parser,
matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
elif params.orgs:
self.import_organizations(parser, params.overwrite)
code = CMD_SUCCESS
else:
self.import_organizations(parser, params.overwrite)
self.import_blacklist(parser)
code = self.import_identities(parser, matching=params.matching,
match_new=params.match_new,
no_strict_matching=params.no_strict,
reset=params.reset,
verbose=params.verbose)
return code |
Dump a query.
@param \TYPO3\CMS\Extbase\Persistence\QueryInterface $query
@param boolean $return Whether or not to return dumped query. Echos by default
@return void | public function query(QueryInterface $query, $return = false)
{
DebuggerUtility::var_dump(
$this->queryParser->parseQuery($query),
null,
8,
false,
true,
$return
);
} |
// chainFilterer is the primary coordination goroutine within the
// CfFilteredChainView. This goroutine handles errors from the running rescan. | func (c *CfFilteredChainView) chainFilterer() {
defer c.wg.Done()
for {
select {
case err := <-c.rescanErrChan:
log.Errorf("Error encountered during rescan: %v", err)
case <-c.quit:
return
}
}
} |
Writes a session value to the session.
@param string $key Key to store the session value in.
@param string $val Value to be stored.
@throws InvalidArgumentException | public function write($key, $val)
{
$key = strval($key);
if(strlen($key) == 0)
{
$msg = 'The key cannot be empty.';
throw new InvalidArgumentException($msg);
}
$this->openSession();
$_SESSION[$key] = $val;
$this->closeSession();
} |
Will fail if locked by anybody other than 'job_key' | public void delete( Key job_key, float dummy ) {
if( _key != null ) {
Log.debug(Log.Tag.Sys.LOCKS,"lock-then-delete "+_key+" by job "+job_key);
new PriorWriteLock(job_key).invoke(_key);
}
Futures fs = new Futures();
delete_impl(fs);
if( _key != null ) DKV.remove(_key,fs); // Delete self also
fs.blockForPending();
} |
Checks the topic for any wildcards as a Event topic can not
contain wildcard characters, the MatchOne and MatchMany
@param topic The topic to be checked
@throws InvalidTopicSyntaxException if topic is syntactically invalid | public void checkEventTopicSyntax(String topic)
throws InvalidTopicSyntaxException
{
checkTopicNotNull(topic);
char[] chars = topic.toCharArray();
// becomes false when dot seen, stays false thereafter
boolean acceptDot = false;
// becomes false when hash seen, stays false thereafter
boolean acceptOrdinary = true;
// becomes false on wildcard, true on separator
boolean prevSeparator = false;
// becomes true on separator
for (int i = 0; i < chars.length; i++)
{
char cand = chars[i];
if (cand == MatchSpace.SUBTOPIC_MATCHONE_CHAR)
{
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
}
else if (cand == MatchSpace.SUBTOPIC_STOP_CHAR)
{
if (acceptDot)
{
prevSeparator = acceptDot = false;
acceptOrdinary = true;
}
else
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
}
else if (cand == MatchSpace.SUBTOPIC_SEPARATOR_CHAR)
{
// A separator is disallowed at the end of a publication
if(i == chars.length - 1)
{
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
}
if(prevSeparator)
{
// We've found a '//' this is disallowed in a publication
// discriminator string
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
}
// First separator
acceptOrdinary = prevSeparator = true;
acceptDot = false;
}
else if( cand == ':')
{
// :'s are disallowed in topic name parts
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
}
else // Ordinary character
{
if (!acceptOrdinary)
throw new InvalidTopicSyntaxException(
NLS.format(
"INVALID_TOPIC_ERROR_CWSIH0006",
new Object[] { topic }));
prevSeparator = false;
acceptDot = true;
}
}
} |
Identify the missing field
@param field missing field
@param expected expected result
@return result of comparison | public JSONCompareResult missing(String field, Object expected) {
_fieldMissing.add(new FieldComparisonFailure(field, expected, null));
fail(formatMissing(field, expected));
return this;
} |
Does the resource tag schedule and policy match the current time. | def process_resource_schedule(self, i, value, time_type):
""""""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
# before this normalization, some cases would silently fail.
value = ';'.join(filter(None, value.split(';')))
if self.parser.has_resource_schedule(value, time_type):
schedule = self.parser.parse(value)
elif self.parser.keys_are_valid(value):
# respect timezone from tag
raw_data = self.parser.raw_data(value)
if 'tz' in raw_data:
schedule = dict(self.default_schedule)
schedule['tz'] = raw_data['tz']
else:
schedule = self.default_schedule
else:
schedule = None
if schedule is None:
log.warning(
"Invalid schedule on resource:%s value:%s", rid, value)
self.parse_errors.append((rid, value))
return False
tz = self.get_tz(schedule['tz'])
if not tz:
log.warning(
"Could not resolve tz on resource:%s value:%s", rid, value)
self.parse_errors.append((rid, value))
return False
now = datetime.datetime.now(tz).replace(
minute=0, second=0, microsecond=0)
now_str = now.strftime("%Y-%m-%d")
if 'skip-days-from' in self.data:
values = ValuesFrom(self.data['skip-days-from'], self.manager)
self.skip_days = values.get_values()
else:
self.skip_days = self.data.get('skip-days', [])
if now_str in self.skip_days:
return False
return self.match(now, schedule) |
Executes the given block of code for each known chip mode, inside the block
the current mode of the top level block will be set to the given mode.
At the end of the block the current mode will be restored to whatever it
was before entering the block. | def with_each_mode
begin
orig = current_mode
rescue
orig = nil
end
modes.each do |_id, mode|
self.current_mode = mode
yield mode
end
self.current_mode = orig
end |
Serialize an object | def Serialize(self, val, info):
self._Serialize(val, info, self.defaultNS) |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
if len(self.actual_arguments) < 2:
return self.print_help()
input_file_path = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
if not self.check_input_file(input_file_path):
return self.ERROR_EXIT_CODE
if not self.check_output_file(output_file_path):
return self.ERROR_EXIT_CODE
try:
converter = FFMPEGWrapper(rconf=self.rconf, logger=self.logger)
converter.convert(input_file_path, output_file_path)
self.print_success(u"Converted '%s' into '%s'" % (input_file_path, output_file_path))
return self.NO_ERROR_EXIT_CODE
except FFMPEGPathError:
self.print_error(u"Unable to call the ffmpeg executable '%s'" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]))
self.print_error(u"Make sure the path to ffmpeg is correct")
except OSError:
self.print_error(u"Cannot convert file '%s' into '%s'" % (input_file_path, output_file_path))
self.print_error(u"Make sure the input file has a format supported by ffmpeg")
return self.ERROR_EXIT_CODE |
Get sortable element link start
@param string $column_key
@return void | protected function getSortableLinkStart($column_key)
{
if ($this->getColumnOption($column_key, self::COLUMN_OPTION_SORTABLE, false))
{
$sortable_url = $this->createUrl(array(
"column_orders[{$column_key}]" => (isset($this->columnOrders[$column_key]) && $this->columnOrders[$column_key] == 'asc') ? 'desc' : 'asc',
'single_order' => $column_key
));
echo '<a href="' . $sortable_url . '">';
}
} |