query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Start the asyncio event loop and runs the application. | def main():
"""Start the asyncio event loop and runs the application."""
# Helper method so that the coroutine exits cleanly if an exception
# happens (which would leave resources dangling)
async def _run_application(loop):
try:
return await cli_handler(loop)
except KeyboardInterrupt:
pass # User pressed Ctrl+C, just ignore it
except SystemExit:
pass # sys.exit() was used - do nothing
except: # pylint: disable=bare-except # noqa
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.writelines(
'\n>>> An error occurred, full stack trace above\n')
return 1
try:
loop = asyncio.get_event_loop()
return loop.run_until_complete(_run_application(loop))
except KeyboardInterrupt:
pass
return 1 | csn |
Initialize the pool manager with the number of pools, the entry sizes for each
pool, and the maximum depth of the free pool.
@param bufferEntrySizes the memory sizes of each entry in the pools
@param bufferEntryDepths the maximum number of entries in the free pool | public void initialize(int[] bufferEntrySizes, int[] bufferEntryDepths) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "initialize");
}
// order both lists from smallest to largest, based only on Entry Sizes
int len = bufferEntrySizes.length;
int[] bSizes = new int[len];
int[] bDepths = new int[len];
int sizeCompare;
int depth;
int sizeSort;
int j;
for (int i = 0; i < len; i++) {
sizeCompare = bufferEntrySizes[i];
depth = bufferEntryDepths[i];
// go backwards, for speed, since first Array List is
// probably already ordered small to large
for (j = i - 1; j >= 0; j--) {
sizeSort = bSizes[j];
if (sizeCompare > sizeSort) {
// add the bigger one after the smaller one
bSizes[j + 1] = sizeCompare;
bDepths[j + 1] = depth;
break;
}
// move current one down, since it is bigger
bSizes[j + 1] = sizeSort;
bDepths[j + 1] = bDepths[j];
}
if (j < 0) {
// smallest so far, add it at the front of the list
bSizes[0] = sizeCompare;
bDepths[0] = depth;
}
}
boolean tracking = trackingBuffers();
this.pools = new WsByteBufferPool[len];
this.poolsDirect = new WsByteBufferPool[len];
this.poolSizes = new int[len];
for (int i = 0; i < len; i++) {
// make backing pool 10 times larger than local pools
this.pools[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, false);
this.poolsDirect[i] = new WsByteBufferPool(bSizes[i], bDepths[i] * 10, tracking, true);
this.poolSizes[i] = bSizes[i];
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Number of pools created: " + this.poolSizes.length);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "initialize");
}
} | csn |
// List lists all of the documents in an index. The documents are returned in
// increasing ID order. | func (x *Index) List(c context.Context, opts *ListOptions) *Iterator {
t := &Iterator{
c: c,
index: x,
count: -1,
listInclusive: true,
more: moreList,
limit: -1,
}
if opts != nil {
t.listStartID = opts.StartID
if opts.Limit > 0 {
t.limit = opts.Limit
}
t.idsOnly = opts.IDsOnly
}
return t
} | csn |
Loads the entity that holds the item type data when an Item is loaded.
@param Item $item
@param LifecycleEventArgs $event | public function postLoad(Item $item, LifecycleEventArgs $event)
{
$type = $this->itemDefinitions->getConvertedType($item->getMimeType());
$definition = $this->itemDefinitions->get($type);
$repository = $event
->getEntityManager()
->getRepository($definition->getEntityClass());
/** @var \UJM\ExoBundle\Entity\ItemType\AbstractItem $typeEntity */
$typeEntity = $repository->findOneBy([
'question' => $item,
]);
if (!empty($typeEntity)) {
$item->setInteraction($typeEntity);
}
} | csn |
Extract the normalized text from within an element
@param fromElement
@return extracted Text node (could be null) | protected Text extractText(Element fromElement) {
fromElement.normalize();
NodeList fromNodeList = fromElement.getChildNodes();
Node currentNode;
for (int i=0; i < fromNodeList.getLength(); ++i) {
currentNode = fromNodeList.item(i);
if (currentNode.getNodeType() == Node.TEXT_NODE) {
return (Text) currentNode;
}
}
return null;
} | csn |
// handle processes a request from a Multiwatcher to the storeManager. | func (sm *storeManager) handle(req *request) {
if req.w.stopped {
// The watcher has previously been stopped.
if req.reply != nil {
select {
case req.reply <- false:
case <-sm.tomb.Dying():
}
}
return
}
if req.reply == nil {
// This is a request to stop the watcher.
for req := sm.waiting[req.w]; req != nil; req = req.next {
select {
case req.reply <- false:
case <-sm.tomb.Dying():
}
}
delete(sm.waiting, req.w)
req.w.stopped = true
sm.leave(req.w)
return
}
// Add request to head of list.
req.next = sm.waiting[req.w]
sm.waiting[req.w] = req
} | csn |
// Limit returns true if rate was exceeded | func (rl *RateLimiter) Limit() bool {
// Calculate the number of ns that have passed since our last call
now := unixNano()
passed := now - atomic.SwapUint64(&rl.lastCheck, now)
// Add them to our allowance
rate := atomic.LoadUint64(&rl.rate)
current := atomic.AddUint64(&rl.allowance, passed*rate)
// Ensure our allowance is not over maximum
if max := atomic.LoadUint64(&rl.max); current > max {
atomic.AddUint64(&rl.allowance, max-current)
current = max
}
// If our allowance is less than one unit, rate-limit!
if current < rl.unit {
return true
}
// Not limited, subtract a unit
atomic.AddUint64(&rl.allowance, -rl.unit)
return false
} | csn |
Modify to the last occurrence of a given day of the week
in the current quarter. If no day_of_week is provided,
modify to the last day of the quarter. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
:type day_of_week: int or None
:rtype: DateTime | def _last_of_quarter(self, day_of_week=None):
"""
Modify to the last occurrence of a given day of the week
in the current quarter. If no day_of_week is provided,
modify to the last day of the quarter. Use the supplied consts
to indicate the desired day_of_week, ex. DateTime.MONDAY.
:type day_of_week: int or None
:rtype: DateTime
"""
return self.on(self.year, self.quarter * 3, 1).last_of("month", day_of_week) | csn |
Compile Sass content using Leafo's ScssPhp compiler.
@link https://github.com/leafo/scssphp
@param string $content
Content to compile.
@param array $directories
The import directories to make available when compiling.
@return string Compiled Sass content. | private static function compileSassContentWithLeafoScss(string $content, array $directories)
{
if (empty($content)) {
return '';
}
if (self::$sassCompilerInstance == null) {
self::$sassCompilerInstance = self::getLeafoScssInstance();
}
self::updateLeafoScssInstance(self::$sassCompilerInstance, $directories);
return self::$sassCompilerInstance->compile($content);
} | csn |
Reset the date to the last day of the decade.
:rtype: Date | def _end_of_decade(self):
"""
Reset the date to the last day of the decade.
:rtype: Date
"""
year = self.year - self.year % YEARS_PER_DECADE + YEARS_PER_DECADE - 1
return self.set(year, 12, 31) | csn |
Puts an archive data row in an index. | private function putRowInIndex(&$index, $metadataNamesToIndexBy, $row, $idSite, $period)
{
$currentLevel = & $index;
foreach ($metadataNamesToIndexBy as $metadataName) {
if ($metadataName == DataTableFactory::TABLE_METADATA_SITE_INDEX) {
$key = $idSite;
} elseif ($metadataName == DataTableFactory::TABLE_METADATA_PERIOD_INDEX) {
$key = $period;
} else {
$key = $row[self::METADATA_CONTAINER_ROW_KEY][$metadataName];
}
if (!isset($currentLevel[$key])) {
$currentLevel[$key] = array();
}
$currentLevel = & $currentLevel[$key];
}
$currentLevel = $row;
} | csn |
Is the point near any points in the multi lat lng
@param point point
@param multiLatLng multi lat lng
@param tolerance distance tolerance
@return true if near | public static boolean isPointNearMultiLatLng(LatLng point, MultiLatLng multiLatLng, double tolerance) {
boolean near = false;
for (LatLng multiPoint : multiLatLng.getLatLngs()) {
near = isPointNearPoint(point, multiPoint, tolerance);
if (near) {
break;
}
}
return near;
} | csn |
Gives support for Rails date_select, datetime_select, time_select helpers. | def process_attributes(attributes = nil)
return attributes if attributes.blank?
multi_parameter_attributes = {}
new_attributes = {}
attributes.each_pair do |key, value|
if key.match(DATE_KEY_REGEX)
match = key.to_s.match(DATE_KEY_REGEX)
found_key = match[1]
index = match[2].to_i
(multi_parameter_attributes[found_key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}")
else
new_attributes[key] = value
end
end
multi_parameter_attributes.empty? ? new_attributes : process_multiparameter_attributes(multi_parameter_attributes, new_attributes)
end | csn |
read-only
@language=en
Set text CSS font style.
@param {String} font Text CSS font style to set.
@returns {Text} the Text object, chained call supported. | function(font){
var me = this;
if(me.font !== font){
me.font = font;
me._fontHeight = Text.measureFontHeight(font);
}
return me;
} | csn |
Generate a new Key in the NFVO.
@param name the name of the new Key
@return the private Key
@throws SDKException if the request fails | @Help(help = "Generate a new Key in the NFVO")
public String generateKey(String name) throws SDKException {
return (String) requestPost("generate", name);
} | csn |
hack for NS62 bug | function jsUnitFixTop() {
var tempTop = top;
if (!tempTop) {
tempTop = window;
while (tempTop.parent) {
tempTop = tempTop.parent;
if (tempTop.top && tempTop.top.jsUnitTestSuite) {
tempTop = tempTop.top;
break;
}
}
}
try {
window.top = tempTop;
} catch (e) {
}
} | csn |
Convert a file into a raid file format | public void raidFile(INode sourceINodes[], String source,
RaidCodec codec, short expectedSourceRepl, Block[] parityBlocks)
throws IOException {
waitForReady();
long now = FSNamesystem.now();
unprotectedRaidFile(sourceINodes, source, codec, expectedSourceRepl,
parityBlocks, now);
fsImage.getEditLog().logRaidFile(source, codec.id, expectedSourceRepl,
now);
} | csn |
Checks if an object holding the same name already exists in the index.
If so, it compares their definition order: the lowest definition order
is kept. If definition order equal, an error is risen.Item
The method returns the item that should be added after it has decided
which one should be kept.
If the new item has precedence over the New existing one, the
existing is removed for the new to replace it.
:param item: object to check for conflict
:type item: alignak.objects.item.Item
:param name: name of the object
:type name: str
:return: 'item' parameter modified
:rtype: object | def manage_conflict(self, item, name):
"""
Checks if an object holding the same name already exists in the index.
If so, it compares their definition order: the lowest definition order
is kept. If definition order equal, an error is risen.Item
The method returns the item that should be added after it has decided
which one should be kept.
If the new item has precedence over the New existing one, the
existing is removed for the new to replace it.
:param item: object to check for conflict
:type item: alignak.objects.item.Item
:param name: name of the object
:type name: str
:return: 'item' parameter modified
:rtype: object
"""
if item.is_tpl():
existing = self.name_to_template[name]
else:
existing = self.name_to_item[name]
if existing == item:
return item
existing_prio = getattr(
existing,
"definition_order",
existing.properties["definition_order"].default)
item_prio = getattr(
item,
"definition_order",
item.properties["definition_order"].default)
if existing_prio < item_prio:
# Existing item has lower priority, so it has precedence.
return existing
if existing_prio > item_prio:
# New item has lower priority, so it has precedence.
# Existing item will be deleted below
pass
else:
# Don't know which one to keep, lastly defined has precedence
objcls = getattr(self.inner_class, "my_type", "[unknown]")
mesg = "duplicate %s '%s', from: '%s' and '%s', using lastly defined. " \
"You may manually set the definition_order parameter to avoid this message." \
% (objcls, name, item.imported_from, existing.imported_from)
item.configuration_warnings.append(mesg)
if item.is_tpl():
self.remove_template(existing)
else:
self.remove_item(existing)
return item | csn |
Convert the alias.
@param string
@return LibBaseTemplateFilterAlias | public function write(&$text)
{
$matches = array();
if (strpos($text, '<html')) {
//add language
$text = str_replace('<html', '<html lang="'.$this->getService('anahita:language')->getTag().'"', $text);
//render the styles
$text = str_replace('</head>', $this->_renderHead().$this->_renderStyles().'</head>', $text);
//render the scripts
$text = str_replace('</body>', $this->_renderScripts().'</body>', $text);
}
} | csn |
Create an object URL.
Given a base URL and an object name, create an object URL.
This is useful because object names can contain certain characters
(namely slashes (`/`)) that are normally URLencoded when they appear
inside of path sequences.
@note
Swift does not distinguish between @c %2F and a slash character, so
this is not strictly necessary.
@param string $base
The base URL. This is not altered; it is just prepended to
the returned string.
@param string $oname
The name of the object.
@retval string
@return string
The URL to the object. Characters that need escaping will be escaped,
while slash characters are not. Thus, the URL will look pathy. | public static function objectUrl($base, $oname) {
if (strpos($oname, '/') === FALSE) {
return $base . '/' . rawurlencode($oname);
}
$oParts = explode('/', $oname);
$buffer = array();
foreach ($oParts as $part) {
$buffer[] = rawurlencode($part);
}
$newname = implode('/', $buffer);
return $base . '/' . $newname;
} | csn |
get the current input instance
@param CCIn_Instance $set if set the current instance gets updated
@return CCIn_Instance | public static function instance( $set = null )
{
if ( is_null( $set ) )
{
return static::$_instance;
}
if ( !$set instanceof CCIn_Instance )
{
throw new \InvalidArgumentException('CCIn::set() - only CCIn_Instance object can be passed.');
}
static::$_instance = $set;
} | csn |
Print the default values of all cls's Parameters. | def print_param_defaults(self_):
"""Print the default values of all cls's Parameters."""
cls = self_.cls
for key,val in cls.__dict__.items():
if isinstance(val,Parameter):
print(cls.__name__+'.'+key+ '='+ repr(val.default)) | csn |
Perform an ajax request to get comments for a node
and insert the comments into the comments tree. | function getComments(id) {
$.ajax({
type: 'GET',
url: opts.getCommentsURL,
data: {node: id},
success: function(data, textStatus, request) {
var ul = $('#cl' + id);
var speed = 100;
$('#cf' + id)
.find('textarea[name="proposal"]')
.data('source', data.source);
if (data.comments.length === 0) {
ul.html('<li>No comments yet.</li>');
ul.data('empty', true);
} else {
// If there are comments, sort them and put them in the list.
var comments = sortComments(data.comments);
speed = data.comments.length * 100;
appendComments(comments, ul);
ul.data('empty', false);
}
$('#cn' + id).slideUp(speed + 200);
ul.slideDown(speed);
},
error: function(request, textStatus, error) {
showError('Oops, there was a problem retrieving the comments.');
},
dataType: 'json'
});
} | csn |
// lookupReader - return the reader function for the given scheme | func (d *Data) lookupReader(scheme string) (func(*Source, ...string) ([]byte, error), error) {
if d.sourceReaders == nil {
d.registerReaders()
}
r, ok := d.sourceReaders[scheme]
if !ok {
return nil, errors.Errorf("scheme %s not registered", scheme)
}
return r, nil
} | csn |
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray | def get_pij_matrix(t, diag, A, A_inv):
"""
Calculates the probability matrix of substitutions i->j over time t,
given the normalised generator diagonalisation.
:param t: time
:type t: float
:return: probability matrix
:rtype: numpy.ndarray
"""
return A.dot(np.diag(np.exp(diag * t))).dot(A_inv) | csn |
Like tree view mode | def tree(self):
"""Like tree view mode
"""
self.msg.template(78)
print("| Dependencies\n"
"| -- Packages")
self.msg.template(78)
self.data()
for pkg, dep in self.dmap.iteritems():
print("+ {0}{1}{2}".format(self.green, pkg, self.endc))
print("|")
for d in dep:
print("+-- {0}".format(d))
print("|")
sys.stdout.write("\x1b[1A{0}\n".format(" "))
sys.stdout.flush()
self.summary()
if self.image:
Graph(self.image).dependencies(self.dmap) | csn |
Payment options.
@return array | public static function getOptions()
{
$options = [];
$options[] = [
'id' => Operation::PRODUCT_VISA,
'label' => "Visa",
];
$options[] = [
'id' => Operation::PRODUCT_MASTERCARD,
'label' => "Mastercard",
];
$options[] = [
'id' => Operation::PRODUCT_AMERICAN_EXPRESS,
'label' => "American Express",
];
$options[] = [
'id' => Operation::PRODUCT_DINERS,
'label' => "Diners",
];
return $options;
} | csn |
Load a profile by name
Called by load_user_options | def _load_profile(self, profile_name):
"""Load a profile by name
Called by load_user_options
"""
# find the profile
default_profile = self._profile_list[0]
for profile in self._profile_list:
if profile.get('default', False):
# explicit default, not the first
default_profile = profile
if profile['display_name'] == profile_name:
break
else:
if profile_name:
# name specified, but not found
raise ValueError("No such profile: %s. Options include: %s" % (
profile_name, ', '.join(p['display_name'] for p in self._profile_list)
))
else:
# no name specified, use the default
profile = default_profile
self.log.debug("Applying KubeSpawner override for profile '%s'", profile['display_name'])
kubespawner_override = profile.get('kubespawner_override', {})
for k, v in kubespawner_override.items():
if callable(v):
v = v(self)
self.log.debug(".. overriding KubeSpawner value %s=%s (callable result)", k, v)
else:
self.log.debug(".. overriding KubeSpawner value %s=%s", k, v)
setattr(self, k, v) | csn |
Wrapper works for conversion.
Args:
- filename -- str, file to be converted | def f2format(filename):
"""Wrapper works for conversion.
Args:
- filename -- str, file to be converted
"""
print('Now converting %r...' % filename)
# fetch encoding
encoding = os.getenv('F2FORMAT_ENCODING', LOCALE_ENCODING)
lineno = dict() # line number -> file offset
content = list() # file content
with open(filename, 'r', encoding=encoding) as file:
lineno[1] = 0
for lnum, line in enumerate(file, start=1):
content.append(line)
lineno[lnum+1] = lineno[lnum] + len(line)
# now, do the dirty works
string = ''.join(content)
text = convert(string, lineno)
# dump back to the file
with open(filename, 'w', encoding=encoding) as file:
file.write(text) | csn |
Teardown button handler. | def exitClient(self):
"""Teardown button handler."""
self.sendRtspRequest(self.TEARDOWN)
#self.handler()
os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video
rate = float(self.counter/self.frameNbr)
print('-'*60 + "\nRTP Packet Loss Rate :" + str(rate) +"\n" + '-'*60)
sys.exit(0) | csn |
Cancelles an invoice
:param invoice_id: the invoice id
:return Response | def cancel_invoice(self, invoice_id):
"""
Cancelles an invoice
:param invoice_id: the invoice id
:return Response
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=CANCEL,
) | csn |
Initializes a new service. | @SuppressWarnings("unchecked")
private RaftServiceContext initializeService(PrimitiveId primitiveId, PrimitiveType primitiveType, String serviceName, byte[] config) {
RaftServiceContext oldService = raft.getServices().getService(serviceName);
ServiceConfig serviceConfig = config == null ? new ServiceConfig() : Serializer.using(primitiveType.namespace()).decode(config);
RaftServiceContext service = new RaftServiceContext(
primitiveId,
serviceName,
primitiveType,
serviceConfig,
primitiveType.newService(serviceConfig),
raft,
threadContextFactory);
raft.getServices().registerService(service);
// If a service with this name was already registered, remove all of its sessions.
if (oldService != null) {
raft.getSessions().removeSessions(oldService.serviceId());
}
return service;
} | csn |
// GetSettings retrieves settings from the ArgoCDConfigMap and secret. | func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
if err != nil {
return nil, err
}
var settings ArgoCDSettings
var errs []error
if err := updateSettingsFromConfigMap(&settings, argoCDCM); err != nil {
errs = append(errs, err)
}
if err := updateSettingsFromSecret(&settings, argoCDSecret); err != nil {
errs = append(errs, err)
}
if len(errs) > 0 {
return &settings, errs[0]
}
return &settings, nil
} | csn |
Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph | def remove_isolated_nodes_op(graph):
"""Build a new graph excluding the isolated nodes.
:param pybel.BELGraph graph: A BEL graph
:rtype: pybel.BELGraph
"""
rv = graph.copy()
nodes = list(nx.isolates(rv))
rv.remove_nodes_from(nodes)
return rv | csn |
Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tuple, even if the
gradient of only one input was required. We unpack the tuple if it is of
length one.
Args:
fwdbwd: An AST. The function definition of the joint primal and adjoint.
func: A function handle. The original function that was differentiated.
wrt: A tuple of integers. The arguments with respect to which we differentiated.
Returns:
The function definition of the new function. | def _create_joint(fwdbwd, func, wrt, input_derivative):
"""Create a user-friendly gradient function.
By default, gradient functions expect the stack to be passed to them
explicitly. This function modifies the function so that the stack doesn't
need to be passed and gets initialized in the function body instead.
For consistency, gradient functions always return a tuple, even if the
gradient of only one input was required. We unpack the tuple if it is of
length one.
Args:
fwdbwd: An AST. The function definition of the joint primal and adjoint.
func: A function handle. The original function that was differentiated.
wrt: A tuple of integers. The arguments with respect to which we differentiated.
Returns:
The function definition of the new function.
"""
# Correct return to be a non-tuple if there's only one element
retval = fwdbwd.body[-1]
if len(retval.value.elts) == 1:
retval.value = retval.value.elts[0]
# Make a stack init statement
init_stack = quoting.quote('%s = tangent.Stack()' % fwdbwd.args.args[0].id)
init_stack = comments.add_comment(init_stack, 'Initialize the tape')
# Prepend the stack init to the top of the function
fwdbwd.body = [init_stack] + fwdbwd.body
# Replace the function arguments with the original ones
grad_name = fwdbwd.args.args[1].id
fwdbwd.args = quoting.parse_function(func).body[0].args
# Give the function a nice name
fwdbwd.name = naming.joint_name(func, wrt)
# Allow the initial gradient to be passed as a keyword argument
fwdbwd = ast_.append_args(fwdbwd, [grad_name])
if input_derivative == INPUT_DERIVATIVE.DefaultOne:
fwdbwd.args.defaults.append(quoting.quote('1.0'))
return fwdbwd | csn |
Determine whether a given key is filterable
@param string $key
@return bool | public function isFilterable(string $key): bool
{
if ($this->filterable === self::ALLOW_ALL) {
return true;
}
return isset($this->filterable[$key]) && $this->filterable[$key];
} | csn |
Borrow an object from the pool, or create a new object
if no valid objects in the pool
@return {@link Entry} to the pooled object
@throws E exception thrown by initializer | public Entry borrow() throws E {
long now = System.currentTimeMillis();
if (timeout > 0) {
long accessed_ = accessed.get();
if (now > accessed_ + Time.SECOND &&
accessed.compareAndSet(accessed_, now)) {
Entry entry;
while ((entry = deque.pollLast()) != null) {
// inactiveCount.decrementAndGet();
if (now < entry.borrowed + timeout) {
deque.offerLast(entry);
// inactiveCount.incrementAndGet();
break;
}
inactiveCount.decrementAndGet();
try {
finalizer.accept(entry.object);
} catch (Exception e) {
// Ignored
}
}
}
}
Entry entry = deque.pollFirst();
if (entry != null) {
inactiveCount.decrementAndGet();
entry.borrowed = now;
entry.borrows ++;
entry.valid = false;
activeCount.incrementAndGet();
return entry;
}
entry = new Entry();
entry.object = initializer.get();
entry.created = entry.borrowed = now;
entry.borrows = 0;
entry.valid = false;
activeCount.incrementAndGet();
return entry;
} | csn |
Creates a new Server object. Also creates an HTTP server to start listening
for XML-RPC method calls. Will emit an event with the XML-RPC call's method
name when receiving a method call.
@constructor
@param {Object|String} options - The HTTP server options. Either a URI string
(e.g. 'http://localhost:9090') or an object
with fields:
- {String} host - (optional)
- {Number} port
@param {Boolean} isSecure - True if using https for making calls,
otherwise false.
@return {Server} | function Server(options, isSecure, onListening) {
if (false === (this instanceof Server)) {
return new Server(options, isSecure)
}
onListening = onListening || function() {}
var that = this
// If a string URI is passed in, converts to URI fields
if (typeof options === 'string') {
options = url.parse(options)
options.host = options.hostname
options.path = options.pathname
}
function handleMethodCall(request, response) {
var deserializer = new Deserializer()
deserializer.deserializeMethodCall(request, function(error, methodName, params) {
if (Object.prototype.hasOwnProperty.call(that._events, methodName)) {
that.emit(methodName, null, params, function(error, value) {
var xml = null
if (error !== null) {
xml = Serializer.serializeFault(error)
}
else {
xml = Serializer.serializeMethodResponse(value)
}
response.writeHead(200, {'Content-Type': 'text/xml'})
response.end(xml)
})
}
else {
that.emit('NotFound', methodName, params)
response.writeHead(404)
response.end()
}
})
}
this.httpServer = isSecure ? https.createServer(options, handleMethodCall)
: http.createServer(handleMethodCall)
process.nextTick(function() {
this.httpServer.listen(options.port, options.host, onListening)
}.bind(this))
this.close = function(callback) {
this.httpServer.once('close', callback)
this.httpServer.close()
}.bind(this)
} | csn |
Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
# ...
@dispatch.public(name='do_something')
def visible_method(arg1)
# ...
:param str name: Name to register callable with. | def public(self, name=None):
"""Convenient decorator.
Allows easy registering of functions to this dispatcher. Example:
.. code-block:: python
dispatch = RPCDispatcher()
@dispatch.public
def foo(bar):
# ...
class Baz(object):
def not_exposed(self):
# ...
@dispatch.public(name='do_something')
def visible_method(arg1)
# ...
:param str name: Name to register callable with.
"""
if callable(name):
self.add_method(name)
return name
def _(f):
self.add_method(f, name=name)
return f
return _ | csn |
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key. | def _collate_data(collation, first_axis, second_axis):
"""
Collects information about the number of edit actions belonging to keys in
a supplied dictionary of object or changeset ids.
Parameters
----------
collation : dict
A dictionary of OpenStreetMap object or changeset ids.
first_axis : string
An object or changeset key for the collation to be performed on.
second_axis : {'create','modify','delete'}
An action key to be added to the first_axis key.
"""
if first_axis not in collation:
collation[first_axis] = {}
collation[first_axis]["create"] = 0
collation[first_axis]["modify"] = 0
collation[first_axis]["delete"] = 0
first = collation[first_axis]
first[second_axis] = first[second_axis] + 1
collation[first_axis] = first | csn |
Check if sending the given message was enabled by the client.
@param message
the message to check
@return true if the message should be sent, false otherwise (and the message is discarded) | protected boolean checkSendMessageEnabled(RTMPMessage message) {
IRTMPEvent body = message.getBody();
if (!receiveAudio && body instanceof AudioData) {
// The user doesn't want to get audio packets
((IStreamData<?>) body).getData().free();
if (sendBlankAudio) {
// Send reset audio packet
sendBlankAudio = false;
body = new AudioData();
// We need a zero timestamp
if (lastMessageTs >= 0) {
body.setTimestamp(lastMessageTs - timestampOffset);
} else {
body.setTimestamp(-timestampOffset);
}
message = RTMPMessage.build(body);
} else {
return false;
}
} else if (!receiveVideo && body instanceof VideoData) {
// The user doesn't want to get video packets
((IStreamData<?>) body).getData().free();
return false;
}
return true;
} | csn |
Moves the positon based on a direction.
@param int $direction
@return void | public function move($direction)
{
if ($direction === self::DIR_FORWARD) {
return $this->next();
} elseif ($direction === self::DIR_BACKWARD) {
return $this->prev();
}
throw new InvalidArgumentException(sprintf('Unknown direction %s', $direction));
} | csn |
// Build the mount_sample tool if it has not yet been built for this process.
// Return its contents. | func getToolContents() (contents []byte, err error) {
// Get hold of the binary contents, if we haven't yet.
getToolContents_Once.Do(func() {
getToolContents_Contents, getToolContents_Err = getToolContentsImpl()
})
contents, err = getToolContents_Contents, getToolContents_Err
return
} | csn |
Get an instance of a validation class.
@param string $name
@return validator\Validation
@throws exceptions\ValidatorException | private function getValidation(string $name): validator\Validation
{
if (!isset($this->validations[$name])) {
if (isset($this->validationRegister[$name])) {
$class = $this->validationRegister[$name];
} else {
throw new exceptions\ValidatorException("Validator [$name] not found");
}
$params = isset($this->validationData[$name]) ? $this->validationData[$name] : null;
$this->validations[$name] = new $class($params);
}
return $this->validations[$name];
} | csn |
// Returns a visualization of the string. | func (s StringObject) String() string {
return fmt.Sprintf("StringObject{Key: %s, Value: '%s'}", DataToString(s.Key), DataToString(s.Value))
} | csn |
Loads all data for zones that belong to provided layout. | public function loadLayoutZonesData(Layout $layout): array
{
$query = $this->getZoneSelectQuery();
$query->where(
$query->expr()->eq('layout_id', ':layout_id')
)
->setParameter('layout_id', $layout->id, Type::INTEGER)
->orderBy('identifier', 'ASC');
$this->applyStatusCondition($query, $layout->status);
return $query->execute()->fetchAll(PDO::FETCH_ASSOC);
} | csn |
// Dequeue pulls a message off the queue
// If there are no messages, it waits for one.
// If the buffer is closed, it will return immediately. | func (r *messageRing) Dequeue() (*Message, error) {
r.mu.Lock()
for len(r.queue) == 0 && !r.closed {
r.wait.Wait()
}
if r.closed {
r.mu.Unlock()
return nil, errClosed
}
msg := r.queue[0]
r.queue = r.queue[1:]
r.sizeBytes -= int64(len(msg.Line))
r.mu.Unlock()
return msg, nil
} | csn |
Set the current agent's state to Ready on the voice channel.
@param reasons Information on causes for, and results of, actions taken by the user of the current DN. For details about reasons, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Reasons).
@param extensions Media device/hardware reason codes and similar information. For details about extensions, refer to the [*Genesys Events and Models Reference Manual*](https://docs.genesys.com/Documentation/System/Current/GenEM/Extensions). (optional) | public void setAgentReady(KeyValueCollection reasons, KeyValueCollection extensions) throws WorkspaceApiException {
try {
VoicereadyData readyData = new VoicereadyData();
readyData.setReasons(Util.toKVList(reasons));
readyData.setExtensions(Util.toKVList(extensions));
ReadyData data = new ReadyData();
data.data(readyData);
ApiSuccessResponse response = this.voiceApi.setAgentStateReady(data);
throwIfNotOk("setAgentReady", response);
} catch (ApiException e) {
throw new WorkspaceApiException("setAgentReady failed.", e);
}
} | csn |
// CreateForwardingPathList creates a new child ForwardingPathList under the Domain | func (o *Domain) CreateForwardingPathList(child *ForwardingPathList) *bambou.Error {
return bambou.CurrentSession().CreateChild(o, child)
} | csn |
Calculate the vertices that define the position of a graphical object within
the worksheet in EMUs.
The vertices are expressed as English Metric Units (EMUs). There are 12,700
EMUs per point. Therefore, 12,700 * 3 /4 = 9,525 EMUs per pixel. | def position_object_emus(col_start, row_start, x1, y1, width, height, x_dpi = 96, y_dpi = 96) #:nodoc:
col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs =
position_object_pixels(col_start, row_start, x1, y1, width, height)
# Convert the pixel values to EMUs. See above.
x1 = (0.5 + 9_525 * x1).to_i
y1 = (0.5 + 9_525 * y1).to_i
x2 = (0.5 + 9_525 * x2).to_i
y2 = (0.5 + 9_525 * y2).to_i
x_abs = (0.5 + 9_525 * x_abs).to_i
y_abs = (0.5 + 9_525 * y_abs).to_i
[col_start, row_start, x1, y1, col_end, row_end, x2, y2, x_abs, y_abs]
end | csn |
// CropCenter cuts out a rectangular region with the specified size
// from the center of the image and returns the cropped image. | func CropCenter(img image.Image, width, height int) *image.NRGBA {
return CropAnchor(img, width, height, Center)
} | csn |
Disable all benchmarking. | def disable():
"""
Disable all benchmarking.
"""
Benchmark.enable = False
ComparisonBenchmark.enable = False
BenchmarkedFunction.enable = False
BenchmarkedClass.enable = False | csn |
// resetBuffer makes a local pointer to the buffer,
// then resets the buffer by assigning to be a newly-
// made value to clear it out, then sets the buffer
// item count to 0. It returns the copied pointer to
// the original map so the old buffer value can be
// used locally. | func resetBuffer() map[string]interface{} {
bufferMu.Lock()
bufCopy := buffer
buffer = make(map[string]interface{})
bufferItemCount = 0
bufferMu.Unlock()
return bufCopy
} | csn |
Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section | def is_back_tracking(neurite):
''' Check if a neurite process backtracks to a previous node. Back-tracking takes place
when a daughter of a branching process goes back and either overlaps with a previous point, or
lies inside the cylindrical volume of the latter.
Args:
neurite(Neurite): neurite to operate on
Returns:
True Under the following scenaria:
1. A segment endpoint falls back and overlaps with a previous segment's point
2. The geometry of a segment overlaps with a previous one in the section
'''
def pair(segs):
''' Pairs the input list into triplets'''
return zip(segs, segs[1:])
def coords(node):
''' Returns the first three values of the tree that correspond to the x, y, z coordinates'''
return node[COLS.XYZ]
def max_radius(seg):
''' Returns maximum radius from the two segment endpoints'''
return max(seg[0][COLS.R], seg[1][COLS.R])
def is_not_zero_seg(seg):
''' Returns True if segment has zero length'''
return not np.allclose(coords(seg[0]), coords(seg[1]))
def is_in_the_same_verse(seg1, seg2):
''' Checks if the vectors face the same direction. This
is true if their dot product is greater than zero.
'''
v1 = coords(seg2[1]) - coords(seg2[0])
v2 = coords(seg1[1]) - coords(seg1[0])
return np.dot(v1, v2) >= 0
def is_seg2_within_seg1_radius(dist, seg1, seg2):
''' Checks whether the orthogonal distance from the point at the end of
seg1 to seg2 segment body is smaller than the sum of their radii
'''
return dist <= max_radius(seg1) + max_radius(seg2)
def is_seg1_overlapping_with_seg2(seg1, seg2):
'''Checks if a segment is in proximity of another one upstream'''
# get the coordinates of seg2 (from the origin)
s1 = coords(seg2[0])
s2 = coords(seg2[1])
# vector of the center of seg2 (from the origin)
C = 0.5 * (s1 + s2)
# endpoint of seg1 (from the origin)
P = coords(seg1[1])
# vector from the center C of seg2 to the endpoint P of seg1
CP = P - C
# vector of seg2
S1S2 = s2 - s1
# projection of CP upon seg2
prj = mm.vector_projection(CP, S1S2)
# check if the distance of the orthogonal complement of CP projection on S1S2
# (vertical distance from P to seg2) is smaller than the sum of the radii. (overlap)
# If not exit early, because there is no way that backtracking can feasible
if not is_seg2_within_seg1_radius(np.linalg.norm(CP - prj), seg1, seg2):
return False
# projection lies within the length of the cylinder. Check if the distance between
# the center C of seg2 and the projection of the end point of seg1, P is smaller than
# half of the others length plus a 5% tolerance
return np.linalg.norm(prj) < 0.55 * np.linalg.norm(S1S2)
def is_inside_cylinder(seg1, seg2):
''' Checks if seg2 approximately lies within a cylindrical volume of seg1.
Two conditions must be satisfied:
1. The two segments are not facing the same direction (seg2 comes back to seg1)
2. seg2 is overlaping with seg1
'''
return not is_in_the_same_verse(seg1, seg2) and is_seg1_overlapping_with_seg2(seg1, seg2)
# filter out single segment sections
section_itr = (snode for snode in neurite.iter_sections() if snode.points.shape[0] > 2)
for snode in section_itr:
# group each section's points intro triplets
segment_pairs = list(filter(is_not_zero_seg, pair(snode.points)))
# filter out zero length segments
for i, seg1 in enumerate(segment_pairs[1:]):
# check if the end point of the segment lies within the previous
# ones in the current sectionmake
for seg2 in segment_pairs[0: i + 1]:
if is_inside_cylinder(seg1, seg2):
return True
return False | csn |
Helper method for performing requests to the homeserver.
@param method [Symbol] HTTP request method to use. Use only symbols
available as keys in {METHODS}.
@param path [String] The API path to query, relative to the base
API path, eg. `/login`.
@param opts [Hash] Additional request options.
@option opts [Hash] :params Additional parameters to include in the
query string (part of the URL, not put in the request body).
@option opts [Hash,#read] :content Content to put in the request body.
If set, must be a Hash or a stream object.
@option opts [Hash{String => String}] :headers Additional headers to
include in the request.
@option opts [String,nil] :base If this is set, it will be used as the
base URI for the request instead of the default (`@base_uri`).
@yield [fragment] HTTParty will call the block during the request.
@return [HTTParty::Response] The HTTParty response object. | def make_request(method, path, opts = {}, &block)
path = (opts[:base] || @base_uri) + URI.encode(path)
options = make_options opts[:params], opts[:content], opts[:headers]
parse_response METHODS[method].call(path, options, &block)
end | csn |
Similar to parse but returns a list of Options objects instead
of the dictionary format. | def parse_options(cls, line, ns={}):
"""
Similar to parse but returns a list of Options objects instead
of the dictionary format.
"""
parsed = cls.parse(line, ns=ns)
options_list = []
for spec in sorted(parsed.keys()):
options = parsed[spec]
merged = {}
for group in options.values():
merged = dict(group.kwargs, **merged)
options_list.append(Options(spec, **merged))
return options_list | csn |
Run server with provided command line arguments. | def start(args):
"""Run server with provided command line arguments.
"""
application = tornado.web.Application([(r"/run", run.get_handler(args)),
(r"/status", run.StatusHandler)])
application.runmonitor = RunMonitor()
application.listen(args.port)
tornado.ioloop.IOLoop.instance().start() | csn |
// GenTLSConfig loads TLS related configuration parameters. | func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) {
// Now load in cert and private key
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile)
if err != nil {
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
}
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
if err != nil {
return nil, fmt.Errorf("error parsing certificate: %v", err)
}
// Create the tls.Config from our options.
// We will determine the cipher suites that we prefer.
// FIXME(dlc) change if ARM based.
config := tls.Config{
MinVersion: tls.VersionTLS12,
CipherSuites: tc.Ciphers,
PreferServerCipherSuites: true,
CurvePreferences: tc.CurvePreferences,
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: tc.Insecure,
}
// Require client certificates as needed
if tc.Verify {
config.ClientAuth = tls.RequireAndVerifyClientCert
}
// Add in CAs if applicable.
if tc.CaFile != "" {
rootPEM, err := ioutil.ReadFile(tc.CaFile)
if err != nil || rootPEM == nil {
return nil, err
}
pool := x509.NewCertPool()
ok := pool.AppendCertsFromPEM(rootPEM)
if !ok {
return nil, fmt.Errorf("failed to parse root ca certificate")
}
config.ClientCAs = pool
}
return &config, nil
} | csn |
// pruneDeadHolders is used to remove all the dead lock holders | func (s *Semaphore) pruneDeadHolders(lock *semaphoreLock, pairs KVPairs) {
// Gather all the live holders
alive := make(map[string]struct{}, len(pairs))
for _, pair := range pairs {
if pair.Session != "" {
alive[pair.Session] = struct{}{}
}
}
// Remove any holders that are dead
for holder := range lock.Holders {
if _, ok := alive[holder]; !ok {
delete(lock.Holders, holder)
}
}
} | csn |
Read and return the data from a corpus json file. | def read_corpus(file_name):
"""
Read and return the data from a corpus json file.
"""
with io.open(file_name, encoding='utf-8') as data_file:
return yaml.load(data_file) | csn |
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail. | def calculate_matrices(states, Omega=1):
r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail.
"""
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:
raise ValueError('All states must belong to the same isotope.')
# We find the fine states involved in the problem.
fine_states = find_fine_states(states)
# We find the full magnetic states. The matrices will be first calculated
# for the complete problem and later reduced to include only the states of
# interest.
full_magnetic_states = make_list_of_states(fine_states, 'magnetic',
verbose=0)
# We calculate the indices corresponding to each sub matrix of fine and
# hyperfine levels.
# We calculate the frequency differences between states.
omega_full = calculate_omega_matrix(full_magnetic_states, Omega)
# We calculate the matrix gamma.
gamma_full = calculate_gamma_matrix(full_magnetic_states, Omega)
# We calculate the reduced matrix elements
reduced_matrix_elements = calculate_reduced_matrix_elements(fine_states)
# We calculate the matrices r_-1, r_0, r_1
r_full = calculate_r_matrices(fine_states, reduced_matrix_elements)
# Reduction to be implemented
omega = omega_full
r = r_full
gamma = gamma_full
return omega, gamma, r | csn |
Get an absolute path to a lock file for a specified file path.
@param string $file The absolute path to get the lock filename for.
@param array $options An array of options for the process.
@return string The absolute path for the lock file | protected function lockFileName($file, array $options = array()) {
$lockDir = $this->getOption('lock_dir', $options, $this->getCachePath() . 'locks' . DIRECTORY_SEPARATOR);
return $lockDir . preg_replace('/\W/', '_', $file) . $this->getOption(xPDO::OPT_LOCKFILE_EXTENSION, $options, '.lock');
} | csn |
// Reads an error out of the HTTP response, or does nothing if
// no error occurred. | func getError(res *http.Response) (*http.Response, error) {
// Do nothing if the response is a successful 2xx
if res.StatusCode/100 == 2 {
return res, nil
}
var apiError ApiError
// ReadAll is usually a bad practice, but here we need to read the response all
// at once because we may attempt to use the data twice. It's preferable to use
// methods that take io.Reader, e.g. json.NewDecoder
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &apiError)
if err != nil {
// If deserializing into ApiError fails, return a generic HttpError instead
return nil, HttpError{res.StatusCode, string(body[:])}
}
apiError.HttpStatusCode = res.StatusCode
return nil, apiError
} | csn |
Updates the gutter markers for the specified range
@param {!CodeMirror} cm the CodeMirror instance for the active editor
@param {!number} from the starting line for the update
@param {!number} to the ending line for the update | function updateFoldInfo(cm, from, to) {
var minFoldSize = prefs.getSetting("minFoldSize") || 2;
var opts = cm.state.foldGutter.options;
var fade = prefs.getSetting("hideUntilMouseover");
var $gutter = $(cm.getGutterElement());
var i = from;
function clear(m) {
return m.clear();
}
/**
* @private
* helper function to check if the given line is in a folded region in the editor.
* @param {number} line the
* @return {Object} the range that hides the specified line or undefine if the line is not hidden
*/
function _isCurrentlyFolded(line) {
var keys = Object.keys(cm._lineFolds), i = 0, range;
while (i < keys.length) {
range = cm._lineFolds[keys[i]];
if (range.from.line < line && range.to.line >= line) {
return range;
}
i++;
}
}
/**
This case is needed when unfolding a region that does not cause the viewport to change.
For instance in a file with about 15 lines, if some code regions are folded and unfolded, the
viewport change event isn't fired by CodeMirror. The setTimeout is a workaround to trigger the
gutter update after the viewport has been drawn.
*/
if (i === to) {
window.setTimeout(function () {
var vp = cm.getViewport();
updateFoldInfo(cm, vp.from, vp.to);
}, 200);
}
while (i < to) {
var sr = _isCurrentlyFolded(i), // surrounding range for the current line if one exists
range;
var mark = marker("CodeMirror-foldgutter-blank");
var pos = CodeMirror.Pos(i, 0),
func = opts.rangeFinder || CodeMirror.fold.auto;
// don't look inside collapsed ranges
if (sr) {
i = sr.to.line + 1;
} else {
range = cm._lineFolds[i] || (func && func(cm, pos));
if (!fade || (fade && $gutter.is(":hover"))) {
if (cm.isFolded(i)) {
// expand fold if invalid
if (range) {
mark = marker(opts.indicatorFolded);
} else {
cm.findMarksAt(pos).filter(isFold)
.forEach(clear);
}
} else {
if (range && range.to.line - range.from.line >= minFoldSize) {
mark = marker(opts.indicatorOpen);
}
}
}
cm.setGutterMarker(i, opts.gutter, mark);
i++;
}
}
} | csn |
Write the point options of Elements
@return options as JSON object
@throws java.io.IOException If an I/O error occurs | public String encode() throws IOException {
FastStringWriter fsw = new FastStringWriter();
try {
ChartUtils.writeDataValue(fsw, "radius", this.radius, false);
ChartUtils.writeDataValue(fsw, "pointStyle", this.pointStyle, true);
ChartUtils.writeDataValue(fsw, "backgroundColor", this.backgroundColor, true);
ChartUtils.writeDataValue(fsw, "borderWidth", this.borderWidth, true);
ChartUtils.writeDataValue(fsw, "borderColor", this.borderColor, true);
ChartUtils.writeDataValue(fsw, "hitRadius", this.hitRadius, true);
ChartUtils.writeDataValue(fsw, "hoverRadius", this.hoverRadius, true);
ChartUtils.writeDataValue(fsw, "hoverBorderWidth", this.hoverBorderWidth, true);
}
finally {
fsw.close();
}
return fsw.toString();
} | csn |
Initialize the properties of the scene.
800x600 with transparent background and a Region as Parent Node
@return the scene built
@throws CoreException if build fails | protected final Scene buildScene() throws CoreException {
final Scene scene = new Scene(buildRootPane(),
StageParameters.APPLICATION_SCENE_WIDTH.get(),
StageParameters.APPLICATION_SCENE_HEIGHT.get(),
JRebirthColors.SCENE_BG_COLOR.get());
return scene;
} | csn |
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised. | def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised.
"""
try:
# Try naïve conversion
return type_(value)
except:
pass
# Try with the typing hints
for _, t in get_type_hints(type_).items():
try:
return type_(l.load(value, t))
except:
pass
raise TypedloadValueError(
'Value could not be loaded into %s' % type_,
value=value,
type_=type_
) | csn |
Handling other not caught exceptions.
@param \OxidEsales\Eshop\Core\Exception\StandardException $exception | protected function _handleBaseException($exception)
{
$this->logException($exception);
if ($this->_isDebugMode()) {
\OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($exception);
$this->_process('exceptionError', 'displayExceptionError');
}
} | csn |
// SortedKeys returns a slice containing the sorted keys of map m. Argument t
// is the type implementing sort.Interface which is used to sort. | func SortedKeys(m interface{}, t reflect.Type) interface{} {
v := reflect.ValueOf(m)
if v.Kind() != reflect.Map {
panic("wrong type")
}
s := reflect.MakeSlice(reflect.SliceOf(v.Type().Key()), v.Len(), v.Len())
for i, k := range v.MapKeys() {
s.Index(i).Set(k)
}
s = s.Convert(t)
sort.Sort(s.Interface().(sort.Interface))
return s.Interface()
} | csn |
Load refresh token details by token
@param string $refresh_token Refresh token
@return array Refresh token details | public function getRefreshToken($refresh_token)
{
// create refresh token
$token = \Components\Developer\Models\Refreshtoken::oneByToken($refresh_token);
// make sure we have a token
if (!$token->get('id'))
{
return false;
}
// make sure its a published token
if (!$token->isPublished())
{
return false;
}
// get the application's client id
$application = \Components\Developer\Models\Application::oneOrFail($token->get('application_id'));
$token->set('client_id', $application->get('client_id'));
// format expires to unix timestamp
$token->set('expires', with(new Date($token->get('expires')))->toUnix());
// return token
return $token->toArray();
} | csn |
Enqueues markup to be rendered and inserted at a supplied index.
@param {string} parentID ID of the parent component.
@param {string} markup Markup that renders into an element.
@param {number} toIndex Destination index.
@private | function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex: toIndex
});
} | csn |
Builds the item from provided search hit. | private function buildItem(SearchHit $searchHit): Item
{
/** @var \eZ\Publish\API\Repository\Values\Content\Location $location */
$location = $searchHit->valueObject;
/** @var \eZ\Publish\API\Repository\Values\Content\Content $content */
$content = $this->repository->sudo(
static function (Repository $repository) use ($location): Content {
return $repository->getContentService()->loadContentByContentInfo(
$location->contentInfo
);
}
);
return new Item(
$location,
$content,
$this->config->getItemType() === 'ezlocation' ?
$location->id :
$location->contentInfo->id,
$this->isSelectable($content)
);
} | csn |
Retrieve an indexed element and return it as a Double.
@param index An integer value specifying the offset from the beginning of the array.
@return The element as a Double, or null if the element is not found. | public Double getDouble (int index) {
String string = getString (index);
return (string != null) ? Double.parseDouble (string) : null;
} | csn |
Return the patch | def patch(self):
"""Return the patch"""
resp = self._get(self._api,
headers={'Accept': 'application/vnd.github.patch'})
return resp.content if self._boolean(resp, 200, 404) else None | csn |
Delete my locks.
@return ResultResponse
@Route("/deletemy", name="locks_delete_my") | public function deletemyAction()
{
$uid = $this->getUser()->getId();
$lockManager = $this->get('phlexible_element.element_lock_manager');
$myLocks = $lockManager->findBy(['userId' => $uid]);
foreach ($myLocks as $lock) {
$lockManager->deleteLock($lock);
}
return new ResultResponse(true, 'My locks released.');
} | csn |
Gets the value of the dispQuoteOrSpeechOrStatement property.
<p>
This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a <CODE>set</CODE> method for the dispQuoteOrSpeechOrStatement property.
<p>
For example, to add a new item, do as follows:
<pre>
getDispQuoteOrSpeechOrStatement().add(newItem);
</pre>
<p>
Objects of the following type(s) are allowed in the list
{@link DispQuote }
{@link Speech }
{@link Statement }
{@link VerseGroup }
{@link DefList }
{@link ch.epfl.bbp.uima.xml.archivearticle3.List }
{@link Alternatives }
{@link ChemStructWrap }
{@link Graphic }
{@link Media }
{@link Preformat }
{@link Table } | public java.util.List<Object> getDispQuoteOrSpeechOrStatement() {
if (dispQuoteOrSpeechOrStatement == null) {
dispQuoteOrSpeechOrStatement = new ArrayList<Object>();
}
return this.dispQuoteOrSpeechOrStatement;
} | csn |
// Get returns the current merkle root, and the server timestamp of
// that root. To help avoid having too frequent calls into the API
// server, caller can provide a positive tolerance, to accept stale
// LimitBytes and UsageBytes data. If tolerance is 0 or negative, this
// always makes a blocking RPC to bserver and return latest quota
// usage.
//
// 1) If the age of cached data is more than blockTolerance, a blocking RPC is
// issued and the function only returns after RPC finishes, with the newest
// data from RPC. The RPC causes cached data to be refreshed as well.
// 2) Otherwise, if the age of cached data is more than bgTolerance,
// a background RPC is spawned to refresh cached data, and the stale
// data is returned immediately.
// 3) Otherwise, the cached stale data is returned immediately. | func (ecmr *EventuallyConsistentMerkleRoot) Get(
ctx context.Context, bgTolerance, blockTolerance time.Duration) (
timestamp time.Time, root keybase1.MerkleRootV2,
rootTime time.Time, err error) {
c := ecmr.getCached()
err = ecmr.fetcher.Do(ctx, bgTolerance, blockTolerance, c.timestamp)
if err != nil {
return time.Time{}, keybase1.MerkleRootV2{}, time.Time{}, err
}
c = ecmr.getCached()
return c.timestamp, c.root, c.rootTime, nil
} | csn |
Static factory method to create a new client instance.
This method produces a client connected to the supplied addresses.
@param addresses one or more addresses to connect to.
@return a new RiakClient instance.
@throws java.net.UnknownHostException if a supplied hostname cannot be resolved. | public static RiakClient newClient(InetSocketAddress... addresses) throws UnknownHostException
{
final List<String> remoteAddresses = new ArrayList<>(addresses.length);
for (InetSocketAddress addy : addresses)
{
remoteAddresses.add(
String.format("%s:%s", addy.getHostName(), addy.getPort())
);
}
return newClient(createDefaultNodeBuilder(), remoteAddresses);
} | csn |
// openDev find and open an interface. | func openDev(config Config) (ifce *Interface, err error) {
// find the device in registry.
deviceid, err := getdeviceid(config.PlatformSpecificParams.ComponentID, config.PlatformSpecificParams.InterfaceName)
if err != nil {
return nil, err
}
path := "\\\\.\\Global\\" + deviceid + ".tap"
pathp, err := syscall.UTF16PtrFromString(path)
if err != nil {
return nil, err
}
// type Handle uintptr
file, err := syscall.CreateFile(pathp, syscall.GENERIC_READ|syscall.GENERIC_WRITE, uint32(syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE), nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_SYSTEM|syscall.FILE_FLAG_OVERLAPPED, 0)
// if err hanppens, close the interface.
defer func() {
if err != nil {
syscall.Close(file)
}
if err := recover(); err != nil {
syscall.Close(file)
}
}()
if err != nil {
return nil, err
}
var bytesReturned uint32
// find the mac address of tap device, use this to find the name of interface
mac := make([]byte, 6)
err = syscall.DeviceIoControl(file, tap_win_ioctl_get_mac, &mac[0], uint32(len(mac)), &mac[0], uint32(len(mac)), &bytesReturned, nil)
if err != nil {
return nil, err
}
// fd := os.NewFile(uintptr(file), path)
ro, err := newOverlapped()
if err != nil {
return
}
wo, err := newOverlapped()
if err != nil {
return
}
fd := &wfile{fd: file, ro: ro, wo: wo}
ifce = &Interface{isTAP: (config.DeviceType == TAP), ReadWriteCloser: fd}
// bring up device.
if err := setStatus(file, true); err != nil {
return nil, err
}
//TUN
if config.DeviceType == TUN {
if err := setTUN(file, config.PlatformSpecificParams.Network); err != nil {
return nil, err
}
}
// find the name of tap interface(u need it to set the ip or other command)
ifces, err := net.Interfaces()
if err != nil {
return
}
for _, v := range ifces {
if bytes.Equal(v.HardwareAddr[:6], mac[:6]) {
ifce.name = v.Name
return
}
}
return nil, errIfceNameNotFound
} | csn |
Return the service as a JSON string. | def as_text(self, is_pretty=False):
"""Return the service as a JSON string."""
values = {
'type': self._type,
self.SERVICE_ENDPOINT: self._service_endpoint,
}
if self._consume_endpoint is not None:
values[self.CONSUME_ENDPOINT] = self._consume_endpoint
if self._values:
# add extra service values to the dictionary
for name, value in self._values.items():
values[name] = value
if is_pretty:
return json.dumps(values, indent=4, separators=(',', ': '))
return json.dumps(values) | csn |
Start capturing and bundling current output.
@param array $options
@return Bundle | public function start(array $options = array())
{
$currentBundleOptions = array(
'docroot' => $this->getDocRoot(),
'bypass' => $this->getBypass()
);
$this->currentBundleOptions = array_merge($currentBundleOptions, $options);
ob_start();
return $this;
} | csn |
assign a value to a visible Field of a object
@param obj Object to assign value to his property
@param prop name of property
@param value Value to assign
@throws PageException | public static boolean setField(Object obj, String prop, Object value) throws PageException {
Class clazz = value.getClass();
try {
Field[] fields = getFieldsIgnoreCase(obj.getClass(), prop);
// exact comparsion
for (int i = 0; i < fields.length; i++) {
if (toReferenceClass(fields[i].getType()) == clazz) {
fields[i].set(obj, value);
return true;
}
}
// like comparsion
for (int i = 0; i < fields.length; i++) {
if (like(fields[i].getType(), clazz)) {
fields[i].set(obj, value);
return true;
}
}
// convert comparsion
for (int i = 0; i < fields.length; i++) {
try {
fields[i].set(obj, convert(value, toReferenceClass(fields[i].getType()), null));
return true;
}
catch (PageException e) {}
}
}
catch (Exception e) {
throw Caster.toPageException(e);
}
return false;
} | csn |
//GetIndex returns the ActionInterface at the index or nil
//supports negative indexing | func (a *ActDepend) getIndex(ind int) ActionInterface {
ind, ok := a.correctIndex(ind)
if !ok {
return nil
}
return a.waiters[ind]
} | csn |
// Send emits the given message on the 'Out' channel. the send Timesout after 100 ms in order to chaeck of the Pipe has stopped and we've been asked to exit.
// If the Pipe has been stopped, the send will fail and there is no guarantee of either success or failure | func (p *Pipe) Send(msg message.Msg, off offset.Offset) {
p.MessageCount++
for _, ch := range p.Out {
A:
for {
select {
case ch <- TrackedMessage{msg, off}:
break A
}
}
}
} | csn |
// List selects resources in the storage which match to the selector. | func (r *REST) List(ctx context.Context, options *metainternalversion.ListOptions) (runtime.Object, error) {
// populate the label selector, defaulting to all
metricSelector := labels.Everything()
if options != nil && options.LabelSelector != nil {
metricSelector = options.LabelSelector
}
namespace := genericapirequest.NamespaceValue(ctx)
requestInfo, ok := request.RequestInfoFrom(ctx)
if !ok {
return nil, fmt.Errorf("unable to get resource and metric name from request")
}
metricName := requestInfo.Resource
return r.emProvider.GetExternalMetric(namespace, metricSelector, provider.ExternalMetricInfo{Metric: metricName})
} | csn |
Retrieves all invoices from Xero
Usage : get_invoices
get_invoices(:invoice_id => "297c2dc5-cc47-4afd-8ec8-74990b8761e9")
get_invoices(:invoice_number => "175")
get_invoices(:contact_ids => ["297c2dc5-cc47-4afd-8ec8-74990b8761e9"] )
Note : modified_since is in UTC format (i.e. Brisbane is UTC+10) | def get_invoices(options = {})
request_params = {}
request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id]
request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number]
request_params[:order] = options[:order] if options[:order]
request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since]
request_params[:IDs] = Array(options[:invoice_ids]).join(",") if options[:invoice_ids]
request_params[:InvoiceNumbers] = Array(options[:invoice_numbers]).join(",") if options[:invoice_numbers]
request_params[:ContactIDs] = Array(options[:contact_ids]).join(",") if options[:contact_ids]
request_params[:page] = options[:page] if options[:page]
request_params[:where] = options[:where] if options[:where]
response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'})
end | csn |
// NewKeyedBlake2B returns a new 512-bit BLAKE2B hash with the given secret key. | func NewKeyedBlake2B(key []byte) hash.Hash {
return New(&Config{Size: 64, Key: key})
} | csn |
Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
"WWPN":{
},
"MAC":{
}
},
"BootProtocol":{
},
"BootPriority":{
},
"FCBootEnvironment":{
}
} | def get_json(self):
"""Create FC port.
:returns: JSON for FC port as follows:
{
"@PortIdx":1,
"PortEnable":{
},
"UseVirtualAddresses":{
},
"VirtualAddress":{
"WWNN":{
},
"WWPN":{
},
"MAC":{
}
},
"BootProtocol":{
},
"BootPriority":{
},
"FCBootEnvironment":{
}
}
"""
port = self.get_basic_json()
port.update({
'BootProtocol': self.boot.BOOT_PROTOCOL,
'BootPriority': self.boot.boot_prio,
})
boot_env = self.boot.get_json()
if boot_env:
port.update(boot_env)
if self.use_virtual_addresses:
addresses = {}
if self.wwnn:
addresses['WWNN'] = self.wwnn
if self.wwpn:
addresses['WWPN'] = self.wwpn
if addresses:
port['VirtualAddress'] = addresses
return port | csn |
Returns first route annotation for method.
@param \ReflectionMethod $reflectionMethod
@return RouteAnnotation[] | private function readRouteAnnotation(\ReflectionMethod $reflectionMethod)
{
$annotations = [];
if ($newAnnotations = $this->readMethodAnnotations($reflectionMethod, 'Route')) {
$annotations = array_merge($annotations, $newAnnotations);
}
return $annotations;
} | csn |
Formats an error message. | def xpatherror(self, file, line, no):
"""Formats an error message. """
libxml2mod.xmlXPatherror(self._o, file, line, no) | csn |
Determine when the next log rotation
should take place.
\param int $currentTime
Current time, as a UNIX timestamp.
\retval int
UNIX timestamp for the next log rotation. | protected function computeRollover($currentTime)
{
if ($this->when == 'MIDNIGHT') {
return strtotime("midnight + 1 day", $currentTime);
}
if (substr($this->when, 0, 1) == 'W') {
return strtotime(
"next " . self::$dayNames[$this->dayOfWeek],
$currentTime
);
}
return $currentTime + $this->interval;
} | csn |
Returns the Config in a format suitable for revealing to users.
@return A ConfigResponse of the current config. Passwords will be encrypted and the default login wil be removed. | @Override
public ConfigResponse<T> getConfigResponse() {
T config = this.config.get();
config = withoutDefaultLogin(config);
if (config instanceof PasswordsConfig<?>) {
config = ((PasswordsConfig<T>) config).withoutPasswords();
}
return new ConfigResponse<>(config, getConfigFileLocation(), configFileLocation);
} | csn |
Returns the thread context that was captured at the point when the task was submitted.
@param execProps execution properties for the persistent task.
@return the thread context that was captured at the point when the task was submitted.
@throws IOException
@throws ClassNotFoundException | public ThreadContextDescriptor deserializeThreadContext(Map<String, String> execProps) throws IOException, ClassNotFoundException {
return threadContextBytes == null ? null : ThreadContextDeserializer.deserialize(threadContextBytes, execProps);
} | csn |
// NewMockTransactional creates a new mock instance | func NewMockTransactional(ctrl *gomock.Controller) *MockTransactional {
mock := &MockTransactional{ctrl: ctrl}
mock.recorder = &MockTransactionalMockRecorder{mock}
return mock
} | csn |
Sets the tickmark sections of the gauge to the given array of section objects
@param TICKMARK_SECTIONS_ARRAY | public void setTickmarkSections(final Section... TICKMARK_SECTIONS_ARRAY) {
tickmarkSections.clear();
for (Section tickmarkSection : TICKMARK_SECTIONS_ARRAY) {
tickmarkSections.add(new Section(tickmarkSection.getStart(), tickmarkSection.getStop(), tickmarkSection.getColor()));
}
validate();
fireStateChanged();
} | csn |
Create shortcuts for this widget. | def create_shortcuts(self):
"""Create shortcuts for this widget."""
# Configurable
copyfig = config_shortcut(self.copy_figure, context='plots',
name='copy', parent=self)
prevfig = config_shortcut(self.go_previous_thumbnail, context='plots',
name='previous figure', parent=self)
nextfig = config_shortcut(self.go_next_thumbnail, context='plots',
name='next figure', parent=self)
return [copyfig, prevfig, nextfig] | csn |
// ChangeLogLevel changes Envoy log level to correspond to the logrus log level 'level'. | func (e *Envoy) ChangeLogLevel(level logrus.Level) {
e.admin.changeLogLevel(level)
} | csn |
Processes LTI tools element data
@param array|stdClass $data | public function process_enrol_lti_tool($data) {
global $DB;
$data = (object) $data;
// Store the old id.
$oldid = $data->id;
// Change the values before we insert it.
$data->timecreated = time();
$data->timemodified = $data->timecreated;
// Now we can insert the new record.
$data->id = $DB->insert_record('enrol_lti_tools', $data);
// Add the array of tools we need to process later.
$this->tools[$data->id] = $data;
// Set up the mapping.
$this->set_mapping('enrol_lti_tool', $oldid, $data->id);
} | csn |
read all text into memory. | def read_text(self, encoding='utf-8') -> str:
''' read all text into memory. '''
with self.open('r', encoding=encoding) as fp:
return fp.read() | csn |
Generates an empty class.
@param className The classes name.
@param superName The super object, which the class extends from.
@param interfaces The name of the interfaces which this class implements.
@param classModifiers The modifiers to the class.
@return A class writer that will be used to write the remaining information of the class. | static ClassWriter generateClass(String className, String superName, String[] interfaces, String signature, int classModifiers, String apiName) {
ClassWriter classWriter = new ClassWriter(0);
if (interfaces != null){
for (int i = 0; i < interfaces.length; i++) {
interfaces[i] = getFullClassTypeName(interfaces[i], apiName);
}
}
classWriter.visit(V1_8, classModifiers, getFullClassTypeName(className, apiName), signature, superName, interfaces);
return classWriter;
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.