query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Generates unique hashes for callback functions
@param mixed $callback
@return sting | public function getCallbackKey($callback)
{
if (is_array($callback)) {
if (is_object($callback[0])) {
$callback[0] = spl_object_hash($callback[0]);
}
} elseif ((function(){} instanceof $callback)) {
$callback = spl_object_hash($callback);
}... | csn |
Read raw pixel data, undo filters, deinterlace, and flatten.
Return in flat row flat pixel format. | def deinterlace(self, raw):
"""
Read raw pixel data, undo filters, deinterlace, and flatten.
Return in flat row flat pixel format.
"""
# Values per row (of the target image)
vpr = self.width * self.planes
# Make a result array, and make it big enough. Interleav... | csn |
Check size of gaps between successive features in list. The features in
the list are assumed to be appropriately ordered.
@param gapLength The minimum gap length to consider. Use a gapLength
of 0 to check if features are contiguous.
@return True if list has any gaps equal to or greater than gapLength. | public boolean hasGaps(int gapLength) {
Location last = null;
for (FeatureI f : this) {
if (last != null && gapLength <= f.location().distance(last)) {
return true;
} else {
last = f.location();
}
}
return false;
} | csn |
Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table. | def insert_query(**kw):
"""
Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_query_where_name.sql... | csn |
// SetMailFromAttributes sets the MailFromAttributes field's value. | func (s *GetEmailIdentityOutput) SetMailFromAttributes(v *MailFromAttributes) *GetEmailIdentityOutput {
s.MailFromAttributes = v
return s
} | csn |
build a dictionary, indexed by chrom name, of interval trees for each chrom.
:param inElements: list of genomic intervals. Members of the list must have
chrom, start and end fields; no other restrictions.
:param verbose: output progress messages to sys.stderr if True | def intervalTreesFromList(inElements, verbose=False, openEnded=False):
"""
build a dictionary, indexed by chrom name, of interval trees for each chrom.
:param inElements: list of genomic intervals. Members of the list must have
chrom, start and end fields; no other restrictions.
:param ver... | csn |
Force a failover of a named master. | def failover(self, name):
"""Force a failover of a named master."""
fut = self.execute(b'FAILOVER', name)
return wait_ok(fut) | csn |
Returns the invocations. | public ArrayList<I> getInvocations()
{
LruCache<Object,I> invocationCache = _invocationCache;
ArrayList<I> invocationList = new ArrayList<>();
synchronized (invocationCache) {
Iterator<I> iter;
iter = invocationCache.values();
while (iter.hasNext()) {
invocationList.add(... | csn |
Adds a predefined schema | @Override
public void schema(Class<?> type)
{
Objects.requireNonNull(type);
_context.schema(type);
} | csn |
// LANSegmentMembers is used to return the members of the given LAN segment. | func (s *Server) LANSegmentMembers(segment string) ([]serf.Member, error) {
if segment == "" {
return s.LANMembers(), nil
}
return nil, structs.ErrSegmentsNotSupported
} | csn |
// WithRuntime sets the runtime data to execute the query with. The runtime data
// can be returned by the `opa.runtime` built-in function. | func (q *Query) WithRuntime(runtime *ast.Term) *Query {
q.runtime = runtime
return q
} | csn |
// OrgSecretListAll returns a list of all repository secrets. | func (c *client) OrgSecretListAll() ([]*Secret, error) {
var out []*Secret
uri := fmt.Sprintf(pathSecrets, c.addr)
err := c.get(uri, &out)
return out, err
} | csn |
close the modal window | function() {
var obj;
// not that the modal viewer is no longer active
DataSaver.updateValue('modalActive', 'false');
modalViewer.active = false;
//Add active class to modal
$('#sg-modal-container').removeClass('active');
// remove the active class from all of the checkbo... | csn |
collection find method | def find(self, *args, **kwargs):
"""collection find method
"""
wrapper = kwargs.pop('wrapper', False)
if wrapper is True:
return self._wrapper_find(*args, **kwargs)
return self.__collect.find(*args, **kwargs) | csn |
Creates a Project for a specific User
@param userId The id of the user to create the project for
@param name The name of the project
@return The GitLab Project
@throws IOException on gitlab api call error | public GitlabProject createUserProject(Integer userId, String name) throws IOException {
return createUserProject(userId, name, null, null, null, null, null, null, null, null, null);
} | csn |
Returns a copy of this dependency path | public SimpleDependencyPath copy() {
SimpleDependencyPath copy = new SimpleDependencyPath();
copy.path.addAll(path);
copy.nodes.addAll(nodes);
return copy;
} | csn |
Sets the SpecTopic of the Revision History for the Content Specification.
@param revisionHistory The SpecTopic for the Revision History | public void setRevisionHistory(final SpecTopic revisionHistory) {
if (revisionHistory == null && this.revisionHistory == null) {
return;
} else if (revisionHistory == null) {
removeChild(this.revisionHistory);
this.revisionHistory = null;
} else if (this.revis... | csn |
Render the breadcrumb
@return string | public function render()
{
$htmlSrc = '<' . $this->containerTag . ' class="' . $this->breadcrumbClass . '">' . PHP_EOL;
foreach ($this->links as $key => $row) {
$htmlSrc .= '<' . $this->itemTag . '>' . $row . '</' . $this->itemTag . '>' . PHP_EOL;
}
$htmlSrc .= '</' . $th... | csn |
// PublishTransaction sends the transaction to the consensus RPC server so it
// can be propagated to other nodes and eventually mined.
//
// This function is unstable and will be removed once syncing code is moved out
// of the wallet. | func (w *Wallet) PublishTransaction(tx *wire.MsgTx) error {
_, err := w.reliablyPublishTransaction(tx)
return err
} | csn |
Get the string value
@param formatter
the CCS target
@return the value | String stringValue( CssFormatter formatter ) {
String str;
try {
formatter.addOutput();
appendTo( formatter );
} catch( Exception ex ) {
throw createException( ex );
} finally {
str = formatter.releaseOutput();
}
return str;... | csn |
// Returns the number of inbound gateway connections | func (s *Server) numInboundGateways() int {
s.gateway.RLock()
n := len(s.gateway.in)
s.gateway.RUnlock()
return n
} | csn |
Linear channel positions along the vertical axis. | def linear_positions(n_channels):
"""Linear channel positions along the vertical axis."""
return np.c_[np.zeros(n_channels),
np.linspace(0., 1., n_channels)] | csn |
Never wrap contents as SanitizedContent if HTML or ATTRIBUTES. | @Override
protected Expression maybeWrapContent(
CodeChunk.Generator generator, CallParamContentNode node, Expression content) {
SanitizedContentKind kind = node.getContentKind();
if (kind == SanitizedContentKind.HTML || kind == SanitizedContentKind.ATTRIBUTES) {
return content;
}
return super... | csn |
//returns the distance between two vectors. | func Dist(v1, v2 Vect) Float {
return Float(math.Sqrt(float64(DistSqr(v1, v2))))
} | csn |
// handleRecurse is used to handle recursive DNS queries | func (d *DNSServer) handleRecurse(resp dns.ResponseWriter, req *dns.Msg) {
cfg := d.config.Load().(*dnsConfig)
q := req.Question[0]
network := "udp"
defer func(s time.Time) {
d.logger.Printf("[DEBUG] dns: request for %v (%s) (%v) from client %s (%s)",
q, network, time.Since(s), resp.RemoteAddr().String(),
... | csn |
// _baseHistory is the base to create an history file. | func _baseHistory(fname string, size int) (*history, error) {
file, err := os.OpenFile(fname, os.O_CREATE|os.O_RDWR, HistoryPerm)
if err != nil {
return nil, err
}
h := new(history)
h.Cap = size
h.filename = fname
h.file = file
h.li = list.New()
return h, nil
} | csn |
Iteratively solves columnization given constraints in props.
Solution is captured by this.state.
@returns {undefined} | function solve() {
while (true) {
// establish vars for current loop
//----------------------------------------------------------
const row = this.state.i % this.state.rows
const col = Math.floor(this.state.i / this.state.rows)
const str = this.props.ar[this.state.i]
const len = str.length
... | csn |
Checks for empty identifiers in the pre-release version or build metadata.
@throws ParseException
if the pre-release version or build metadata have empty identifier(s) | private void checkForEmptyIdentifier() {
Character la = chars.lookahead(1);
if (CharType.DOT.isMatchedBy(la) || CharType.PLUS.isMatchedBy(la)
|| CharType.EOL.isMatchedBy(la)) {
throw new ParseException("Identifiers MUST NOT be empty", new UnexpectedCharacterException(la,
chars.currentOff... | csn |
Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory | def add_category(self, name):
"""
Adds a bayes category that we can later train
:param name: name of the category
:type name: str
:return: the requested category
:rtype: BayesCategory
"""
category = BayesCategory(name)
self.categories[name] = cate... | csn |
Attempts to load a message resource. | private Properties loadMessages(String fileOrUrl) {
URL url = ClasspathUtils.locateOnClasspath(fileOrUrl);
if (url != null) {
try (InputStreamReader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
Properties messages = new Properties();
... | csn |
Attempt to set the session name
If the session has already been started, or if the name provided fails
validation, an exception will be raised.
@param string $name
@throws SessionException
@return void | public function setName($name): void
{
if ($this->sessionExists()) {
throw new SessionException(
'Cannot set session name after a session has already started'
);
}
if (!preg_match('/^[a-zA-Z0-9]+$/', $name)) {
throw new SessionException(
... | csn |
Helper function used in plot functions that accept an optional array of Axes
as argument. If ax_array is None, we build the `matplotlib` figure and
create the array of Axes by calling plt.subplots else we return the
current active figure.
Returns:
ax: Array of :class:`Axes` objects
figu... | def get_axarray_fig_plt(ax_array, nrows=1, ncols=1, sharex=False, sharey=False,
squeeze=True, subplot_kw=None, gridspec_kw=None,
**fig_kw):
"""
Helper function used in plot functions that accept an optional array of Axes
as argument. If ax_array is None, we bu... | csn |
Gets the set of rotational speed rpms of the disks.
:param system_obj: The HPESystem object.
:returns the set of rotational speed rpms of the HDD devices. | def get_drive_rotational_speed_rpm(system_obj):
"""Gets the set of rotational speed rpms of the disks.
:param system_obj: The HPESystem object.
:returns the set of rotational speed rpms of the HDD devices.
"""
speed = set()
smart_resource = _get_attribute_value_of(system_obj, 'smart_storage')
... | csn |
Mark host as having an active worker
@param Worker $worker the worker instance | public function working(Worker $worker)
{
$this->redis->sadd(self::redisKey(), $this->hostname);
$this->redis->sadd(self::redisKey($this), (string)$worker);
$this->redis->expire(self::redisKey($this), $this->timeout);
} | csn |
Checks if discount applies for article
@param \OxidEsales\Eshop\Application\Model\Article $oArticle article object
@return bool | public function isForArticle($oArticle)
{
// item discounts may only be applied for basket
if ($this->oxdiscount__oxaddsumtype->value == 'itm') {
return false;
}
if ($this->oxdiscount__oxamount->value || $this->oxdiscount__oxprice->value) {
return false;
... | csn |
Filter out cell barcodes not in the whitelist, with
optional cell barcode error correction | def filterCellBarcode(self, cell):
'''Filter out cell barcodes not in the whitelist, with
optional cell barcode error correction'''
if self.cell_blacklist and cell in self.cell_blacklist:
self.read_counts['Cell barcode in blacklist'] += 1
return None
if cell not... | csn |
// Initialize initializes all loaded plugins | func (loader *PluginLoader) Initialize() error {
for _, p := range loader.plugins {
err := p.Init()
if err != nil {
return err
}
}
return nil
} | csn |
DeAuthorize user from app
@param User $user
@return void | private function deAuthorize(User $user): void
{
$client = new Client;
$client->delete("https://graph.facebook.com/{$user->id}/permissions",
[
'headers' => ['Accept' => 'application/json'],
'form_params' => [
'access_token' => $user->t... | csn |
Constructor for filesystem cache backend | function FSBackend(loadParameter) {
this.loaded = false;
this.index = [];
this.location = typeof loadParameter === "string" && loadParameter.length > 0 ? loadParameter : process.cwd() + "/cache/";
this.location = this.location.substr(this.location.length - 1) === "/" ? this.location : this.location + "/... | csn |
Registers an entity code generator service.
@param CodeGeneratorInterface $codeGenerator the entity code generator service
@throws \Exception | public static function register(CodeGeneratorInterface $codeGenerator)
{
$class = get_class($codeGenerator);
if (!defined("$class::ENTITY_CLASS")) {
throw new \Exception($class . ' must define a ENTITY_CLASS constant.');
}
if (!defined("$class::ENTITY_FIELD")) {
... | csn |
Get a list of objects' properties
@return array | public function getPropertiesNames() {
$propertiesList = [];
foreach($this->_data as $item) {
$propertiesList += array_keys($item);
}
return $propertiesList;
} | csn |
Delete a topic.
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion. | def delete_topic_groups(self, group_id, topic_id):
"""
Delete a topic.
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_... | csn |
Attempts to return the internally loaded project. This function
prevents race condition issues where projects are loaded via threads
because the internal loop will try to continuously load the internal
project until it is available or until the timeout is reached.
:param timeout:
... | def get_internal_project(
self,
timeout: float = 1
) -> typing.Union['projects.Project', None]:
"""
Attempts to return the internally loaded project. This function
prevents race condition issues where projects are loaded via threads
because the internal loop w... | csn |
Ensures that we get the right IP address even if behind CloudFlare or most proxies
@return string | public function getRequestingIp()
{
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
{
return isset($_SERVER['HTTP_X_FORWARDED_FOR']);
}
elseif (isset(... | csn |
Checks whether the substring, starting at the specified index, starts with the given prefix string.
@param prefix The prefix character sequence.
@param startIndex The position to start checking for the prefix.
@return True, if this StringValue substring, starting at position <code>startIndex</code> has <code>prefix</... | public boolean startsWith(CharSequence prefix, int startIndex) {
final char[] thisChars = this.value;
final int pLen = this.len;
final int sLen = prefix.length();
if ((startIndex < 0) || (startIndex > pLen - sLen)) {
return false;
}
int sPos = 0;
while (sPos < sLen) {
if (thisChars[startIndex++... | csn |
Method to delete the contents of a folder
@param type $folderpath
@param type $filterByType
@param type $filterByName
@param type $filterExcludeMode | final public function deleteContents($folderpath, $filterByExtension = [], $filterByName = [],
$filterExcludeMode = true, $recursive = true)
{
//1. Search $name as a folder or as a file
if (!$this->is($folderpath)) { //if in path is a directory
r... | csn |
from A means node.level == 0
from . import B means node.level == 1
from .A means node.level == 1 | def handle_relative_import(self, node):
"""
from A means node.level == 0
from . import B means node.level == 1
from .A means node.level == 1
"""
no_file = os.path.abspath(os.path.join(self.filenames[-1], os.pardir))
skip_init = False
if node.l... | csn |
// Create a new state representing this state, with a temporary shift
// to a different mode to output a single value. | func (s *state) shiftAndAppend(mode encodingMode, value int) *state {
tokens := s.tokens
// Shifts exist only to UPPER and PUNCT, both with tokens size 5.
tokens = newSimpleToken(tokens, shiftTable[s.mode][mode], s.mode.BitCount())
tokens = newSimpleToken(tokens, value, 5)
return &state{
mode: s.mod... | csn |
Retrieve a single page of TaskInstance records from the API.
Request is executed immediately
:param unicode priority: Retrieve the list of all Tasks in the workspace with the specified priority.
:param unicode assignment_status: Returns the list of all Tasks in the workspace with the specified ... | def page(self, priority=values.unset, assignment_status=values.unset,
workflow_sid=values.unset, workflow_name=values.unset,
task_queue_sid=values.unset, task_queue_name=values.unset,
evaluate_task_attributes=values.unset, ordering=values.unset,
has_addons=values.unse... | csn |
Get the venue tips.
@param Description $description The tip group description.
@return Tip[] | private function getTips(Description $description)
{
return array_map(
function (\stdClass $tipDescription) {
return $this->tipFactory->create(new Description($tipDescription));
},
$description->getOptionalProperty('items', [])
);
} | csn |
Creates a new Parameter object from the given ParameterArgument. | def new(cls, arg):
"""
Creates a new Parameter object from the given ParameterArgument.
"""
content = None
if arg.kind == 'file':
if os.path.exists(arg.value):
with open(arg.value, 'r') as f:
content = f.read()
else:
... | csn |
Convert a Unicode field into the corresponding list of Unicode strings.
The (input) Unicode field is a Unicode string containing
one or more Unicode codepoints (``xxxx`` or ``U+xxxx`` or ``xxxx_yyyy``),
separated by a space.
:param str string: the (input) Unicode field
:rtype: list of Unicode stri... | def convert_unicode_field(string):
"""
Convert a Unicode field into the corresponding list of Unicode strings.
The (input) Unicode field is a Unicode string containing
one or more Unicode codepoints (``xxxx`` or ``U+xxxx`` or ``xxxx_yyyy``),
separated by a space.
:param str string: the (input)... | csn |
Get the controller method used for the route.
@return string | public function getControllerMethod()
{
if (! isset($this->method)) {
list (, $method) = $this->parseControllerCallback();
return $this->method = $method;
}
return $this->method;
} | csn |
Flags a paper as finished.
@EXT\Route("/{id}/end", name="exercise_attempt_finish")
@EXT\Method("PUT")
@EXT\ParamConverter("paper", class="UJMExoBundle:Attempt\Paper", options={"mapping": {"id": "uuid"}})
@EXT\ParamConverter("user", converter="current_user", options={"allowAnonymous"=true})
@param Paper $paper
@param ... | public function finishAction(Paper $paper, User $user = null)
{
$this->assertHasPermission('OPEN', $paper->getExercise());
$this->assertHasPaperAccess($paper, $user);
$this->attemptManager->end($paper, true, !empty($user));
$userEvaluation = !empty($user) ?
$this->resour... | csn |
Whether the administration interface should be enabled.
@access public
@return bool $is_enabled True if the admin interface is enabled. | public function is_enabled() {
$enabled = false;
// Enabled if this plugin is installed as a regular WordPress plugin.
$plugin_path = untrailingslashit( ABSPATH ) . DIRECTORY_SEPARATOR . 'wp-content' . DIRECTORY_SEPARATOR . 'plugins';
$current_dir = $this->current_dir();
if ( false !== strpos( $current_dir, ... | csn |
Initialize the palette.
@return void | public function initializePalette(): void
{
if (Input::get('act') === 'edit') {
$model = GridModel::findByPk(Input::get('id'));
$sizes = array_map(
function ($value) {
return $value . 'Size';
},
StringUtil::deseriali... | csn |
Parse CVSS vector
@param string $vector
@throws \InvalidArgumentException | public function setVector($vector)
{
if (empty($vector)) {
throw new \InvalidArgumentException(sprintf('Cvss vector "%s" is not valid.', $vector));
}
if (!preg_match('/^' . self::$vectorHead . '.*/mi', $vector)) {
throw new \InvalidArgumentException((sprintf('Cvss ve... | csn |
Received message object router.
@param message
an IoBuffer or Packet | public void messageReceived(Object message) {
if (message instanceof Packet) {
try {
messageReceived(conn, (Packet) message);
} catch (Exception e) {
log.warn("Exception on packet receive", e);
}
} else {
// raw buff... | csn |
// GetStringMap tries to read a string to string map from a
// PluginConfig. If the key is not found defaultValue is returned. | func (reader PluginConfigReaderWithError) GetStringMap(key string, defaultValue map[string]string) (map[string]string, error) {
key = reader.config.registerKey(key)
if reader.HasValue(key) {
return reader.config.Settings.StringMap(key)
}
return defaultValue, nil
} | csn |
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome ! | def acquire_context(self):
"""
Inspect the stack to acquire the current context used,
to render the placeholder. I'm really sorry for this,
but if you have a better way, you are welcome !
"""
frame = None
request = None
try:
for f in inspect.s... | csn |
Obtained new grants from Cluster Manager.
@param grants | public void addNewGrants(List<ResourceGrant> grants) {
int numGranted = 0;
int numAvailable = 0;
synchronized(lockObject) {
for (ResourceGrant grant: grants) {
Integer requestId = grant.getId();
if (!requestedResources.containsKey(requestId) ||
!requestMap.containsKey(reque... | csn |
Displays this interface with tidy XHTML
The display() method is called and the output is cleaned up.
@deprecated This method breaks some elements of swat by adding
whitespace between nodes. Use {@link SwatUI::display()}
instead. | public function displayTidy()
{
$breaking_tags = '@</?(div|p|table|tr|td|ul|li|ol|dl|option)[^<>]*>@ui';
ob_start();
$this->display();
$buffer = ob_get_clean();
$tidy = preg_replace($breaking_tags, "\n\\0\n", $buffer);
$tidy = str_replace("\n\n", "\n", $tidy);
... | csn |
// CopyArchive downloads files and directories as a tarball and saves it to a specified path. | func CopyArchive(c KubernetesClientInterface, containerID, sourcePath, destPath string) error {
log.Infof("Archiving %s:%s to %s", containerID, sourcePath, destPath)
b, err := c.CreateArchive(containerID, sourcePath)
if err != nil {
return err
}
f, err := os.OpenFile(destPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY,... | csn |
Passed off to scipy.interpolate.interp1d. method is scipy's kind.
Returns an array interpolated at new_x. Add any new methods to
the list in _clean_interp_method. | def _interpolate_scipy_wrapper(x, y, new_x, method, fill_value=None,
bounds_error=False, order=None, **kwargs):
"""
Passed off to scipy.interpolate.interp1d. method is scipy's kind.
Returns an array interpolated at new_x. Add any new methods to
the list in _clean_interp_m... | csn |
Returns the subscribe ID of a channel having the passed in functional name or null if it
can't find such a channel in the layout. | @Override
public String getSubscribeId(String fname) {
final Document userLayout = this.getUserLayoutDOM();
return new PortletSubscribeIdResolver(fname).traverseDocument(userLayout);
} | csn |
Start a fresh connection. The object closes any existing connection and
opens a new one. | def start(request_params)
# close the previous if exists
finish
# create new connection
@server = request_params[:server]
@port = request_params[:port]
@protocol = request_params[:protocol]
@proxy_host = request_params[:proxy_host]
@proxy_port ... | csn |
Request available methods for the service. | async def fetch_signatures(endpoint, protocol, idgen):
"""Request available methods for the service."""
async with aiohttp.ClientSession() as session:
req = {
"method": "getMethodTypes",
"params": [''],
"version": "1.0",
"id": n... | csn |
// Change implements Processor. | func (prc ListProcessor) Change(params imageserver.Params) bool {
for _, p := range prc {
if p.Change(params) {
return true
}
}
return false
} | csn |
// IsMentionFor checks if the given user was mentioned with the message | func (m Message) IsMentionFor(user string) bool {
return strings.HasPrefix(m.Message, "<@"+user+">")
} | csn |
Toggles instrumented memory tracing. | function instrumentMemoryClicked() {
_gaq.push(['_trackEvent', 'popup', 'instrument_memory']);
try {
new Function('return %GetHeapUsage()');
} catch (e) {
// Pop open docs page.
port.postMessage({
command: 'instrument',
type: 'memory',
needsHelp: true
});
return;
}
port... | csn |
Return relevant who-did-what logs from the ticket history | def history(self, user=None):
""" Return relevant who-did-what logs from the ticket history """
for event in self.changelog:
when, who, what, old, new, ignore = event
if (when >= self.options.since.date and
when <= self.options.until.date):
if ... | csn |
// FindCol finds column in cols by name. | func FindCol(cols []*Column, name string) *Column {
for _, col := range cols {
if strings.EqualFold(col.Name.O, name) {
return col
}
}
return nil
} | csn |
Updates a key with the translation in the default language.
@param representation key representation
@return key representation
@throws URISyntaxException if the URI is not valid. | @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@RequiresPermissions(I18nPermissions.KEY_WRITE)
public Response updateKey(KeyRepresentation representation) throws URISyntaxException {
WebAssertions.assertNotNull(representation, THE_KEY_SHOULD_NOT_BE_NULL);
... | csn |
Remove the attribute from each element
@param string $attr
@return MultiElementsAbstract | public function removeElementsAttr($attr) {
foreach ($this->getElements() as $element) {
if ($element instanceof Tag) {
$element->removeAttr($attr);
}
}
return $this;
} | csn |
Cleans the files and directories in the directory path.
@param {string} directoryPath
@param {function(Error=)} done | function clean(directoryPath, isRoot, done) {
fs.stat(directoryPath, function(err, stat) {
if (err) return done(isRoot ? undefined : err);
if (stat.isFile()) return fs.unlink(directoryPath, done);
fs.readdir(directoryPath, function(err, relativePaths) {
if (err) return done(err);
each(relative... | csn |
Serialized Astyanax Composite objects use a lot of memory. Trim it down. | private static ByteBuffer trim(ByteBuffer buf) {
if (buf.capacity() <= 4 * buf.remaining()) {
return buf;
} else {
ByteBuffer clone = ByteBuffer.allocate(buf.remaining());
buf.get(clone.array());
return clone;
}
} | csn |
// SetStyleTextsWithParams - Applies specified style edits one after another in the given order.
// Returns - styles - The resulting styles after modification. | func (c *CSS) SetStyleTextsWithParams(v *CSSSetStyleTextsParams) ([]*CSSCSSStyle, error) {
resp, err := gcdmessage.SendCustomReturn(c.target, c.target.GetSendCh(), &gcdmessage.ParamRequest{Id: c.target.GetId(), Method: "CSS.setStyleTexts", Params: v})
if err != nil {
return nil, err
}
var chromeData struct {
R... | csn |
Build method with href and set alt check
@see \Core\Abstracts\AbstractHtml::build() | public function build()
{
if (isset($this->attribute['href']) && (! isset($this->attribute['alt']))) {
$this->attribute['alt'] = $this->attribute['href'];
}
return parent::build();
} | csn |
// EngineVersion implements the ClusterRegistry interface | func (r *EtcdRegistry) EngineVersion() (int, error) {
res, err := r.kAPI.Get(context.Background(), r.engineVersionPath(), nil)
if err != nil {
// no big deal, either the cluster is new or is just
// upgrading from old unversioned code
if isEtcdError(err, etcd.ErrorCodeKeyNotFound) {
err = nil
}
return 0,... | csn |
Can be used to append a String to a formatter.
@param formatter
The {@link java.util.Formatter Formatter}
@param width
Minimum width to meet, filled with space if needed
@param precision
Maximum amount of characters to append
@param leftJustified
Whether or not to left-justify the value
@param out
The String to append | public static void appendTo(Formatter formatter, int width, int precision, boolean leftJustified, String out)
{
try
{
Appendable appendable = formatter.out();
if (precision > -1 && out.length() > precision)
{
appendable.append(Helpers.truncate(out,... | csn |
Return the JSON defined at the S3 location in the constructor.
The get method will reload the S3 object after the TTL has
expired.
Fetch the JSON object from cache or S3 if necessary | def get(self, transform=None):
"""
Return the JSON defined at the S3 location in the constructor.
The get method will reload the S3 object after the TTL has
expired.
Fetch the JSON object from cache or S3 if necessary
"""
if not self.has_expired() and self._cache... | csn |
Gets the Compiler instance.
@return Twig_CompilerInterface A Twig_CompilerInterface instance | public function getCompiler()
{
if (null === $this->compiler) {
$this->compiler = new Twig_Compiler($this);
}
return $this->compiler;
} | csn |
Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable. | def add_proxy(self, proxy):
"""Add a valid proxy into pool
You must call `add_proxy` method to add a proxy into pool instead of
directly operate the `proxies` variable.
"""
protocol = proxy.protocol
addr = proxy.addr
if addr in self.proxies:
self.prox... | csn |
Gets the record associated with a specific Row
@param row The row
@return The associated record, or null. | public T getRecordForRow( Row row )
{
Integer recordId = rowToRecordIds.get( row );
if( recordId == null )
return null;
return getRecordForId( recordId );
} | csn |
Combine terms with AND.
There must be a term added before using this method.
Arguments:
close_group (bool): If ``True``, will end the current group and start a new one.
If ``False``, will continue current group.
Example::
If ... | def _and_join(self, close_group=False):
"""Combine terms with AND.
There must be a term added before using this method.
Arguments:
close_group (bool): If ``True``, will end the current group and start a new one.
If ``False``, will continue current group.
... | csn |
Records a mutation compacting existing mutations for the same key path.
@private
@param {MutationTracker~mutation} mutation | function (mutation) {
// for `set` and `unset` mutations the key to compact with is the `keyPath`
var key = mutation[0];
// convert `keyPath` to a string
key = Array.isArray(key) ? key.join('.') : key;
this.compacted[key] = mutation;
} | csn |
Instantiate the given plugin, which either needs a path property or a name
property which fits to the npm module name convention. Options will be passed
to the constructor.
CLI arguments will be considered.
@param {Object} config deepstream configuration object
@private
@returns {Function} Instance return be the plu... | function resolvePluginClass (plugin, type) {
// alias require to trick nexe from bundling it
const req = require
let requirePath
let pluginConstructor
if (plugin.path != null) {
requirePath = fileUtils.lookupLibRequirePath(plugin.path)
pluginConstructor = req(requirePath)
} else if (plugin.name != n... | csn |
Stops the artifact server.
@throws Exception | public synchronized void stop() throws Exception {
if (this.serverChannel != null) {
this.serverChannel.close().awaitUninterruptibly();
this.serverChannel = null;
}
if (bootstrap != null) {
if (bootstrap.group() != null) {
bootstrap.group().shutdownGracefully();
}
bootstrap = null;
}
} | csn |
Return a plain-object representation of `test`
free of cyclic properties etc.
@private
@param {Object} test
@return {Object} | function clean(test) {
var err = test.err || {};
if (err instanceof Error) {
err = errorJSON(err);
}
return {
title: test.title,
fullTitle: test.fullTitle(),
duration: test.duration,
currentRetry: test.currentRetry(),
err: cleanCycles(err)
};
} | csn |
Serialize the value as an xml element with the given node name.
@param string
@param mixed
@return string | protected function _serializeNode($nodeName, $value)
{
return sprintf('<%s>%s</%1$s>', $nodeName, $this->xmlEncode($this->_helper->escapeHtml($value)));
} | csn |
Delete a Widget quantum.
@param Widget $widget The widget to delete
@param int $viewReference The current view
@throws Exception
@return JsonResponse response
@Route("/victoire-dcms/widget/delete/quantum/{id}/{viewReference}", name="victoire_core_widget_delete_bulk", defaults={"_format": "json"}) | public function deleteBulkAction(Widget $widget, $viewReference)
{
$view = $this->getViewByReferenceId($viewReference);
try {
$widgets = $widget->getWidgetMap()->getWidgets();
foreach ($widgets as $widget) {
$this->get('widget_manager')->deleteWidget($widget... | csn |
Will make the thread ready to run once again after it has stopped. | void reset()
{
if (!hasStopped)
{
throw new IllegalStateException("cannot reset a non stopped queue poller");
}
hasStopped = false;
run = true;
lastLoop = null;
loop = new Semaphore(0);
} | csn |
Actual file move to external storage
@param string $filePath
@param Folder $folder | private function moveFileToExternalStorage($filePath,Folder $folder = null)
{
$oldPath = $this->getInternalPath() . $filePath;
$newPath = $this->getExternalPath() . $filePath;
$this->createBothFoldersInFileSystem($folder);
if ( ! rename($oldPath, $newPath)) {
// throw new Exception\RuntimeException('Failed... | csn |
Gets a list of all the modified properties of this object
@return array an array of modified properties and their values in the
form of: name => value | public function getModifiedProperties()
{
if ($this->read_only) {
return array();
}
$modified_properties = array();
foreach ($this->getProperties() as $name => $value) {
$hashed_value = $this->getHashValue($value);
if (
array_key_e... | csn |
Creates or updates a configuration value in the service with the given key.
<p><strong>Code Samples</strong></p>
<pre>
ConfigurationSetting result = client.setSetting('prodDBConnection", "db_connection");
System.out.printf("Key: %s, Value: %s", result.key(), result.value());
result = client.setSetting("prodDBConnect... | public Response<ConfigurationSetting> setSetting(String key, String value) {
return setSetting(new ConfigurationSetting().key(key).value(value));
} | csn |
Append label for ``mode`` and display ``value`` on it.
|Args|
* ``mode`` (**str**): mode of mode.
* ``value`` (**object**): value of mode.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if at least one argument has an invalid type. | def qteAddMode(self, mode: str, value):
"""
Append label for ``mode`` and display ``value`` on it.
|Args|
* ``mode`` (**str**): mode of mode.
* ``value`` (**object**): value of mode.
|Returns|
* **None**
|Raises|
* **QtmacsArgumentError** if ... | csn |
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance. | def _WX28_clipped_agg_as_bitmap(agg, bbox):
"""
Convert the region of a the agg buffer bounded by bbox to a wx.Bitmap.
Note: agg must be a backend_agg.RendererAgg instance.
"""
l, b, width, height = bbox.bounds
r = l + width
t = b + height
srcBmp = wx.BitmapFromBufferRGBA(int(agg.width... | csn |
Check whether given exception is in skippable exception list | private boolean containsSkippable(Set<String> skipList, Exception e)
{
final String mName = "containsSkippable";
boolean retVal = false;
for ( Iterator it = skipList.iterator(); it.hasNext(); ) {
String exClassName = (String) it.next();
try {
ClassLoader tccl... | csn |
Compute an new version and write it as a tag | def update_version(self, version, step=1):
"Compute an new version and write it as a tag"
# update the version based on the flags passed.
if self.config.patch:
version.patch += step
if self.config.minor:
version.minor += step
if self.config.major:
... | csn |
Returns a List of all Folders an Files of a Path on FTP Server.
@access public
@param string $path Path
@param bool $recursive Scan Folders recursive (default: FALSE)
@return array | public function getList( $path = "", $recursive = FALSE )
{
$this->connection->checkConnection();
$parsed = array();
if( !$path )
$path = $this->getPath();
$list = ftp_rawlist( $this->connection->getResource(), $path );
if( is_array( $list ) )
{
foreach( $list as $current )
{
$data = $this->pa... | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.