query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Gives you attachment body as return value
@param int $attachmentID
@param array $options Additional Connection Options
@return string | public static function getAttachment($attachmentID,$options = [])
{
$result = null;
$downloader = new Priloha($attachmentID,$options);
if ($downloader->lastResponseCode == 200) {
$downloader->doCurlRequest(self::getDownloadURL($downloader), 'GET');
if ($downloade... | csn |
From list of bases at a site D, make counts of bases | def stack(S):
"""
From list of bases at a site D, make counts of bases
"""
S, nreps = zip(*S)
S = np.array([list(x) for x in S])
rows, cols = S.shape
counts = []
for c in xrange(cols):
freq = [0] * NBASES
for b, nrep in zip(S[:, c], nreps):
freq[BASES.index(b... | csn |
Center the given window within the screen boundaries.
@param window the window to be centered. | public static void centerWindow (Window window)
{
Rectangle bounds;
try {
bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().getBounds();
} catch (Throwable t) {
Toolkit tk = window.getToolkit... | csn |
Delete the published wsdl | public void unpublishWsdlFiles() throws IOException
{
String deploymentDir = (dep.getParent() != null ? dep.getParent().getSimpleName() : dep.getSimpleName());
File serviceDir = new File(serverConfig.getServerDataDir().getCanonicalPath() + "/wsdl/" + deploymentDir);
deleteWsdlPublishDirectory(serv... | csn |
// Base64 reads string from config file then decode using base64 | func (r *Reader) Base64(name string) []byte {
return r.Base64Default(name, []byte{})
} | csn |
// Connect returns the runhcs shim information | func (s *service) Connect(ctx context.Context, r *taskAPI.ConnectRequest) (*taskAPI.ConnectResponse, error) {
log.G(ctx).Debugf("Connect: %s", r.ID)
var taskpid uint32
p, _ := s.getProcess(r.ID, "")
if p != nil {
taskpid = p.stat().pid
}
return &taskAPI.ConnectResponse{
ShimPid: uint32(os.Getpid()),
TaskP... | csn |
create the directory if needed and configure it
:return: None | def initialize(self):
"""
create the directory if needed and configure it
:return: None
"""
if not self._initialized:
logger.info("initializing %r", self)
if not os.path.exists(self.path):
if self.mode is not None:
os.m... | csn |
Validate token or die.
@param bool $justDie
@param string $message
@return bool | public function validate($justDie = false, $message = 'Invalid Token')
{
if (!$this->checkToken()) {
if ($justDie) {
exit($message);
}
throw new InvalidTokenException($message);
}
return true;
} | csn |
Returns products main category id
@param \OxidEsales\Eshop\Application\Model\Article $oArticle product
@return string | protected function _getMainCategory($oArticle)
{
$oMainCat = null;
// if variant parent id must be used
$sArtId = $oArticle->getId();
if (isset($oArticle->oxarticles__oxparentid->value) && $oArticle->oxarticles__oxparentid->value) {
$sArtId = $oArticle->oxarticles__oxpar... | csn |
// GetXtructs returns the value of Xtructs if it is set or its
// zero value if it is unset. | func (v *Insanity) GetXtructs() (o []*Xtruct) {
if v != nil && v.Xtructs != nil {
return v.Xtructs
}
return
} | csn |
If this collection has already been initialized with
an identical criteria, it returns the collection.
Otherwise if this Category is new, it will return
an empty collection; or if this Category has previously
been saved, it will retrieve related C2Ms from storage.
This method is protected by default in order to keep t... | public function getC2MsJoinMedia(Criteria $criteria = null, ConnectionInterface $con = null, $joinBehavior = Criteria::LEFT_JOIN)
{
$query = ChildC2MQuery::create(null, $criteria);
$query->joinWith('Media', $joinBehavior);
return $this->getC2Ms($query, $con);
} | csn |
Create a new clientModelDoc
@param {Object} clientModelDoc - clientModelDocData
@param {Function} callback - optional
@return {Promise} | function update(clientModelDoc, callback) {
var cb = callback || angular.noop;
return ClientModelDoc.update(clientModelDoc,
function (clientModelDoc) {
return cb(clientModelDoc);
},
function (err) {
return cb(err);
}).$promise;
} | csn |
Build response payload array based on configured format.
@param mixed $message
@param array $format
@return array | public function format($message, array $format)
{
$replace = [
':message' => $message,
':code' => $this->getStatusCode(),
];
array_walk_recursive($format, function (&$value, $key) use ($replace) {
if (isset($replace[$value])) {
$value = $r... | csn |
Move progress forward and redraws the progressbar. | public function advance(): void
{
$this->progress++;
if($this->progress === $this->items || ($this->progress % $this->redrawRate) === 0)
{
$this->draw();
}
} | csn |
Aside from looking into our own, consult other facets that can handle Jelly-compatible scripts. | @Override
public Script resolveScript(String name) throws JellyException {
// cut off the extension so that we can search all the extensions
String shortName;
int dot = name.lastIndexOf('.');
if (dot>name.lastIndexOf('/')) shortName = name.substring(0, dot);
else ... | csn |
//Dump the object to file in toml format | func Dump(file string, v interface{}) error {
b, err := Marshal(v)
if err != nil {
return err
}
return ioutil.WriteFile(file, b, 0644)
} | csn |
Convert the header set into an HTTP header string. | def to_header(self):
"""Convert the header set into an HTTP header string."""
result = []
for value, quality in self:
if quality != 1:
value = '%s;q=%s' % (value, quality)
result.append(value)
return ','.join(result) | csn |
Does a pretty job printing a Fisher mean and associated statistics for
directional data.
Parameters
----------
mean_dictionary: output dictionary of pmag.fisher_mean
Examples
--------
Generate a Fisher mean using ``ipmag.fisher_mean`` and then print it nicely
using ``ipmag.print_direct... | def print_direction_mean(mean_dictionary):
"""
Does a pretty job printing a Fisher mean and associated statistics for
directional data.
Parameters
----------
mean_dictionary: output dictionary of pmag.fisher_mean
Examples
--------
Generate a Fisher mean using ``ipmag.fisher_mean`` ... | csn |
Truncates all the clusters the class uses.
@throws IOException | public void truncate() throws IOException {
getDatabase().checkSecurity(ODatabaseSecurityResources.CLASS, ORole.PERMISSION_UPDATE);
getDatabase().getStorage().callInLock(new Callable<Object>() {
public Object call() throws Exception {
for (int id : clusterIds) {
getDatabase().getS... | csn |
Set the name of the form.
@param string $name
@param bool $rebuild
@return $this | public function setName($name, $rebuild = true)
{
$this->name = $name;
if ($rebuild) {
$this->rebuildForm();
}
return $this;
} | csn |
This method sets a property on an object via reflection.
@param object The object on which the property is to be set.
@param property The name of the property to be set.
@param propertyType The type of the property being set.
@param value The value of the property being set. | public static void setProperty(final Object object, final String property,
final Class propertyType, final Object value) {
Class[] paramTypes = new Class[]{propertyType};
Object[] params = new Object[]{value};
String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
Reflec... | csn |
Parses and convert to protocol timezone a dateTimeTimeZone resource
This resource is a dict with a date time and a windows timezone
This is a common structure on Microsoft apis so it's included here. | def _parse_date_time_time_zone(self, date_time_time_zone):
""" Parses and convert to protocol timezone a dateTimeTimeZone resource
This resource is a dict with a date time and a windows timezone
This is a common structure on Microsoft apis so it's included here.
"""
if date_time_... | csn |
Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None | def create_button(self, widget):
"""Create a button that has the given widget rendered as an icon
:param widget: the widget to render as icon
:type widget: QtGui.QWidget
:returns: the created button
:rtype: QtGui.QAbstractButton
:raises: None
"""
btn = Qt... | csn |
Passwordless self-registration.
This byway registration doesn't differ sign in and sign up.
Use this with caution, e.g. with proper authentication via
OAuth*, SMTP or the like. Unlike add user with password, this
also returns `sid` to associate `session.sid` with a column
on different table.
@param array $args Dict o... | public function adm_self_add_user_passwordless($args) {
if ($this->store_is_logged_in())
return [AdminStoreError::USER_ALREADY_LOGGED_IN];
# check vars
if (!isset($args['service']))
return [AdminStoreError::DATA_INCOMPLETE];
$uname = $uservice = null;
$service = Common::check_idict($args['service'],
... | csn |
handle fencepoint move | def cmd_fence_move(self, args):
'''handle fencepoint move'''
if len(args) < 1:
print("Usage: fence move FENCEPOINTNUM")
return
if not self.have_list:
print("Please list fence points first")
return
idx = int(args[0])
if idx <= 0 or ... | csn |
// CheckMdsAvailability checks whether a local metadata service can be reached. | func CheckMdsAvailability() error {
if conn, err := net.Dial("unix", common.MetadataServiceRegSock); err != nil {
return errUnreachable
} else {
conn.Close()
return nil
}
} | csn |
Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items. | def _distro_release_info(self):
"""
Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items.
"""
if self.distro_release_file:
# If it was specified, we use it and parse what we can, even if
... | csn |
Generates an emphasized text.
@param string $text the text to emphasize.
@param array $htmlOptions additional HTML attributes.
@param string $tag the HTML tag.
@return string the generated text. | public static function em($text, $htmlOptions = array(), $tag = 'p')
{
$color = TbArray::popValue('color', $htmlOptions);
if (TbArray::popValue('muted', $htmlOptions, false)) {
self::addCssClass('muted', $htmlOptions);
} else {
if (!empty($color)) {
se... | csn |
since this method is a wrapper for the tryReconnect only limited
we set a max amount of retries.
increase the counter and reconnect
as often as defined
@return bool | public function reconnect()
{
if ($this->getMaxReconnects() < $this->getReconnectCount()) {
return false;
}
$this->increaseReconnectCount();
// returns the state if the ping was possible
return $this->ping();
} | csn |
// NewOperandTypeErr returns an operand error indicating the operand's type was wrong. | func NewOperandTypeErr(pos int, got ast.Value, expected ...string) error {
if len(expected) == 1 {
return NewOperandErr(pos, "must be %v but got %v", expected[0], ast.TypeName(got))
}
return NewOperandErr(pos, "must be one of {%v} but got %v", strings.Join(expected, ", "), ast.TypeName(got))
} | csn |
Run `cmd` as a check on `paths`. | def _check_std(self, paths, cmd_pieces):
"""
Run `cmd` as a check on `paths`.
"""
cmd_pieces.extend(paths)
process = Popen(cmd_pieces, stdout=PIPE, stderr=PIPE)
out, err = process.communicate()
lines = out.strip().splitlines() + err.strip().splitlines()
re... | csn |
Convert an info_frags.txt file into a fasta file given a reference.
Optionally adds junction sequences to reflect the possibly missing base
pairs between two newly joined scaffolds. | def write_fasta(
init_fasta, info_frags, output=DEFAULT_NEW_GENOME_NAME, junction=False
):
"""Convert an info_frags.txt file into a fasta file given a reference.
Optionally adds junction sequences to reflect the possibly missing base
pairs between two newly joined scaffolds.
"""
init_genome = ... | csn |
Finds a target compiler supporting the given target.
@param mixed $target The target to filter.
@param string $mode The execution mode (MODE_FILTER or MODE_SATISFIES).
@throws TargetUnsupportedException | private function findTargetCompiler($target, $mode): CompilationTarget
{
/** @var CompilationTarget $targetCompiler */
foreach ($this->compilationTargets as $targetCompiler) {
if ($targetCompiler->supports($target, $mode)) {
return $targetCompiler;
}
}... | csn |
// Error returns a detailed error string including the exact transaction that
// caused an invalid htlc signature. | func (i *InvalidHtlcSigError) Error() string {
return fmt.Sprintf("rejected commitment: commit_height=%v, "+
"invalid_htlc_sig=%x, commit_tx=%x, sig_hash=%x", i.commitHeight,
i.htlcSig, i.commitTx, i.sigHash[:])
} | csn |
Prepend num zeros onto the beginning of this TimeSeries. Update also
epoch to include this prepending. | def prepend_zeros(self, num):
"""Prepend num zeros onto the beginning of this TimeSeries. Update also
epoch to include this prepending.
"""
self.resize(len(self) + num)
self.roll(num)
self._epoch = self._epoch - num * self._delta_t | csn |
Applies the list of patches as DOM updates.
@param {Array} patches | function executePatch(patches) {
for (let i = 0; i < patches.length; i++) {
const patch = patches[i];
switch (patch.type) {
case patchTypes.updateText: {
// Update text of a node with new text.
const nodeOld = patch.nodeOld;
const nodeNew = patch.nodeNew;
nodeOld.element.textContent = nodeNew.... | csn |
// CreateResource constructs, validates, and returns a resource URL string. An
// error will be returned if unable to create the resource string. | func CreateResource(scheme, u string) (string, error) {
scheme = strings.ToLower(scheme)
if scheme == "http" || scheme == "https" || scheme == "http*" || scheme == "*" {
return u, nil
}
if scheme == "rtmp" {
parsed, err := url.Parse(u)
if err != nil {
return "", fmt.Errorf("unable to parse rtmp URL, err:... | csn |
Set the list of words that should be considered as optional when found in
the query.
@param words The list of optional words. | public Query setOptionalWords(List<String> words) {
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
builder.append(",");
}
this.optionalWords = builder.toString();
return this;
} | csn |
Loads a specific plugin instance.
@param string $type
The type of the plugin to be loaded.
@param string $file
The fully qualified path of the plugin to be loaded. | static protected function load($type, $file) {
include $file;
switch ($type) {
case 'filters':
self::$objects['filters'][] = $filter;
break;
case 'functions':
self::$objects['functions'][] = $function;
break;
case 'tags':
if (preg_match('/^([^\.]+)\.tag\... | csn |
Get the parent class or interface listeners for the event.
@param object $event
@return array | protected function getParentListeners($event)
{
$parentListeners = [];
foreach ($this->listeners as $key => $listeners)
{
if ($event instanceof $key)
{
$parentListeners = array_merge($parentListeners, $listeners);
}
}
retu... | csn |
Run apropriate check based on `file`'s extension and return it,
otherwise raise an Error | def _check(self, file):
"""
Run apropriate check based on `file`'s extension and return it,
otherwise raise an Error
"""
if not os.path.exists(file):
raise Error("file \"{}\" not found".format(file))
_, extension = os.path.splitext(file)
try:
... | csn |
// EmptyEnvs empties the environment variables for a pod | func (p *Pod) EmptyEnvs() *Pod {
p.Env = make(map[string]string)
return p
} | csn |
Returns the value associated with the given config option as a boolean.
If no value is mapped under any key of the option, it returns the specified
default instead of the option's default value.
@param configOption The configuration option
@param overrideDefault The value to return if no value was mapper for any key o... | @PublicEvolving
public boolean getBoolean(ConfigOption<Boolean> configOption, boolean overrideDefault) {
Object o = getRawValueFromOption(configOption);
if (o == null) {
return overrideDefault;
}
return convertToBoolean(o);
} | csn |
Interactively change the intensity map by scrolling. | def sc_imap(self, viewer, event, msg=True):
"""Interactively change the intensity map by scrolling.
"""
direction = self.get_direction(event.direction)
self._cycle_imap(viewer, msg, direction=direction)
return True | csn |
version of doQuery that takes a Hash of parameters | def _doQueryHash( doQueryOptions )
doQueryOptions ||= {}
raise "options must be a Hash" unless doQueryOptions.is_a?(Hash)
doQueryOptions["dbid"] ||= @dbid
doQueryOptions["fmt"] ||= "structured"
doQuery( doQueryOptions["dbid"],
doQueryOptions["query"],
... | csn |
// IsValidName returns if the name of the lxd profile looks valid. | func IsValidName(name string) bool {
// doesn't contain the prefix
if !strings.HasPrefix(name, Prefix) {
return false
}
// it's required to have at least the following chars `x-x-0`
suffix := name[len(Prefix):]
if len(suffix) < 5 {
return false
}
// lastly check the last part is a number
lastHyphen := stri... | csn |
End position of code to replace.
@return [Integer] end position. | def end_pos
node_begin_pos = @node.loc.expression.begin_pos
node_begin_pos += @node.loc.expression.source.index "do"
while @node.loc.expression.source_buffer.source[node_begin_pos += 1] != '@'
end
node_begin_pos
end | csn |
Return the event data parsed into the given type.
@param type type token to parse data
@param <R> type to parse the data into
@return the event data | public <R> R getData(TypeToken<R> type) {
return GSON.fromJson(data, type.getType());
} | csn |
// matchesClusterNameMultipart checks if the name could have been generated by our cluster
// considering all the prefixes separated by `-`. maxParts limits the number of parts we consider. | func (d *clusterDiscoveryGCE) matchesClusterNameMultipart(name string, maxParts int) bool {
tokens := strings.Split(name, "-")
for i := 1; i <= maxParts; i++ {
if i > len(tokens) {
break
}
id := strings.Join(tokens[:i], "-")
if id == "" {
continue
}
if name == gce.SafeObjectName(id, d.clusterName)... | csn |
Normalizes a DateTime to a string.
@param \DateTime|null $date
@return string|null | public static function normalize(\DateTime $date = null)
{
if (!empty($date)) {
return $date->format(static::DATE_FORMAT);
}
return null;
} | csn |
Sends a text message using this object's websocket session.
@param message json binary message | public void sendMessage(final String message) {
try {
session.sendMessage(new TextMessage(message));
}
catch (IOException e) {
logger.error("[sendTextMessage]", e);
}
} | csn |
Gets a unit vector parallel to input vector | def get_uvec(vec):
""" Gets a unit vector parallel to input vector"""
l = np.linalg.norm(vec)
if l < 1e-8:
return vec
return vec / l | csn |
Validates response body
@param [Object] response
@raise [Exceptions::Validation] When there is a missing required header.. | def validate_body!(response)
return unless media_type
return if media_type.kind_of? SimpleMediaType
errors = self.media_type.validate(self.media_type.load(response.body))
if errors.any?
message = "Invalid response body for #{media_type.identifier}." +
"Errors: #{errors.inspect... | csn |
Parse scheme.
@param UrlInterface|null $baseUrl The base url or null if no base url is present.
@param string|null $schemeString The scheme that is to be parsed or null if no scheme is present.
@param SchemeInterface|null $scheme The scheme if parsing was successful, undefined otherwise.
@param ... | private static function myParseScheme(?UrlInterface $baseUrl = null, ?string $schemeString, ?SchemeInterface &$scheme = null, ?string &$error = null): bool
{
if ($schemeString === null) {
if ($baseUrl === null) {
$error = 'Scheme is missing.';
return false;
... | csn |
Returns the map with a marker to the default map | def marker_(self, lat, long, text, pmap, color=None, icon=None):
"""
Returns the map with a marker to the default map
"""
try:
xmap = self._marker(lat, long, text, pmap, color, icon)
return xmap
except Exception as e:
self.err(e, self.marker_, ... | csn |
// Done lets Throttler know that a job has been completed so that another worker
// can be activated. If Done is called less times than totalJobs,
// Throttle will block forever | func (t *Throttler) Done(err error) {
if err != nil {
t.errsMutex.Lock()
t.errs = append(t.errs, err)
atomic.AddInt32(&t.errorCount, 1)
t.errsMutex.Unlock()
}
t.doneChan <- struct{}{}
} | csn |
Gets a binding for an interface
@param string $interface The interface whose binding we want
@return IBinding|null The binding if one exists, otherwise null | protected function getBinding(string $interface)
{
// If there's a targeted binding, use it
if ($this->currentTarget !== self::$emptyTarget && isset($this->bindings[$this->currentTarget][$interface])) {
return $this->bindings[$this->currentTarget][$interface];
}
// If th... | csn |
Test if an object is shallowly equal. | function shallowEqual(actual, expected) {
var keys = Object.keys(expected);
var _arr2 = keys;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var key = _arr2[_i2];
if (actual[key] !== expected[key]) {
return false;
}
}
return true;
} | csn |
Fix the name of an existing file to be used with php file functions
@param $file
@return String or null, if the file does not exist | public static function fixFilename($file) {
if (file_exists($file)) {
return $file;
}
else {
$file = iconv('utf-8', 'cp1252', $file);
if (file_exists($file)) {
return $file;
}
}
return null;
} | csn |
// notaryRoleToSigner converts TUF role name to a human-understandable signer name | func notaryRoleToSigner(tufRole data.RoleName) string {
// don't show a signer for "targets" or "targets/releases"
if isReleasedTarget(data.RoleName(tufRole.String())) {
return releasedRoleName
}
return strings.TrimPrefix(tufRole.String(), "targets/")
} | csn |
Converts an SQL time without time zone to a PHP date time
@param string $sqlTime The time to convert
@param Provider $provider The provider to convert from
@return DateTime|null The PHP time
@throws InvalidArgumentException Thrown if the input time couldn't be cast to a PHP time | public function fromSqlTimeWithoutTimeZone($sqlTime, Provider $provider = null)
{
if ($sqlTime === null) {
return null;
}
$this->setParameterProvider($provider);
$phpTime = DateTime::createFromFormat($provider->getTimeWithoutTimeZoneFormat(), $sqlTime);
if ($php... | csn |
Generate Module config
@param $module
@param $names
@param OutputInterface $output
@return mixed | public function createModuleClass($module, $names, OutputInterface $output)
{
$source = realpath(__DIR__ . '/../src/module.txt');
$file = file_get_contents($source);
$file = str_replace("!module", ucfirst($names), $file);
$file = str_replace("!date",date('d/m/Y'),$file);
$fil... | csn |
Creates a configuration with an annotation metadata driver.
@param array $paths
@param boolean $isDevMode
@param string $proxyDir
@param Cache $cache
@param bool $useSimpleAnnotationReader
@return Configuration | public static function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null, $useSimpleAnnotationReader = true)
{
$config = self::createConfiguration($isDevMode, $proxyDir, $cache);
$config->setMetadataDriverImpl($config->newDefaultAnnotationD... | csn |
Sends a message. This will automatically close the +message+ for both successful
and failed sends.
@param message
@param flag
One of @0 (default)@ and @XS::NonBlocking
@return 0 when the message was successfully enqueued
@return -1 under two conditions
1. The message could not be enqueued
2. When +flag+... | def send_and_close message, flag = 0
rc = sendmsg message, flag
message.close
rc
end | csn |
Get the default stores for all modes.
@return array An array containing sub-arrays, one for each mode. | public static function get_default_mode_stores() {
global $OUTPUT;
$instance = cache_config::instance();
$adequatestores = cache_helper::get_stores_suitable_for_mode_default();
$icon = new pix_icon('i/warning', new lang_string('inadequatestoreformapping', 'cache'));
$storenames =... | csn |
Returns list of callback call result for every object's key-value pair.
@param {object} object Any object can has properties.
@param {function(key, value)} callback
@param {*=} thisObject
@return {Array.<*>} | function iterate(object, callback, thisObject){
var result = [];
for (var key in object)
result.push(callback.call(thisObject, key, object[key]));
return result;
} | csn |
// installCompose download docker-compose from given url and saves to the specified path if it
// is not already installed. | func installCompose(path string, url string) error {
// Check if already installed at path.
if ok, err := util.PathExists(path); err != nil {
return err
} else if ok {
log.Printf("docker-compose is already installed at %s", path)
return nil
}
// Create dir if not exists
dir := filepath.Dir(path)
ok, err :... | csn |
Create a destination anchor in the `container` to direct links to
`flowable` to. | def create_destination(flowable, container, at_top_of_container=False):
"""Create a destination anchor in the `container` to direct links to
`flowable` to."""
vertical_position = 0 if at_top_of_container else container.cursor
ids = flowable.get_ids(container.document)
destination = NamedDestination(... | csn |
// FlatTypes returns the types in FunctionTypes as a flat slice of types. This allows for easier iteration in some applications | func (t *FunctionType) FlatTypes() Types {
retVal := BorrowTypes(8) // start with 8. Can always grow
retVal = retVal[:0]
if a, ok := t.a.(*FunctionType); ok {
ft := a.FlatTypes()
retVal = append(retVal, ft...)
ReturnTypes(ft)
} else {
retVal = append(retVal, t.a)
}
if b, ok := t.b.(*FunctionType); ok {
... | csn |
Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets. | def actualize_source_type (self, sources, prop_set):
""" Helper for 'actualize_sources'.
For each passed source, actualizes it with the appropriate scanner.
Returns the actualized virtual targets.
"""
assert is_iterable_typed(sources, VirtualTarget)
assert isinsta... | csn |
split_ints and merge_ints converts between string and integer array,
where the integer is right-padded until it fits a 256 bit integer. | def split_ints(secret)
result = []
secret.split('').map { |x|
data = x.unpack("H*")[0]
"0"*(data.size % 2) + data
}.join("").scan(/.{1,64}/) { |segment|
result.push (segment+"0"*(64-segment.size)).hex
}
return ... | csn |
This method writes the help to the console.
@param Command $command the command instance
@param Option $option optional option | public function write( Command $command, Option $option = NULL )
{
$output = PHP_EOL;
$output .= '-----------------------------------------------------' . PHP_EOL;
$output .= $command->name . ' ' . $command->version . PHP_EOL;
$output .= '---------------------------------------------... | csn |
// NewError returns an instance of an error. | func NewError(options ...func(*Error)) *Error {
err := &Error{}
for _, o := range options {
o(err)
}
return err
} | csn |
// GenerateOCSP is a mock | func (ca *MockCA) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {
return
} | csn |
Sitemap URLs discovered but not yet parsed
@return array | public function getQueue()
{
$this->queue = array_values(array_diff(array_unique(array_merge($this->queue, array_keys($this->sitemaps))), $this->history));
return $this->queue;
} | csn |
// New API client instance | func New(config Config) *Instance {
client := &Instance{
conf: &config,
clients: make(map[string]*fasthttp.HostClient),
clientsMu: new(sync.RWMutex),
balancer: newRangeBalancer(),
}
return client
} | csn |
// IsPointGetByUniqueKey checks whether is a point get by unique key. | func (p *PhysicalIndexScan) IsPointGetByUniqueKey(sc *stmtctx.StatementContext) bool {
return len(p.Ranges) == 1 &&
p.Index.Unique &&
len(p.Ranges[0].LowVal) == len(p.Index.Columns) &&
p.Ranges[0].IsPoint(sc)
} | csn |
Give external links the external class, and affix size and type prefixes to files.
@return String | public function Content()
{
$content = $this->owner->Content;
// Internal links.
$matches = array();
preg_match_all('/<a.*href="\[file_link,id=([0-9]+)\].*".*>.*<\/a>/U', $content, $matches);
for ($i = 0; $i < count($matches[0]); $i++) {
$file = DataObject::get_... | csn |
A KindName representing the kind of a missing symbol, given an
error kind. | public static KindName absentKind(int kind) {
switch (kind) {
case ABSENT_VAR:
return KindName.VAR;
case WRONG_MTHS: case WRONG_MTH: case ABSENT_MTH: case WRONG_STATICNESS:
return KindName.METHOD;
case ABSENT_TYP:
return KindName.CLASS;
default... | csn |
Attempt to guess the table name and "creation" status of the given migration.
@param string $migration
@return array | public static function guess($migration)
{
foreach (self::CREATE_PATTERNS as $pattern) {
if (preg_match($pattern, $migration, $matches)) {
return [$matches[1], $create = true];
}
}
foreach (self::CHANGE_PATTERNS as $pattern) {
if (preg_mat... | csn |
Returns current Event Date from Event or Reservation keys
@param key
@return | public static Date getEventDate(Key key)
{
Key ek = findAncestor(Repository.EVENT, key);
return new Date(ek.getId());
} | csn |
Converts emoticons shortcuts to images
@param string $str
@return string | public static function emoticonsToHtml($str)
{
$str = str_replace (" :)", ' <img src="/media/emot/icon_biggrin.gif" alt="big_grin" />', $str);
$str = str_replace (" :(", ' <img src="/media/emot/icon_cry.gif" alt="cry" />', $str);
$str = str_replace (" ;)", ' <img src="/media/emot/icon_wink... | csn |
called on change triggers set and modify if data keys are changed | function changeHandler(eventOptions = {}) {
const { key, silent } = eventOptions;
const def = defs.get(this);
if (key && key in def.keys && !silent) {
triggerOne(this, 'set', eventOptions);
triggerOne(this, 'modify', eventOptions);
}
} | csn |
Reset all auth fields.
@return $this | public function reset()
{
$this->token_type = '';
$this->access_token = '';
$this->expires_in = 0;
$this->expire_time = 0;
$this->refresh_token = '';
$this->refresh_token_expires_in = 0;
$this->refresh_token_expire_time = 0;
$this->scope = '';
... | csn |
When stopwatch is started, a new tree node is added to the parent
tree node and pushed on the call stack.
As a result, child tree node becomes the current tree node.
@return Current (child) tree node | public CallTreeNode onStopwatchStart(Split split) {
final String name = split.getStopwatch().getName();
CallTreeNode currentNode;
if (callStack.isEmpty()) {
// Root tree node
rootNode = new CallTreeNode(name);
currentNode = rootNode;
onRootStopwatchStart(currentNode, split);
} else {
// ... | csn |
Use the LineageRelatedByAncestorId relation Lineage object
@see useQuery()
@param string $relationAlias optional alias for the relation,
to be used as main alias in the secondary query
@param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
@return \gossi\trixionary\model\Li... | public function useLineageRelatedByAncestorIdQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
return $this
->joinLineageRelatedByAncestorId($relationAlias, $joinType)
->useQuery($relationAlias ? $relationAlias : 'LineageRelatedByAncestorId', '\gossi\trixionary\model\L... | csn |
Get a new_date = date + seconds.
Ignores Feb 29 for no-leap days. | def date_plus_seconds(init_date, seconds, caltype):
"""
Get a new_date = date + seconds.
Ignores Feb 29 for no-leap days.
"""
end_date = init_date + datetime.timedelta(seconds=seconds)
if caltype == NOLEAP:
end_date += get_leapdays(init_date, end_date)
if end_date.month == 2 a... | csn |
Returns a Vector instance from cylindircal coordinates | def cylindrical(cls, mag, theta, z=0):
'''Returns a Vector instance from cylindircal coordinates'''
return cls(
mag * math.cos(theta), # X
mag * math.sin(theta), # Y
z # Z
) | csn |
This method should only be called from aria.templates.ModuleCtrl when a module controller is disposed, so
that its sub-modules and flow can be disposed as well.
@param {aria.templates.ModuleCtrl} moduleCtrlPrivate module controller instance which is being disposed
@private | function (moduleCtrlPrivate) {
var k = moduleCtrlPrivate[MODULECTRL_ID_PROPERTY];
var res = getModulePrivateInfoWithCheck(moduleCtrlPrivate, "notifyModuleCtrlDisposed");
if (!res) {
// error is already logged
return;
... | csn |
// WriteTo redirects all writes to the Write syscall, which is 4 times faster. | func (c *connectedUDPConn) WriteTo(b []byte, addr net.Addr) (int, error) {
writer, ok := c.PacketConn.(io.Writer)
if ok {
return writer.Write(b)
}
return c.PacketConn.WriteTo(b, addr)
} | csn |
Returns all the assets directories contained in the given jsonData
@param array $jsonData
@return array|null | public function getPackageAssetsDirs($jsonData)
{
$packagesAssetsDir = null;
// If some assets were set on the package
if (isset($jsonData["extra"][self::LABEL_ASSETS_DIR])) {
// We get the assets-dir of this package
$packagesAssetsDir = $jsonData["extra"][self::LABEL... | csn |
// authHandler allows to get admin web interface token. | func (s *Handler) authHandler(w http.ResponseWriter, r *http.Request) {
formPassword := r.FormValue("password")
insecure := s.config.Insecure
password := s.config.Password
secret := s.config.Secret
if insecure {
w.Header().Set("Content-Type", "application/json")
resp := struct {
Token string `json:"token"... | csn |
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad]. | def delta_hv(scatterer):
"""
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad].
"""
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | csn |
If the query got changed to a funnel, move the step-specific parameters to a steps object.
@param {Object} explorer The explorer model that is being updated
@param {Object} newModel The updated explorer model
@return {Object} The new set of updates | function _migrateToFunnel(explorer, newModel) {
var firstStep = _defaultStep();
firstStep.active = true;
_.each(SHARED_FUNNEL_STEP_PROPERTIES, function (key) {
if(!_.isUndefined(explorer.query[key]) && !_.isNull(explorer.query[key])) {
firstStep[key] = explorer.query[key]
}
newModel.query[key]... | csn |
Download a remote file via scp.
@param session the session to use.
@param remoteFilePath the remote file path.
@param localFilePath the local file path to copy into.
@throws Exception | public static void downloadFile( Session session, String remoteFilePath, String localFilePath ) throws Exception {
// exec 'scp -f rfile' remotely
String command = "scp -f " + remoteFilePath;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
... | csn |
Class to add vessel as POI on Leaflet | function DeviceOnMap (map, data) {
this.trace=[]; // keep trace of device trace on xx positions
this.count=0; // number of points created for this device
this.devid = data.devid;
this.src = data.src;
this.name = data.name;
this.cargo = data.cargo;
this.vessel= ' cargo-' + data.cargo;
... | csn |
Returns a random file path to use for a new file.
@return string | public function generateRandomFilePath()
{
do {
$file = sys_get_temp_dir().
'/graphviz-'.sha1(uniqid('graphviz-image-', true).time().rand(0, 9999)).'.png';
} while (is_file($file));
return $file;
} | csn |
If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name | def get_output_jsonpath_with_name(self, sub_output=None):
"""If ExtractorProcessor has a name defined, return
a JSONPath that has a filter on that name"""
if self.name is None:
return None
output_jsonpath_field = self.get_output_jsonpath_field(sub_output)
extractor_f... | csn |
Builds and return the row of icons for the left side of the report.
It only has one cell that says "Controls"
@param array $rows The Array of rows for the left part of the report
@param int $colspan The number of columns this cell has to span
@return array Array of rows for the left part of the report | public function get_left_icons_row($rows=array(), $colspan=1) {
global $USER;
if ($USER->gradeediting[$this->courseid]) {
$controlsrow = new html_table_row();
$controlsrow->attributes['class'] = 'controls';
$controlscell = new html_table_cell();
$controls... | csn |
Resizes an image to the specified width, changing width in the same proportion
@param originalImage Image in memory
@param widthOut The width to resize
@return New Image in memory | public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int widthPercent = (widthOut * 100) / width;
int newHeight = (height * widthPercent) / 100;
BufferedImage resi... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.