query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Send the given entry.
@param Entry $entry | private function sendEntry(Entry $entry)
{
if ($this->batchEnabled) {
$this->batchRunner->submitItem($this->identifier, $entry);
return;
}
$this->logger->write($entry);
} | csn |
Dense layer with dropconnect. | def dense_dropconnect(inputs,
output_size,
dropconnect_dropout=0.0,
name="dense_dropconnect",
**kwargs):
"""Dense layer with dropconnect."""
if dropconnect_dropout != 0.0:
tf.logging.info("Applying dropconnect as the kernel... | csn |
// GetState returns the latest task state. It will only return the status once
// as the message will get consumed and removed from the queue. | func (b *Backend) GetState(taskUUID string) (*tasks.TaskState, error) {
declareQueueArgs := amqp.Table{
// Time in milliseconds
// after that message will expire
"x-message-ttl": int32(b.getExpiresIn()),
// Time after that the queue will be deleted.
"x-expires": int32(b.getExpiresIn()),
}
conn, channel, _,... | csn |
Defines a mapping between a method call to a column
@param string $methodName
@return PropertyColumnDefiner | public function method(string $methodName): PropertyColumnDefiner
{
return new PropertyColumnDefiner($this, null, function (Column $column) use ($methodName) {
$this->methodColumnMap[$methodName] = $column->getName();
$this->addColumn($column);
});
} | csn |
Is request throttled.
@param request the request
@param response the response
@return true if the request is throttled. False otherwise, letting it proceed. | protected boolean throttleRequest(final HttpServletRequest request, final HttpServletResponse response) {
return configurationContext.getThrottledRequestExecutor() != null
&& configurationContext.getThrottledRequestExecutor().throttle(request, response);
} | csn |
This function will create the index in the table passed as arguments
Before creating the index, the function will check it doesn't exists
@param xmldb_table $xmldb_table Table object (just the name is mandatory).
@param xmldb_index $xmldb_intex Index object (full specs are required).
@return void | public function add_index($xmldb_table, $xmldb_intex) {
if (!$this->table_exists($xmldb_table)) {
throw new ddl_table_missing_exception($xmldb_table->getName());
}
// Check index doesn't exist
if ($this->index_exists($xmldb_table, $xmldb_intex)) {
throw new ddl_e... | csn |
// TraceTransaction returns the structured logs created during the execution of EVM
// and returns them as a JSON object. | func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
// Retrieve the transaction and assemble its EVM context
tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
if tx == nil {
return nil, fmt.Errorf("transaction %#x n... | csn |
Checks for first IP in proxy string and returns it
@param string $proxyString
@return null|string | private static function getFirstIP($proxyString = ''): ?string
{
\preg_match('/^(([0-9]{1,3}\.){3}[0-9]{1,3})/', $proxyString, $matches);
return (\is_array($matches) && isset($matches[1])) ? $matches[1] : null;
} | csn |
// MarshalJSON is generated so ComponentStatus satisfies json.Marshaler. | func (r ComponentStatus) MarshalJSON() ([]byte, error) {
if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String())
}
s, ok := _ComponentStatusValueToName[r]
if !ok {
return nil, fmt.Errorf("invalid ComponentStatus: %d", r)
}
return json.Marshal(s)
} | csn |
// ParseForm form from url values. | func ParseForm(raw url.Values) Form {
result := make(Form, len(raw))
for k, v := range raw {
if len(v) == 0 {
continue
}
fields := strings.FieldsFunc(k, fieldsExtractor)
pfield, cfield := "", ""
form := result
for i := range fields {
pfield = cfield
cfield = fields[i]
if index, err := strc... | csn |
Checks to see if any of the args are templates. | def _should_defer(input_layer, args, kwargs):
"""Checks to see if any of the args are templates."""
for arg in itertools.chain([input_layer], args, six.itervalues(kwargs)):
if isinstance(arg, (_DeferredLayer, UnboundVariable)):
return True
elif (isinstance(arg, collections.Sequence) and
not ... | csn |
Set current MenuLink IDs.
We use routeName and params to match active MenuLinks.
While the same MenuLink can be linked to different Menus and they have the same params and routeName,
there is currently no way to identify which of them is active, therefore all of their IDs are returned.
@param bool $reset
@throws \Ex... | public static function setActiveIDs($reset = false)
{
if(!self::$activeIDs || $reset) {
// Get current Menu Link
$currentRoute = \Request::route();
// Get active MenuLinks by routeName and params
$currentMenuLinkIDs = [];
$isDefaultLanguage = (App... | csn |
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`. | def build_extension(extensions: Sequence[ExtensionHeader]) -> str:
"""
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`.
"""
return ", ".join(
build_extension_item(name, parameters) for name, parameters in extensions
) | csn |
// All returns all owners for all hash map elements | func (h *HashMap) All() ([]string, error) {
var (
values []string
value string
)
rows, err := h.host.db.Query(fmt.Sprintf("SELECT %s FROM %s", ownerCol, h.table))
if err != nil {
return values, err
}
if rows == nil {
return values, ErrNoAvailableValues
}
defer rows.Close()
for rows.Next() {
err = ro... | csn |
Set all filter as an array
@param $filters
@return $this | public function setFilters($filters)
{
if (!is_array($filters)) {
$this->clearFilters();
foreach(explode('|', $filters) as $filter) {
// searching for optional params
$params = [];
if (strpos($filter, ':')) {
list(... | csn |
Implements the instanceof operator.
@param instance The value that appeared on the LHS of the instanceof
operator
@return true if "this" appears in value's prototype chain | public boolean hasInstance(Scriptable instance) {
// Default for JS objects (other than Function) is to do prototype
// chasing.
Scriptable proto = instance.getPrototype();
while (proto != null) {
if (proto.equals(this)) return true;
proto = proto.getPrototype();
... | csn |
An alternative method for constructing the income process in the infinite horizon model.
Parameters
----------
none
Returns
-------
none | def updateIncomeProcess(self):
'''
An alternative method for constructing the income process in the infinite horizon model.
Parameters
----------
none
Returns
-------
none
'''
if self.cycles == 0:
tax_rate = (self.IncUnemp*sel... | csn |
Adds a product to the wishlist
@param array $cart
@return array | protected function addToWishlist(array $cart)
{
$data = array(
'user_id' => $cart['user_id'],
'store_id' => $cart['store_id'],
'product_id' => $cart['product_id']
);
return $this->wishlist_action->add($data);
} | csn |
// Command adds a command action to the transaction with the given args.
// handler will be called with the reply from this specific command when
// the transaction is executed. | func (t *Transaction) Command(name string, args redis.Args, handler ReplyHandler) {
t.actions = append(t.actions, &Action{
kind: commandAction,
name: name,
args: args,
handler: handler,
})
} | csn |
Returns true if date passed is within this week.
@param string|int $time
@return bool | public static function isThisWeek($time): bool
{
return (self::factory($time)->format('W-Y') === self::factory()->format('W-Y'));
} | csn |
Provide resampling when using a TimeGrouper.
Given a grouper, the function resamples it according to a string
"string" -> "frequency".
See the :ref:`frequency aliases <timeseries.offset_aliases>`
documentation for more details.
Parameters
----------
rule : str ... | def resample(self, rule, *args, **kwargs):
"""
Provide resampling when using a TimeGrouper.
Given a grouper, the function resamples it according to a string
"string" -> "frequency".
See the :ref:`frequency aliases <timeseries.offset_aliases>`
documentation for more deta... | csn |
This should ONLY be called once all training threads have completed
@return | public ThresholdAlgorithm getAverageThresholdAlgorithm(){
Collection<ThresholdAlgorithm> c = this.allThreadThresholdAlgorithms.values();
if(c.isEmpty()){
return null;
}
if(c.size() == 1){
return c.iterator().next();
}
Iterator<ThresholdAlgorithm> i... | csn |
Generates the content for the configuration file.
@param array $config
@return string | protected function generateConfigContent(array $config)
{
/* This code is taken from ZF2s' classmap_generator.php script. */
// Create a file with the class/file map.
// Stupid syntax highlighters make separating < from PHP declaration necessary
$content = '<' . "?php\n"
... | csn |
Parse DocxColor object
@param node [Nokogiri::XML:Element] node to parse
@return [DocxColor] result of parsing | def parse(node)
node.xpath('*').each do |node_child|
case node_child.name
when 'blipFill'
@type = :picture
@value = DocxBlip.new(parent: self).parse(node_child)
node_child.xpath('*').each do |fill_type_node_child|
case fill_type_node_child.name
... | csn |
Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template. | def get_display_label(choices, status):
"""Get a display label for resource status.
This method is used in places where a resource's status or
admin state labels need to assigned before they are sent to the
view template.
"""
for (value, label) in choices:
if value == (status or '').lo... | csn |
Handle key event on keydown or keypress. Synchronous function
@see _handleKey
@protected
@param {Object|aria.DomEvent} event object containing keyboard event information (at least charCode and
keyCode properties). This object may be or may not be an instance of aria.DomEvent. | function (event) {
if (this._cfg.waiAria && !this._dropdownPopup && event.keyCode === DomEvent.KC_DOWN) {
// disable arrow down key when waiAria is enabled and the popup is closed
return;
}
var controller = this.controller;
var cp = this.ge... | csn |
Obtain the value for this Future | def value(timeout = nil)
ready = result = nil
begin
@mutex.lock
if @ready
ready = true
result = @result
else
case @forwards
when Array
@forwards << Celluloid.mailbox
when NilClass
@forwards = Celluloid.mailbo... | csn |
Cast a value to boolean.
@param mixed $value
@return bool | public static function toBool($value)
{
if ($value instanceof Countable) {
return (bool)count($value);
}
if (!static::isStringLike($value)) {
return (bool)$value;
}
$string = "$value";
if (trim($string) == '') {
return false;
... | csn |
Reset users password.
@param Request $request
@return array | public function resetPassword(Request $request)
{
// check if user has permissions to access this link
if(!User::hasAccess('user', 'update')) {
return $this->noPermission();
}
// validation
$validator = Validator::make(
$request->all(), [
'... | csn |
Process the related OutcomeMaximum expression.
@return \qtism\runtime\common\MultipleContainer|null A MultipleContainer object with baseType float containing all the retrieved normalMaximum values or NULL if no declared maximum in the sub-set.
@throws \qtism\runtime\expressions\ExpressionProcessingException | public function process()
{
$itemSubset = $this->getItemSubset();
if (count($itemSubset) === 0) {
return null;
}
$testSession = $this->getState();
$outcomeIdentifier = $this->getExpression()->getOutcomeIdentifier();
// If no weightIdentifier specified, i... | csn |
Walk through commands. | def walk(self):
"""Walk through commands."""
yield self
if self.has_arguments():
for arg in self.args_definition:
if not arg["name"] in self.arguments:
continue
value = self.arguments[arg["name"]]
if type(value) == l... | csn |
Return a list of classes from external plugins that are used to
generate checker classes | def _get_generator_plugins(cls):
"""
Return a list of classes from external plugins that are used to
generate checker classes
"""
if not hasattr(cls, 'suite_generators'):
gens = working_set.iter_entry_points('compliance_checker.generators')
cls.suite_gene... | csn |
Remove a label | def remove_label(label)
unless label.valid?
errors.add(:label, "is not valid.")
return Trello.logger.warn "Label is not valid." unless label.valid?
end
client.delete("/cards/#{id}/idLabels/#{label.id}")
end | csn |
Upgrades the geometry to a feature geometry. | private static Geometry convertGeometry_(Geometry geometry, double tolerance) {
int gt = geometry.getType().value();
if (Geometry.isSegment(gt)) {
Polyline polyline = new Polyline(geometry.getDescription());
polyline.addSegment((Segment) geometry, true);
return polyline;
}
if (gt == Geometry.Geometry... | csn |
Downloads the binary file specified by content ID and field ID.
Assumes that the file is locally stored
Dispatch \Netgen\Bundle\SiteBundle\Event\SiteEvents::CONTENT_DOWNLOAD only once
@param \Symfony\Component\HttpFoundation\Request $request
@param mixed $contentId
@param mixed $fieldId
@param bool $isInline
@throw... | public function downloadFile(Request $request, $contentId, $fieldId, $isInline = false): BinaryStreamResponse
{
$content = $this->getSite()->getLoadService()->loadContent(
$contentId,
$request->query->get('version'),
$request->query->get('inLanguage')
);
... | csn |
Push an element onto an array that may not have been defined in
the dict | def push(self, my_dict, key, element):
''' Push an element onto an array that may not have been defined in
the dict '''
group_info = my_dict.setdefault(key, [])
if isinstance(group_info, dict):
host_list = group_info.setdefault('hosts', [])
host_list.append(elemen... | csn |
Return the base page class name from the PageYaml input
@return A {@link String} representation of the base page class. | public String getBaseClassName() {
CodeGeneratorLoggerFactory.getLogger().debug(
String.format("Reading base class name from data file [%s]", fileName));
String baseClass = reader.getBaseClassName();
if (baseClass == null) {
String path = new File(fileName).getAbsolut... | csn |
Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
Possibly has a `.dtype` attribute, a... | def maybe_infer_dtype_type(element):
"""Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
... | csn |
Show raw data in console even if verbose mode is not in force.
@param string $data The data to go in output.
@param boolean $newLine Whether to display a new line after $data. | protected function out($data, $newLine = true)
{
CliTools\out($data);
if ($newLine === true) {
CliTools\out("\n");
}
} | csn |
Generates settings that are specific to server. | protected function generateServerConfig(): void
{
$settings = [];
// Siteaccess match settings
$settings['ezpublish']['siteaccess']['match']['URIElement'] = '1';
// Config specific files
$kernelDir = $this->container->getParameter('kernel.project_dir') . '/' . $this->cont... | csn |
// Return the best match for cpuset list in the guest.
// The runtime caller may apply cpuset for specific CPUs in the host.
// The CPUs may not exist on the guest as they are hotplugged based
// on cpu and qouta.
// This function return a working cpuset to apply on the guest. | func getAvailableCpusetList(cpusetReq string) (string, error) {
cpusetGuest, err := getCpusetGuest()
if err != nil {
return "", err
}
cpusetListReq, err := parsers.ParseUintList(cpusetReq)
if err != nil {
return "", err
}
cpusetGuestList, err := parsers.ParseUintList(cpusetGuest)
if err != nil {
return... | csn |
Returns a boolean specifying whether or not the element corresponding to
the key has expired. Only returns true if element is in cache and has
expired. Error conditions return false, if no expireTable entry, returns
true. Always returns false if expireTime <= 0. Also, if SoftReference in
the CacheLine object has been c... | public boolean hasExpired(Object key) {
if (key == null)
return false;
CacheLine line = (CacheLine) cacheLineTable.get(key);
return hasExpired(line);
} | csn |
return a collection of set, in each set, all the fragments are connected | private static Collection<Set<Fragment>> getConnectedFragmentSets(Set<Fragment> allFragments) {
// TODO this could be implemented in a more readable way (eg. using a graph + BFS etc.)
final Map<Integer, Set<Variable>> varSetMap = new HashMap<>();
final Map<Integer, Set<Fragment>> fragmentSetMap ... | csn |
Create a cache key by concatenating the prefix with a hash of the path. | def get_cache_key(path):
"""
Create a cache key by concatenating the prefix with a hash of the path.
"""
# Python 2/3 support for path hashing
try:
path_hash = hashlib.md5(path).hexdigest()
except TypeError:
path_hash = hashlib.md5(path.encode('utf-8')).hexdigest()
return set... | csn |
// MAC returns the MAC address of the VM's first network interface. | func (d *Parallels9Driver) MAC(vmName string) (string, error) {
var stdout bytes.Buffer
cmd := exec.Command(d.PrlctlPath, "list", "-i", vmName)
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
log.Printf("MAC address for NIC: nic0 on Virtual Machine: %s not found!\n", vmName)
return "", err
}
stdoutSt... | csn |
//Send a DHCP Packet. | func (c *Client) SendPacket(packet dhcp4.Packet) error {
return c.connection.Write(packet)
} | csn |
// scanHeredoc scans a heredoc string | func (s *Scanner) scanHeredoc() {
// Scan the second '<' in example: '<<EOF'
if s.next() != '<' {
s.err("heredoc expected second '<', didn't see it")
return
}
// Get the original offset so we can read just the heredoc ident
offs := s.srcPos.Offset
// Scan the identifier
ch := s.next()
// Indented heredoc... | csn |
// NewMemberChangeNameType returns a new MemberChangeNameType instance | func NewMemberChangeNameType(Description string) *MemberChangeNameType {
s := new(MemberChangeNameType)
s.Description = Description
return s
} | csn |
Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and its dependency list, as given in the input
depen... | def dependency_sort(dependency_tree):
"""
Sorts items 'dependencies first' in a given dependency tree.
A dependency tree is a dictionary mapping an object to a collection its
dependency objects.
Result is a properly sorted list of items, where each item is a 2-tuple
containing an object and it... | csn |
Exports the database to a file or to STDOUT.
Runs `mysqldump` utility using `DB_HOST`, `DB_NAME`, `DB_USER` and
`DB_PASSWORD` database credentials specified in wp-config.php.
## OPTIONS
[<file>]
: The name of the SQL file to export. If '-', then outputs to STDOUT. If
omitted, it will be '{dbname}-{Y-m-d}-{random-has... | public function export( $args, $assoc_args ) {
if ( ! empty( $args[0] ) ) {
$result_file = $args[0];
} else {
// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_mt_rand -- WordPress is not loaded.
$hash = substr( md5( mt_rand() ), 0, 7 );
$result_file = sprintf( '%s-%s-%s.sql', DB_NAME, date(... | csn |
// Pubkey returns the public key represented by the node ID.
// It returns an error if the ID is not a point on the curve. | func (n NodeID) Pubkey() (*ecdsa.PublicKey, error) {
p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
half := len(n) / 2
p.X.SetBytes(n[:half])
p.Y.SetBytes(n[half:])
if !p.Curve.IsOnCurve(p.X, p.Y) {
return nil, errors.New("id is invalid secp256k1 curve point")
}
return p, nil
} | csn |
Find all Widgets for a given View.
@param View $view
@return Widget[] | public function findAllWidgetsForView(View $view)
{
$qb = $this->getAllForView($view);
return $qb->getQuery()->getResult();
} | csn |
Compares two dialects. | def dialect_compare(dialect1, dialect2):
"""
Compares two dialects.
"""
orig = set(dialect1.items())
new = set(dialect2.items())
return dict(
added=dict(list(new.difference(orig))),
removed=dict(list(orig.difference(new)))
) | csn |
Get a list of corporations the current
authenticated user has access to.
@deprecated replace by new ACL system. Must be move to ACL trait
@return mixed | public function getCharacterCorporations()
{
// TODO : rewrite the method according to the new ACL mechanic
$user = auth()->user();
$corporations = ApiKeyInfoCharacters::join(
'eve_api_keys',
'eve_api_keys.key_id', '=',
'account_api_key_info_characters.... | csn |
Returns an instance of Request based on the given options and client configuration.
@param array $options Array of options for this request.
@return GuzzleHttp\Psr7\Request Returns an initialized request. | private function getRequest($options)
{
$headers = isset($options['headers']) ? $options['headers'] : [];
$headers['User-Agent'] = 'sanity-php ' . Version::VERSION;
if (!empty($this->clientConfig['token'])) {
$headers['Authorization'] = 'Bearer ' . $this->clientConfig['token'];
... | csn |
clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip... | def _clean_up_columns(
self):
"""clean up columns of the NED table
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
... | csn |
Sets the maximum number of attempts to connect to a server
before giving up.
@api
@param integer|null $autoretrymax
@return integer | public function setAutoRetryMax($autoretrymax = null)
{
if (is_integer($autoretrymax)) {
if ($autoretrymax == 0) {
$this->setAutoRetry(false);
} else {
$this->_autoretrymax = $autoretrymax;
}
} else {
$this->_autoretryma... | csn |
Sets the provided host to current instance.
@param string $host The hostname
@return Uri The current instance with the provided host | protected function setHost($host)
{
$this->uriString = null;
$this->host = (string) $host;
return $this;
} | csn |
Helper method for complex_type_to_class | def fill_complex_type_properties(complex_type_xml, klass)
properties = complex_type_xml.xpath(".//*")
properties.each do |prop|
klass.send "#{prop.name}=", parse_value_xml(prop)
end
end | csn |
Configure a Py4J gateway.
:param launch_jvm: ``True`` to spawn a Java Virtual Machine in a subprocess and connect to
it, ``False`` to connect to an existing Py4J enabled JVM
:param gateway: either a :class:`~py4j.java_gateway.GatewayParameters` object or a
dictionary of keyword ... | def configure_gateway(
cls, launch_jvm: bool = True,
gateway: Union[GatewayParameters, Dict[str, Any]] = None,
callback_server: Union[CallbackServerParameters, Dict[str, Any]] = False,
javaopts: Iterable[str] = (), classpath: Iterable[str] = ''):
"""
Confi... | csn |
One of the task to be performed by a pool of subprocesses, as the first
step in identifying the cluster labels and indices of the cluster centers
for Affinity Propagation clustering. | def cluster_labels_A(hdf5_file, c, lock, I, rows_slice):
"""One of the task to be performed by a pool of subprocesses, as the first
step in identifying the cluster labels and indices of the cluster centers
for Affinity Propagation clustering.
"""
with Worker.hdf5_lock:
with tables.o... | csn |
reset the parameters
@return $this | public function resetQuery()
{
$this->_field_list = array(self::DEFAULT_FIELD);
$this->_param_list = array();
$this->_limit = array(self::DEFAULT_LIMIT);
$this->_where_list = array();
return $this;
} | csn |
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is a symlink or can't be read. | def get_path_uid(path):
# type: (str) -> int
"""
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is... | csn |
Returns this control word as an rtf string
@return string
@since 0.1.0 | protected function toRtf()
{
$rtf = '';
// if a word exists
if ($this->word) {
// if the word is ignored
if ($this->isIgnored) {
// prepend the ignored control symbol
$rtf = '\\*';
}
// append the word and its parameter
$rtf .= "\\{$this->word}{$this->parameter}";
// if the word is s... | csn |
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LocalQuota. | func (in *LocalQuota) DeepCopy() *LocalQuota {
if in == nil {
return nil
}
out := new(LocalQuota)
in.DeepCopyInto(out)
return out
} | csn |
Parse properties of an object
@param {any} obj Target object
@param {any} options Parser options
@returns {any} Parsed options | function (obj, options) {
debug('Parsing properties...');
debug('Object: %o', obj);
Object.keys(obj)
.map(key => {
let value = obj[key];
debug('Value: %o', value);
// parse current value
... | csn |
Retrieve every log event for a specific user id
Args:
user_id (str): The user_id of the logs to retrieve
page (int, optional): The result's page number (zero based).
per_page (int, optional): The amount of entries per page.
Default: 50. Max value: 100
... | def get_log_events(self, user_id, page=0, per_page=50, sort=None,
include_totals=False):
"""Retrieve every log event for a specific user id
Args:
user_id (str): The user_id of the logs to retrieve
page (int, optional): The result's page number (zero base... | csn |
Merge BoolOp operand type.
BoolOp are "and" and "or" and may return any of these results so all
operands should have the combinable type. | def visit_BoolOp(self, node):
"""
Merge BoolOp operand type.
BoolOp are "and" and "or" and may return any of these results so all
operands should have the combinable type.
"""
# Visit subnodes
self.generic_visit(node)
# Merge all operands types.
[... | csn |
Adds a new user.
@param username The username.
@param password The password.
@param roles A comma-separated list of roles that the new user will have. | @CommandArgument
public void adduser(
@OptionArgument("username") String username,
@OptionArgument("password") String password,
@OptionArgument("roles") String roles) {
if (users.containsKey(username)) {
System.err.println(String.format("User '%s' already exists", username));
} else {... | csn |
Adapts the dialog's positive button. | private void adaptPositiveButton() {
if (positiveButton != null) {
positiveButton.setText(positiveButtonText != null ?
positiveButtonText.toString().toUpperCase(Locale.getDefault()) : null);
OnClickListenerWrapper onClickListener =
new OnClickListe... | csn |
Added modal html
@return void | public function _edit_form_after_editor() {
$post_type = get_post_type();
if ( ! $post_type ) {
return;
}
if ( false === get_post_type_object( $post_type )->public ) {
return;
}
ob_start();
include( __DIR__ . '/view/modal.php' );
// @codingStandardsIgnoreStart
echo ob_get_clean();
// @codin... | csn |
Gets the primaryImageAsset value for this BaseImageCreative.
@return primaryImageAsset * The primary image asset associated with this creative. This
attribute is required. | public com.google.api.ads.admanager.axis.v201805.CreativeAsset getPrimaryImageAsset() {
return primaryImageAsset;
} | csn |
Find all the jobs that we'd previously been working on | def resumable(self):
'''Find all the jobs that we'd previously been working on'''
# First, find the jids of all the jobs registered to this client.
# Then, get the corresponding job objects
jids = self.client.workers[self.client.worker_name]['jobs']
jobs = self.client.jobs.get(*j... | csn |
If sudo is needed, make sure the command is prepended
correctly, otherwise return the command as it came.
:param sudo: A boolean representing the intention of having a sudo command
(or not)
:param command: A list of the actual command to execute with Popen. | def admin_command(sudo, command):
"""
If sudo is needed, make sure the command is prepended
correctly, otherwise return the command as it came.
:param sudo: A boolean representing the intention of having a sudo command
(or not)
:param command: A list of the actual command to execute... | csn |
subtract date on supported date
@param d date to subtract
@return <code>this</code> | public DateFuncSup subtract(DateSeperator d) {
date.setTime(date.getTime() - d.parse());
return this;
} | csn |
Initialise the database | public function install ()
{
parent::install();
any_db_query("ALTER TABLE oauth_consumer_registry MODIFY ocr_usa_id_ref int(11) unsigned");
any_db_query("ALTER TABLE oauth_consumer_token MODIFY oct_usa_id_ref int(11) unsigned not null");
any_db_query("ALTER TABLE oauth_server_registry MODIFY osr_usa_id_r... | csn |
Given a list of sample IDs generate unique n-base barcodes for each.
Note that only 4^n unique barcodes are possible. | def generate_barcodes(nIds, codeLen=12):
"""
Given a list of sample IDs generate unique n-base barcodes for each.
Note that only 4^n unique barcodes are possible.
"""
def next_code(b, c, i):
return c[:i] + b + (c[i+1:] if i < -1 else '')
def rand_base():
return random.choice(['A... | csn |
verifies the entire string is upper case and contains eventually an underscore used to avoid RegExp for non RegExp aware environment | function isPublicStatic(key) {
for(var c, i = 0; i < key.length; i++) {
c = key.charCodeAt(i);
if ((c < 65 || 90 < c) && c !== 95) {
return false;
}
}
return true;
} | csn |
Removes prefixes defined in array from string.
Example:
<code>
$string = 'prefixRest';
$withoutPrefix = Strings::removePrefixes($string, array('pre', 'fix'));
</code>
Result:
<code>
Rest
</code>
@param string $string
@param array $prefixes
@return mixed | public static function removePrefixes($string, array $prefixes)
{
return array_reduce($prefixes, function ($string, $prefix) {
return Strings::removePrefix($string, $prefix);
}, $string);
} | csn |
Get a collection of items
@param array $params
@return Daursu\Xero\BaseModel | public static function get($params = array())
{
$object = new static;
$data = $object->request('GET', $object->getUrl(), $params);
$data = $object->stripResponseData($data);
// Initialise a collection
$collection = self::newCollection();
if (isset($data[0]) && is_array($data[0])) {
// This should ... | csn |
Returns the runtime type for the message correspdoning to the given descriptor.. | public static Type protoType(Descriptor descriptor) {
return Type.getType('L' + JavaQualifiedNames.getClassName(descriptor).replace('.', '/') + ';');
} | csn |
RECORDSET FUNCTIONS
Returns Record index for given TR element or page row index.
@method getRecordIndex
@param row {YAHOO.widget.Record | HTMLElement | Number} Record instance, TR
element reference or page row index.
@return {Number} Record's RecordSet index, or null. | function(row) {
var nTrIndex;
if(!lang.isNumber(row)) {
// By Record
if(row instanceof YAHOO.widget.Record) {
return this._oRecordSet.getRecordIndex(row);
}
// By element reference
else {
// Find the TR element
var el = this.getTrEl(ro... | csn |
Processes a format specifier sequence.
@param c initial character of format specifier.
@param pattern conversion pattern
@param i current position in conversion pattern.
@param currentLiteral current literal.
@param formattingInfo current field specifier.
@param converterRegistry map of user-provided pattern converter... | private static int finalizeConverter(
char c, String pattern, int i,
final StringBuffer currentLiteral, final ExtrasFormattingInfo formattingInfo,
final Map converterRegistry, final Map rules, final List patternConverters,
final List formattingInfos) {
StringBuffer convBuf = new StringBuffer();
... | csn |
Instantly aborts the WebSocket connection by closing the socket | def _abort(self) -> None:
"""Instantly aborts the WebSocket connection by closing the socket"""
self.client_terminated = True
self.server_terminated = True
if self.stream is not None:
self.stream.close() # forcibly tear down the connection
self.close() | csn |
Fetches information for a lbaas_listener. | def show_listener(self, lbaas_listener, **_params):
"""Fetches information for a lbaas_listener."""
return self.get(self.lbaas_listener_path % (lbaas_listener),
params=_params) | csn |
remove the semaphore resource
@return bool | public function remove()
{
if ($this->locked) {
throw new \RuntimeException('can not remove a locked semaphore resource');
}
if (!is_resource($this->lock_id)) {
throw new \RuntimeException('can not remove a empty semaphore resource');
}
if (!sem_relea... | csn |
Returns the number of parameters in the network
@param backwards If true: exclude any parameters uned only in unsupervised layerwise training (such as the decoder
parameters in an autoencoder)
@return The number of parameters | @Override
public long numParams(boolean backwards) {
int length = 0;
for (int i = 0; i < layers.length; i++)
length += layers[i].numParams(backwards);
return length;
} | csn |
END ODO CHANGES | private void startRelayWithPortTollerance(HttpServer server, SslListener relay, int tries) throws Exception {
if (tries >= 5) {
throw new BindException("Unable to bind to several ports, most recently " + relay.getPort() + ". Giving up");
}
try {
if (server.isStarted()) {
... | csn |
Send an email notification to sender
@param string $message Message to put in the body of the email
@param array $mappedVars Inbound POST vars mapped to database fields
@return void | public function sendEmailNotificationToSender($message, $mappedVars) {
// Prep the email
$data = $this->prepareNotificationEmailData($message, $mappedVars);
// What blade file to use?
$emailBladeFile = 'lasallecmsemail::email.notification_email_to_inbound_sender';
// Send da e... | csn |
Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form
#style ID -> SVG style dictionary,
and return the result.
The possible keys and values of each SVG style dictionary, the style options, are
- ``iconUrl``: ... | def build_svg_style(node):
"""
Given a DOM node, grab its top-level Style nodes, convert every one into a SVG style dictionary, put them in a master dictionary of the form
#style ID -> SVG style dictionary,
and return the result.
The possible keys and values of each SVG style dictionary, the ... | csn |
Finalize outputs.
Args:
mapreduce_spec: an instance of MapreduceSpec.
mapreduce_state: an instance of MapreduceState. | def _finalize_outputs(cls, mapreduce_spec, mapreduce_state):
"""Finalize outputs.
Args:
mapreduce_spec: an instance of MapreduceSpec.
mapreduce_state: an instance of MapreduceState.
"""
# Only finalize the output writers if the job is successful.
if (mapreduce_spec.mapper.output_writer_... | csn |
Process unrecognized fields in message. | def _DecodeUnrecognizedFields(message, pair_type):
"""Process unrecognized fields in message."""
new_values = []
codec = _ProtoJsonApiTools.Get()
for unknown_field in message.all_unrecognized_fields():
# TODO(craigcitro): Consider validating the variant if
# the assignment below doesn't ... | csn |
Sets the smartSizeMode value for this AdUnit.
@param smartSizeMode * The smart size mode for this ad unit. This attribute is optional
and defaults to {@link
SmartSizeMode#NONE} for fixed sizes. | public void setSmartSizeMode(com.google.api.ads.admanager.axis.v201811.SmartSizeMode smartSizeMode) {
this.smartSizeMode = smartSizeMode;
} | csn |
Load and transform an image. | def get_image(self, img, is_train):
"""Load and transform an image."""
img_arr = mx.image.imread(img)
img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
return img_arr | csn |
// initListeners - initializes PeerREST clients available in listener.json. | func (sys *NotificationSys) initListeners(ctx context.Context, objAPI ObjectLayer, bucketName string) error {
// listener.json is available/applicable only in DistXL mode.
if !globalIsDistXL {
return nil
}
// Construct path to listener.json for the given bucket.
configFile := path.Join(bucketConfigPrefix, bucke... | csn |
// MaybeUpdateKEK does a KEK rotation if one is required. Returns whether
// the kek was updated, whether it went from unlocked to locked, and any errors. | func (r *RaftDEKManager) MaybeUpdateKEK(candidateKEK ca.KEKData) (bool, bool, error) {
var updated, unlockedToLocked bool
err := r.kw.ViewAndRotateKEK(func(currentKEK ca.KEKData, h ca.PEMKeyHeaders) (ca.KEKData, ca.PEMKeyHeaders, error) {
var err error
updated, unlockedToLocked, err = compareKEKs(currentKEK, cand... | csn |
// MemoryRestGetVirtual gets the virtual memory via GET request. | func MemoryRestGetVirtual(context *gin.Context) {
body, err := memory.ServiceGetVirtualMemory()
util.RestHandleResponse(context, body, err)
} | csn |
Initializes Dwoo_ITemplate type of class and sets properties from _templateFileSettings
@param string Template location
@return Dwoo_ITemplate | public function getTemplateFile($template) {
$templateFileClass = $this->_templateFileClass;
$dwooTemplateFile = new $templateFileClass($template);
if (!($dwooTemplateFile instanceof Dwoo_ITemplate)) {
throw new Dwoo_Exception("Custom templateFile class must be a subclass of Dwoo_ITemplate");
}
fore... | csn |
Return the raw source line corresponding to the specified AST node
@param node - the Groovy AST node | protected String sourceLine(ASTNode node) {
return sourceCode.getLines().get(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);
} | csn |
Prepend the message if it is non-null. | private void prependMessage( String s )
{
if ( s == null )
return;
if ( message == null )
message = s;
else
message = s + " : "+ message;
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.