query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Creates an audit entry for the 'client registered' event.
@param bean the bean
@param securityContext the security context
@return the audit entry | public static AuditEntryBean clientRegistered(ClientVersionBean bean,
ISecurityContext securityContext) {
AuditEntryBean entry = newEntry(bean.getClient().getOrganization().getId(), AuditEntityType.Client, securityContext);
entry.setEntityId(bean.getClient().getId());
entry.setEntity... | csn |
Set options on current Renderer. | def _set_render_options(cls, options, backend=None):
"""
Set options on current Renderer.
"""
if backend:
backend = backend.split(':')[0]
else:
backend = Store.current_backend
cls.set_backend(backend)
if 'widgets' in options:
o... | csn |
func (c *Client) GetDirector(i *GetDirectorInput) (*Director, error) {
if i.Service == "" {
return nil, ErrMissingService
}
if i.Version == 0 {
return nil, ErrMissingVersion
}
if i.Name == "" {
return nil, ErrMissingName
}
path := fmt.Sprintf("/service/%s/version/%d/director/%s", i.Service, i.Version, i... | err := c.Get(path, nil)
if err != nil {
return nil, err
}
var d *Director
if err := decodeJSON(&d, resp.Body); err != nil {
return nil, err
}
return d, nil
} | csn_ccr |
protected function redirect($url, $code = 302)
{
$this->response->setStatusCode($code); |
$this->response->headers->set('Location', $url);
return $this->response;
} | csn_ccr |
function hasStringLiteral(node) {
if (isConcatenation(node)) {
// `left` is deeper than `right` normally.
| return hasStringLiteral(node.right) || hasStringLiteral(node.left);
}
return astUtils.isStringLiteral(node);
} | csn_ccr |
Implement a magic directory with buildDict, and search methods.
For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.
For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified wor... | class MagicDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.l = []
def buildDict(self, dict):
"""
Build a dictionary through a list of words
:type dict: List[str]
:rtype: void
"""
sel... | apps |
public function facetRolesFormAction(Facet $facet)
{
$roles = $facet->getRoles();
$platformRoles = $this->roleManager->getPlatformNonAdminRoles(true);
| return array('roles' => $roles, 'facet' => $facet, 'platformRoles' => $platformRoles);
} | csn_ccr |
def ensure_frequencies(self, frequencies):
"""Ensure frequencies is dict of host-frequencies."""
if not frequencies:
return {}
if not isinstance(frequencies, | dict):
raise ValueError("frequencies should be dict")
frequencies = {
host: Frequency.ensure_frequency(frequencies[host]) for host in frequencies
}
return frequencies | csn_ccr |
public static function jsIncTag($path)
{
if (strpos($path, 'http') === false and strpos($path, '//') === false) | {
$path = Request::basePath($path);
}
return '<script src="' . $path . '" type="text/javascript"></script>' . PHP_EOL;
} | csn_ccr |
func (env *Environment) GetArray(key string, overrideDefault *[]string) ([]string, error) {
var oD *string
if overrideDefault != nil {
if len(*overrideDefault) > 0 {
| ovr := (*overrideDefault)[0]
oD = &ovr
}
}
v, e := env.Get(key, oD)
arr := []string{v}
if env.supportArrays {
if strings.Contains(v, ",") {
arr = strings.Split(v, ",")
}
}
if len(v) > 0 {
return arr, e
}
return []string{}, e
} | csn_ccr |
protected function exchangeToken() {
$result = $this->requestAccessToken();
if ($result && !empty($result['access_token'])) {
$this->accessToken = $result['access_token'];
$this->sessionStorage->write('access_token', $result['access_token']);
if (!empty($result['refre... | $this->validateIdToken($result['id_token']);
$this->user = $this->requestUserInfo();
if ($this->user) {
$this->sessionStorage->write('user', $this->user);
}
}
}
} | csn_ccr |
function( index, callback ) {
var scope = this;
var shot = scope.shots[ index|0 ];
if( ! shot ) {
throw new Error(
| "Shot number " + index + " not found"
);
return;
}
return shot;
} | csn_ccr |
Determines if queue is busy
=== Return
active(Boolean):: true if queue is busy | def busy?
busy = false
@mutex.synchronize { busy = @thread_name_to_queue.any? { |_, q| q.busy? } }
busy
end | csn |
print ordered dict python | def pprint_for_ordereddict():
"""
Context manager that causes pprint() to print OrderedDict objects as nicely
as standard Python dictionary objects.
"""
od_saved = OrderedDict.__repr__
try:
OrderedDict.__repr__ = dict.__repr__
yield
finally:
OrderedDict.__repr__ = od_... | cosqa |
public function evalSha($sha, array $arguments = array()) {
try {
if (empty($arguments)) {
$result = $this->getRedis()->evalSha($sha);
} else {
$result = $this->getRedis()->evalSha($sha, $arguments, count($arguments));
| }
$lastError = $this->getRedis()->getLastError();
$this->getRedis()->clearLastError();
if (is_null($lastError)) {
return $result;
}
throw new ScriptExecutionException($lastError);
} catch (RedisException $ex) {
th... | csn_ccr |
public <X extends Throwable> V getValueOrElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
LettuceAssert.notNull(exceptionSupplier, "Supplier | function must not be null");
if (hasValue()) {
return value;
}
throw exceptionSupplier.get();
} | csn_ccr |
private function compileBreaker($expression, $lexic, $o_lexic)
{
$output = preg_replace_callback(
"/($lexic *(\(.+?\))|$lexic)/s",
function ($match) use ($lexic, $o_lexic) {
array_shift($match);
if (trim($match[0]) == $lexic) {
ret... |
return "<?php if {$match[1]}: $o_lexic; endif; ?>";
},
$expression
);
return $output == $expression ? '' : $output;
} | csn_ccr |
Return an array of stores for the given website and attach a language code to them, Varien_Object style
@param mixed $website the website to get stores from.
@param string $langCode (optional) if passed, only stores using that langCode are returned.
@return array of Mage_Core_Model_Store, keyed by StoreId. Each store... | public function getWebsiteStores($website, $langCode = null)
{
$stores = array();
$config = Mage::helper('radial_core')->getConfigModel();
$website = Mage::app()->getWebsite($website);
foreach ($website->getGroups() as $group) {
foreach ($group->getStores() as $store) {
... | csn |
Get the compliance level of the output file. | def get_compliance(self, filename):
"""Get the compliance level of the output file."""
print('Running Compliance Check on {}'.format(filename))
print('#' * 80)
start_time, status, dt, qual, target = mlp_compliance.l2_check_file_w_starttime(
filename)
print('#' * 80)
if status:
lev... | csn |
def get_critical_line_loading(grid):
"""
Assign line loading to each branch determined by peak load and peak
generation of descendant branches
The attribute `s_res` is a list of two elements
1. apparent power in load case
2. apparent power in feed-in case
Parameters
----------
grid... | peak_load / cos_phi_load,
peak_gen / cos_phi_feedin]})
else:
# preceeding node of node
predecessors = list(tree.predecessors(node))
# a non-meshed grid topology returns a list with only 1 item
predecessor = predecessors[0]
... | csn_ccr |
Return the web element from a page element or its locator
:param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value)
:returns: WebElement object | def get_web_element(self, element):
"""Return the web element from a page element or its locator
:param element: either a WebElement, PageElement or element locator as a tuple (locator_type, locator_value)
:returns: WebElement object
"""
from toolium.pageelements.page_element im... | csn |
Loads the FAQ's
@return Faq[] | public function loadFaqs() : array
{
return $this->repository->matching(
$this->repository->criteria()
->orderByAsc(Faq::ORDER_TO_DISPLAY)
);
} | csn |
Update the competency settings for a course.
Requires moodle/competency:coursecompetencyconfigure capability at the course context.
@param int $courseid The course id
@param stdClass $settings List of settings. The only valid setting ATM is pushratginstouserplans (boolean).
@return bool | public static function update_course_competency_settings($courseid, $settings) {
static::require_enabled();
$settings = (object) $settings;
// Get all the valid settings.
$pushratingstouserplans = isset($settings->pushratingstouserplans) ? $settings->pushratingstouserplans : false;
... | csn |
set every cell in matrix to 0 if that row or column contains a 0 python | def check_precomputed_distance_matrix(X):
"""Perform check_array(X) after removing infinite values (numpy.inf) from the given distance matrix.
"""
tmp = X.copy()
tmp[np.isinf(tmp)] = 1
check_array(tmp) | cosqa |
def convert_from_sliced_object(data):
"""Fix the memory of multi-dimensional sliced object."""
if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray):
| if not data.flags.c_contiguous:
warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended "
"due to it will double the peak memory cost in LightGBM.")
return np.copy(data)
return data | csn_ccr |
private function doWarm(array $types)
{
$warmed = [];
$this->doClear($types);
foreach ($types as $type) {
| $this->mf->getMetadataForType($type);
$warmed[] = $type;
}
return $warmed;
} | csn_ccr |
public static function get_by_version($version) {
$migrations = self::get_all();
if (strpos($version, '/') === false) {
$version = 'project/' . $version;
}
list($package, $version) = explode('/', $version);
$migrations = \Skeleton\Database\Migration::get_between_versions($package);
foreach ($migration... | $classname = $matches[1];
} else {
$classname = get_class($migration);
}
if ($version == $classname) {
return $migration;
}
}
throw new \Exception('The specified version does not exists.');
} | csn_ccr |
public function getTXOsByHash($wallet_uuid, $address_hash, $page = 0)
{
$parameters = [
'hash' => $address_hash,
'pg' => (string) $page,
];
| return $this->newAPIRequest('GET', $wallet_uuid . '/address/txos', $parameters);
} | csn_ccr |
// NewGRPCService returns an envelope.Service which use gRPC to communicate the remote KMS provider. | func NewGRPCService(endpoint string, callTimeout time.Duration) (Service, error) {
klog.V(4).Infof("Configure KMS provider with endpoint: %s", endpoint)
addr, err := parseEndpoint(endpoint)
if err != nil {
return nil, err
}
connection, err := grpc.Dial(addr, grpc.WithInsecure(), grpc.WithDefaultCallOptions(grp... | csn |
Unlock the keychain using the provided password
@param [String] the password to open the keychain | def unlock(password)
cmd = Xcode::Shell::Command.new "security"
cmd << "unlock-keychain"
cmd << "-p #{password}"
cmd << "\"#{@path}\""
cmd.execute
end | csn |
Shut down after N seconds.
@param int $seconds
@return self | public function stopAfter(int $seconds): self
{
$seconds = 0 >= $seconds ? 1 : $seconds;
/** @psalm-suppress MixedTypeCoercion Incorrect amphp types */
Loop::delay(
$seconds * 1000,
function() use ($seconds): void
{
/** @var LoggerInterfac... | csn |
Recursively duplicate competencies from a tree, we start duplicating from parents to children to have a correct path.
This method does not copy the related competencies.
@param int $frameworkid - framework id
@param competency[] $tree - array of competencies object
@param int $oldparent - old parent id
@param int $new... | protected static function duplicate_competency_tree($frameworkid, $tree, $oldparent = 0, $newparent = 0) {
$matchids = array();
foreach ($tree as $node) {
if ($node->competency->get('parentid') == $oldparent) {
$parentid = $node->competency->get('id');
// Cre... | csn |
Method checking whether or not the sip servlet request in parameter is initial
according to algorithm defined in JSR289 Appendix B
@param sipServletRequest the sip servlet request to check
@param dialog the dialog associated with this request
@return true if the request is initial false otherwise | private static RoutingState checkRoutingState(SipServletRequestImpl sipServletRequest, Dialog dialog) {
// 2. Ongoing Transaction Detection - Employ methods of Section 17.2.3 in RFC 3261
//to see if the request matches an existing transaction.
//If it does, stop. The request is not an initial request.
if(dialog... | csn |
Given part of a sequence ID, find the first actual ID that contains it.
Example::
>>> find_seq_id(block, '2QG5')
'gi|158430190|pdb|2QG5|A'
Raise a ValueError if no matching key is found. | def find_seq_id(block, name, case_sensitive=True):
"""Given part of a sequence ID, find the first actual ID that contains it.
Example::
>>> find_seq_id(block, '2QG5')
'gi|158430190|pdb|2QG5|A'
Raise a ValueError if no matching key is found.
"""
# logging.warn("DEPRECATED: Try to u... | csn |
def home(self) -> str:
"""
Return the robot to the home position and update the position tracker
"""
| self.hardware.home()
self.current_position = self._position()
return 'Homed' | csn_ccr |
PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END | function merge() {
var observables = [];
for (var _i = 0; _i < arguments.length; _i++) {
observables[_i] = arguments[_i];
}
var concurrent = Number.POSITIVE_INFINITY;
var scheduler = null;
var last = observables[observables.length - 1];
if (Object(_util_isScheduler__WEBPACK_IMPORTED_... | csn |
Method to get the department name | def get_dept_name(self):
"""Method to get the department name"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("name", None) | csn |
func (a customResourceStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
if utilfeature.DefaultFeatureGate.Enabled(apiextensionsfeatures.CustomResourceSubresources) && a.status != nil {
| customResourceObject := obj.(*unstructured.Unstructured)
customResource := customResourceObject.UnstructuredContent()
// create cannot set status
if _, ok := customResource["status"]; ok {
delete(customResource, "status")
}
}
accessor, _ := meta.Accessor(obj)
accessor.SetGeneration(1)
} | csn_ccr |
def _from_dict(cls, _dict):
"""Initialize a Collection object from a json dictionary."""
args = {}
if 'collection_id' in _dict:
args['collection_id'] = _dict.get('collection_id')
if 'name' in _dict:
args['name'] = _dict.get('name')
if 'description' in _dic... | if 'status' in _dict:
args['status'] = _dict.get('status')
if 'configuration_id' in _dict:
args['configuration_id'] = _dict.get('configuration_id')
if 'language' in _dict:
args['language'] = _dict.get('language')
if 'document_counts' in _dict:
arg... | csn_ccr |
Filters out samples that have already been used for training.
@param int[] $sampleids
@param \core_analytics\local\time_splitting\base $timesplitting
@return null | protected function filter_out_train_samples(array &$sampleids, \core_analytics\local\time_splitting\base $timesplitting) {
global $DB;
$params = array('modelid' => $this->analyser->get_modelid(), 'analysableid' => $timesplitting->get_analysable()->get_id(),
'timesplitting' => $timesplitting... | csn |
public function getContext($options = []) {
$url = $this->getBaseURI();
if (count($options) > 0) {
| $prefix = ($this->_type) ? "&" : "?";
$url .= $prefix . urldecode(http_build_query($options));
}
return $this->_orion->get($url);
} | csn_ccr |
contains method
check if child is contained in this element
@param {(string|object)} child - element or css selector
@return {boolean} | function(child) {
return this.length ? (/^o/.test(typeof child) ? this[0] !== child[0] && this[0].contains(child[0]) : this[0].querySelector(child) !== null) : false;
} | csn |
Returns the reference to the array of the session variables.
@return array
Returns the reference to the array of the session variables.
The reason of this interacfe is to wrap the standard session
handling to be able to flexibly change the implementation without
any change in the code where it is used.
Thus, we cann... | public function &vars()
{
if (empty($_SESSION[$this->getContext()])) {
$_SESSION[$this->getContext()] = [];
}
return $_SESSION[$this->getContext()];
} | csn |
// CreateContainer creates a new container with the given name while returning a
// container instance with the given information. | func (l *location) CreateContainer(name string) (stow.Container, error) {
err := l.client.ContainerCreate(name, nil)
if err != nil {
return nil, err
}
container := &container{
id: name,
client: l.client,
}
return container, nil
} | csn |
Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
a maintenance task that should be run under ve... | def tag(check, version, push, dry_run):
"""Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
... | csn |
def list_enrollment_terms(self, account_id, workflow_state=None):
"""
List enrollment terms.
Return all of the terms in the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"... | self.logger.debug("GET /api/v1/accounts/{account_id}/terms with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("GET", "/api/v1/accounts/{account_id}/terms".format(**path), data=data, params=params, data_key='enrollment_terms', all_pages=True... | csn_ccr |
// GetRemoteClusters returns remote clusters with updated statuses | func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) {
// To make sure remote cluster exists - to protect against random
// clusterName requests (e.g. when clusterName is set to local cluster name)
remoteClusters, err := a.Presence.GetRemoteClusters(opts...)
if er... | csn |
Store the user deleting a record.
@param \Illuminate\Database\Eloquent\Model $model | public function deleting($model)
{
if ($model->accountableEnabled() &&
collect(class_uses($model))->contains(SoftDeletes::class)) {
$model->{$this->config['column_names']['deleted_by']} = $this->accountableUserId();
$model->save();
}
} | csn |
Convert a string URI to an object URI.
<p>This function support the syntax ":*" for the port.
@param uri the string representation of the URI to parse.
@return the URI.
@throws URISyntaxException - if the given string has invalid format. | public static URI toURI(String uri) throws URISyntaxException {
final URI u = new URI(uri);
// Inspired by ZeroMQ
String adr = u.getAuthority();
if (adr == null) {
adr = u.getPath();
}
if (adr != null && adr.endsWith(":*")) { //$NON-NLS-1$
return new URI(u.getScheme(), u.getUserInfo(), adr.substring(0... | csn |
def convert (val)
return nil if val.blank? and val != false
if @type == String
return val.to_s
elsif @type == Integer
return Kernel.Integer(val) rescue val
elsif @type == Float
return Kernel.Float(val) rescue val
elsif @type == Boolean
v = BOOLEAN_MAPPING[va... | val = [val] unless val.is_a?(Array)
raise ArgumentError.new("#{name} must be an Array") unless val.is_a?(Array)
return val
elsif @type == Hash
raise ArgumentError.new("#{name} must be a Hash") unless val.is_a?(Hash)
return val
elsif @type == BigDecimal
return BigDec... | csn_ccr |
public void delete(String cfName, WriteOptions writeOptions, String key)
throws RocksDbException {
if (cfName == null) {
cfName = DEFAULT_COLUMN_FAMILY;
}
try {
delete(getColumnFamilyHandle(cfName), writeOptions,
| key.getBytes(StandardCharsets.UTF_8));
} catch (RocksDbException.ColumnFamilyNotExists e) {
throw new RocksDbException.ColumnFamilyNotExists(cfName);
}
} | csn_ccr |
def filter(self, criteria: Q, offset: int = 0, limit: int = 10, order_by: list = ()):
"""Read the repository and return results as per the filer"""
if criteria.children:
items = list(self._filter(criteria, self.conn['data'][self.schema_name]).values())
else:
items = list... | reverse = True
o_key = o_key[1:]
items = sorted(items, key=itemgetter(o_key), reverse=reverse)
result = ResultSet(
offset=offset,
limit=limit,
total=len(items),
items=items[offset: offset + limit])
return result | csn_ccr |
how to make multi lined code in python | def make_html_code( self, lines ):
""" convert a code sequence to HTML """
line = code_header + '\n'
for l in lines:
line = line + html_quote( l ) + '\n'
return line + code_footer | cosqa |
public static function get_by_info($info, $update_oauth_token=true) {
$mysql = bootstrap::get_library('mysql');
// find via the oauth token
$sql = "SELECT * FROM `login_github` WHERE `oauth_token` = '%s';";
$login = $mysql::select('row', $sql, $info['oauth_token']);
if (!empty($login)) {
return new static($l... | return false;
}
$object = new static($login['id']);
// keep token up to date
if ($update_oauth_token && $info['oauth_token'] != $login['oauth_token']) {
$object->update_oauth_token($info['oauth_token']);
}
return $object;
} | csn_ccr |
Gets a resource query session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.ResourceQuerySession) - ``a
ResourceQuerySession``
raise: NotFound - ``bin_id`` not found
raise: ... | def get_resource_query_session_for_bin(self, bin_id, proxy):
"""Gets a resource query session for the given bin.
arg: bin_id (osid.id.Id): the ``Id`` of the bin
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.ResourceQuerySession) - ``a
ResourceQueryS... | csn |
// podListMetrics returns a list of metric timeseries for each for the listed nodes | func (a *HistoricalApi) podListMetrics(request *restful.Request, response *restful.Response) {
start, end, err := getStartEndTimeHistorical(request)
if err != nil {
response.WriteError(http.StatusBadRequest, err)
return
}
keys := []core.HistoricalKey{}
if request.PathParameter("pod-id-list") != "" {
for _, ... | csn |
private function getWhereClause()
{
if (empty($this->where)) {
return '';
}
$result = [];
foreach ($this->where as $key => $value) {
$result[] | = $this->getWhereCondition($value[0], $value[1], $value[2]);
}
return sprintf('WHERE %s', implode(' AND ', $result));
} | csn_ccr |
Creates a new time duration from given seconds and nanoseconds.
@param seconds Signed seconds of the span of time. Must be from -315,576,000,000 to
+315,576,000,000 inclusive.
@param nanos Signed fractions of a second at nanosecond resolution of the span of time.
Durations less than one second are represented with a 0... | public static Duration create(long seconds, int nanos) {
if (seconds < -MAX_SECONDS) {
throw new IllegalArgumentException(
"'seconds' is less than minimum (" + -MAX_SECONDS + "): " + seconds);
}
if (seconds > MAX_SECONDS) {
throw new IllegalArgumentException(
"'seconds' is gr... | csn |
Wizard to create the user-level configuration file. | def setup(ctx, force):
"""Wizard to create the user-level configuration file."""
if os.path.exists(USER_CONFIG) and not force:
click.secho(
'An existing configuration file was found at "{}".\n'
.format(USER_CONFIG),
fg='red', bold=True
)
click.secho(
... | csn |
private AbstractChainedGlobalProcessor<T> addOrCreateChain(AbstractChainedGlobalProcessor<T> chain, String key) {
AbstractChainedGlobalProcessor<T> toAdd;
if (customPostprocessors.get(key) == null) {
toAdd = buildProcessorByKey(key);
} else {
toAdd = (AbstractChainedGlobalProcessor<T>) customPostprocessor... | toAdd);
}
AbstractChainedGlobalProcessor<T> newChainResult = null;
if (chain == null) {
newChainResult = toAdd;
} else {
chain.addNextProcessor(toAdd);
newChainResult = chain;
}
return newChainResult;
} | csn_ccr |
func Convert_core_ServiceList_To_v1_ServiceList(in *core.ServiceList, out *v1.ServiceList, s conversion.Scope) error { |
return autoConvert_core_ServiceList_To_v1_ServiceList(in, out, s)
} | csn_ccr |
public String decode(String text) {
if (text == null) { return null; }
if ((!text.startsWith(Prefix)) || (!text.endsWith(Postfix)))
throw new IllegalArgumentException("RFC 1522 violation: malformed encoded content");
int terminator = text.length() - 2;
int from = 2;
int to = text.indexOf(Sep, ... | if (to == terminator) throw new IllegalArgumentException("RFC 1522 violation: encoding token not found");
String encoding = text.substring(from, to);
if (!getEncoding().equalsIgnoreCase(encoding))
throw new IllegalArgumentException("This codec cannot decode " + encoding + " encoded content");
from... | csn_ccr |
Allows the use of Pythonic-style parameters with underscores instead of camel-case.
:param parameters: The parameters object.
:type parameters: dict
:return: The processed parameters.
:rtype: dict | def process_parameters(parameters):
"""Allows the use of Pythonic-style parameters with underscores instead of camel-case.
:param parameters: The parameters object.
:type parameters: dict
:return: The processed parameters.
:rtype: dict
"""
if not parameters:
return {}
params = c... | csn |
// mainHashArgs returns the args for the hash which will store the job data | func (j *Job) mainHashArgs() []interface{} {
hashArgs := []interface{}{j.Key(),
"data", string(j.data),
"type", j.typ.name,
"time", j.time,
"freq", j.freq,
"priority", j.priority,
"retries", j.retries,
"status", j.status,
"started", j.started,
"finished", j.finished,
"poolId", j.poolId,
}
if j.er... | csn |
import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import math
import numpy as np
import paddle
from paddle import nn
true_w, features, poly_features, labels = [paddle.to_tensor(x, dtype=
paddle.float32) for x in [true_w, features, poly_features, labels]]
features[:2], poly_features[:2,... | import math
import numpy as np
import torch
from torch import nn
from d2l import torch as d2l
true_w, features, poly_features, labels = [torch.tensor(x, dtype=torch.float32) for x in [true_w, features, poly_features, labels]]
features[:2], poly_features[:2, :], labels[:2]
def train(train_features, test_features, train_... | codetrans_dl |
Returns the metric description.
@param metricName the initial metric name
@param metric the codahale metric class.
@return a String the custom metric description | static String generateFullMetricDescription(String metricName, Metric metric) {
return "Collected from "
+ SOURCE
+ " (metric="
+ metricName
+ ", type="
+ metric.getClass().getName()
+ ")";
} | csn |
function( array ) {
var i;
if ( this.array ) {
for ( i = 0; i < this.array.length; i++ ) {
delete this.array[i];
}
}
this.array | = array;
for ( i = 0; i < array.length; i++ ) {
this[i] = this.array[i];
}
return this;
} | csn_ccr |
Get fields definitions.
@return array | public function getFields()
{
// Fetch fields when the method is called for the first time.
if ( $this->fields === null ) {
$fields = array();
$result = $this->api(self::REQUEST_GET, '/rest/api/2/field', array(), true);
/* set hash key as custom field id */
foreach ( $result as $field ) {
$fields[... | csn |
@Override
public synchronized void messagingEngineStopping(
final JsMessagingEngine messagingEngine, final int mode)
{
final String methodName = "messagingEngineStopping";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
... | }
SibTr.info(TRACE, "ME_STOPPING_CWSIV0784", new Object[] {
messagingEngine.getName(),
messagingEngine.getBus() });
// dropConnection (messagingEngine.getUuid().toStr... | csn_ccr |
Syntactically and semantically checks a call or new expression.
@param node The call/new expression to be checked.
@returns On success, the expression's signature's return type. On failure, anyType. | function checkCallExpression(node) {
// Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true
checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments);
var signature = getResolvedSignature(node);
if (nod... | csn |
python is or not symlink | def is_symlink(self):
"""
Whether this path is a symbolic link.
"""
try:
return S_ISLNK(self.lstat().st_mode)
except OSError as e:
if e.errno != ENOENT:
raise
# Path doesn't exist
return False | cosqa |
protected function addgroup_hostnames(){
$this->registerGroup(BLang::_('ADMIN_CONFIG_GENERAL_HOSTNAMES'),'hostnames',array(
new BConfigFieldString(
'BHOSTNAME',
BLang::_('ADMIN_CONFIG_GENERAL_BHOSTNAME'),
'vidido.ua'),
new BConfigFieldString(
'BHOSTNAME_STATIC',
| BLang::_('ADMIN_CONFIG_GENERAL_BHOSTNAME_STATIC'),
'static.vidido.ua'),
new BConfigFieldString(
'BHOSTNAME_MEDIA',
BLang::_('ADMIN_CONFIG_GENERAL_BHOSTNAME_MEDIA'),
'media.vidido.ua')
));
} | csn_ccr |
def get_instance(self, payload):
"""
Build an instance of BindingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.notify.v1.service.binding.BindingInstance
| :rtype: twilio.rest.notify.v1.service.binding.BindingInstance
"""
return BindingInstance(self._version, payload, service_sid=self._solution['service_sid'], ) | csn_ccr |
func (s *RetentionPeriod) SetNumberOfDays(v int64) *RetentionPeriod {
| s.NumberOfDays = &v
return s
} | csn_ccr |
def from_datetime(cls, generation_time):
"""Create a dummy ObjectId instance with a specific generation time.
This method is useful for doing range queries on a field
containing :class:`ObjectId` instances.
.. warning::
It is not safe to insert a document containing an Objec... | 1)
>>> dummy_id = ObjectId.from_datetime(gen_time)
>>> result = collection.find({"_id": {"$lt": dummy_id}})
:Parameters:
- `generation_time`: :class:`~datetime.datetime` to be used
as the generation time for the resulting ObjectId.
"""
if generation_time.u... | csn_ccr |
public void advance(long currentTimeNanos) {
long previousTimeNanos = nanos;
try {
nanos = currentTimeNanos;
for (int i = 0; i < SHIFT.length; i++) {
long previousTicks = (previousTimeNanos >> SHIFT[i]);
long currentTicks = (currentTimeNanos >> SHIFT[i]);
if ((currentTicks - ... | break;
}
expire(i, previousTicks, currentTicks);
}
} catch (Throwable t) {
nanos = previousTimeNanos;
throw t;
}
} | csn_ccr |
Parse the ePCR output file. Populate dictionary of resutls. For alleles, find the best result based on the
number of mismatches before populating dictionary | def parse_epcr(self):
"""
Parse the ePCR output file. Populate dictionary of resutls. For alleles, find the best result based on the
number of mismatches before populating dictionary
"""
# Use the metadata object from the vtyper_object
for sample in self.vtyper_object.met... | csn |
Parse list of key=value strings where keys are not duplicated. | def parse_keqv_list(l):
"""Parse list of key=value strings where keys are not duplicated."""
parsed = {}
for elt in l:
k, v = elt.split('=', 1)
if v[0] == '"' and v[-1] == '"':
v = v[1:-1]
parsed[k] = v
return parsed | csn |
// requireQuota updates the selector requirements for the given quota. This prevents stale updates to the mapping itself.
// returns true if a modification was made | func (m *clusterQuotaMapper) requireQuota(quota *quotav1.ClusterResourceQuota) bool {
m.lock.RLock()
selector, exists := m.requiredQuotaToSelector[quota.Name]
m.lock.RUnlock()
if selectorMatches(selector, exists, quota) {
return false
}
m.lock.Lock()
defer m.lock.Unlock()
selector, exists = m.requiredQuotaT... | csn |
//Kill the server | func (s *Server) Kill() error {
for _, connection := range s.connections {
err := connection.Close()
if err != nil {
return err
}
}
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
return err
}
}
// Only need to close channel once to broadcast to all waiting
if s.d... | csn |
def SignMessage(self, message, script_hash):
"""
Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message
| """
keypair = self.GetKeyByScriptHash(script_hash)
prikey = bytes(keypair.PrivateKey)
res = Crypto.Default().Sign(message, prikey)
return res, keypair.PublicKey | csn_ccr |
protected OntologyBuilder getOntologyBuilder(VersionRows vr, String rootModuleId, String rootModuleVersion,
Map<String, String> metadata) {
| return new OntologyBuilder(vr, rootModuleId, rootModuleVersion, metadata);
} | csn_ccr |
Format the data for packer
@param string $interface
@param string $version
@param string $method
@param array $params
@return array | public function formatData(string $interface, string $version, string $method, array $params): array
{
return [
'interface' => $interface,
'version' => $version,
'method' => $method,
'params' => $params,
'logid' => RequestContext::getLogid(),
... | csn |
public function rewind()
{
$this->subPriorities = $this->priorities;
$this->maxPriority = empty($this->priorities) ? 0 : max($this->priorities);
| $this->index = 0;
$this->subIndex = 0;
} | csn_ccr |
private function resetCurlHandle()
{
if (!is_null($this->curlHandle) && $this->getEnablePersistentConnections()) {
| curl_reset($this->curlHandle);
} else {
$this->initCurlHandle();
}
} | csn_ccr |
// ClickedCharacter should only be called after a bounding box hit is confirmed because
// it does not check y-axis values at all. Returns the index and side of the char clicked. | func (t *Text) ClickedCharacter(xPos, offset float64) (index int, side CharacterSide) {
// transform from screen coordinates to... window coordinates?
xPos = xPos - float64(t.Font.WindowWidth/2) - offset
// could do a binary search...
at := float64(t.X1.X)
for i, cs := range t.CharSpacing {
at = float64(cs) + a... | csn |
def r_plokamos_proxy(self):
""" Proxy to write to the annotation store
:return: response from the remote query store
:rtype: {str: Any}
"""
query = request.data
if self.is_authorized(query,NemoOauthPlugin.current_user()['uri']):
try:
resp = ... | "accept": "application/sparql-results+json"})
resp.raise_for_status()
return resp.content, resp.status_code
except requests.exceptions.HTTPError as err:
return str(err), resp.status_code
else:
return "Unauthorized request", 4... | csn_ccr |
def fit(self, X, y=None):
"""Fit the grid
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data points
Returns
-------
self
"""
X = array2d(X)
self.n_features = X.shape[1]
self.n_bins = self.n_bins... | * np.ones(self.n_features)
else:
min = np.asarray(self.min)
if not min.shape == (self.n_features,):
raise ValueError('min shape error')
if self.max is None:
max = np.max(X, axis=0)
elif isinstance(self.max, numbers.Number):
max = ... | csn_ccr |
public static double getRobustTreeEditDistance(String dom1, String dom2) {
LblTree domTree1 = null, domTree2 = null;
try {
domTree1 = getDomTree(dom1);
domTree2 = getDomTree(dom2);
} catch (IOException e) {
e.printStackTrace();
}
double DD = 0.0;
RTED_InfoTree_Opt rted;
double ted;
rted = ne... |
int maxSize = Math.max(domTree1.getNodeCount(), domTree2.getNodeCount());
rted.computeOptimalStrategy();
ted = rted.nonNormalizedTreeDist();
ted /= (double) maxSize;
DD = ted;
return DD;
} | csn_ccr |
Generates a random sha265 token | private function generateActivationToken(): string
{
$this->setSize(32);
$this->generateRandomToken();
$this->activation_token = hash('sha256', $this->token);
return $this->activation_token;
} | csn |
Normalizes the input array so that it sums to 1.
Parameters
----------
a : array
Non-normalized input data.
axis : int
Dimension along which normalization is performed.
Notes
-----
Modifies the input **inplace**. | def normalize(a, axis=None):
"""Normalizes the input array so that it sums to 1.
Parameters
----------
a : array
Non-normalized input data.
axis : int
Dimension along which normalization is performed.
Notes
-----
Modifies the input **inplace**.
"""
a_sum = a.su... | csn |
Inserts an element at the beginning of the array.
If you set both params, that first param is the key, and second is the value,
else first param is the value, and the second is ignored.
@param mixed $k
@param mixed $v
@return $this | public function prepend($k, $v = null)
{
$array = $this->val();
if (!$this->isNull($v)) {
$array = array_reverse($array, true);
$array[$k] = $v;
$array = array_reverse($array, true);
} else {
array_unshift($array, $k);
}
$this... | csn |
Continuously run, while executing pending jobs at each elapsed
time interval.
@return cease_continuous_run: threading.Event which can be set to
cease continuous run.
Please note that it is *intended behavior that run_continuously()
does not run missed jobs*. For example, if you... | def run_continuously(self, interval=1):
"""Continuously run, while executing pending jobs at each elapsed
time interval.
@return cease_continuous_run: threading.Event which can be set to
cease continuous run.
Please note that it is *intended behavior that run_continuously()
... | csn |
how to check windows filesystem with python | def is_unix_like(platform=None):
"""Returns whether the given platform is a Unix-like platform with the usual
Unix filesystem. When the parameter is omitted, it defaults to ``sys.platform``
"""
platform = platform or sys.platform
platform = platform.lower()
return platform.startswith("linux") or... | cosqa |
Returns True iff this represents a scalar node.
If a type is given, checks that the ScalarNode represents this \
type. Type may be `str`, `int`, `float`, `bool`, or `None`.
If no type is given, any ScalarNode will return True. | def is_scalar(self, typ: Type = _Any) -> bool:
"""Returns True iff this represents a scalar node.
If a type is given, checks that the ScalarNode represents this \
type. Type may be `str`, `int`, `float`, `bool`, or `None`.
If no type is given, any ScalarNode will return True.
"... | csn |
how to show the toolbar in python | def add_to_toolbar(self, toolbar, widget):
"""Add widget actions to toolbar"""
actions = widget.toolbar_actions
if actions is not None:
add_actions(toolbar, actions) | cosqa |
Removes either the specified Instance or all Instance objects.
:param index: the 0-based index of the instance to remove
:type index: int | def delete(self, index=None):
"""
Removes either the specified Instance or all Instance objects.
:param index: the 0-based index of the instance to remove
:type index: int
"""
if index is None:
javabridge.call(self.jobject, "delete", "()V")
else:
... | csn |
// New creates a new client-side UnitAssigner facade. | func New(caller base.APICaller) API {
fc := base.NewFacadeCaller(caller, uaFacade)
return API{facade: fc}
} | csn |
// KeyPoolRefillSizeAsync returns an instance of a type that can be used to get
// the result of the RPC at some future time by invoking the Receive function on
// the returned instance.
//
// See KeyPoolRefillSize for the blocking version and more details. | func (c *Client) KeyPoolRefillSizeAsync(newSize uint) FutureKeyPoolRefillResult {
cmd := btcjson.NewKeyPoolRefillCmd(&newSize)
return c.sendCmd(cmd)
} | csn |
private function createElasticClient($clientName, ContainerBuilder $container)
{
// Storage metadata
$smfName = sprintf('%s.metadata', $clientName);
$definition = new Definition(
Utility::getLibraryClass('Search\Elastic\StorageMetadataFactory')
);
$definition->set... |
$container->setDefinition($smfName, $definition);
// Client
return new Definition(
Utility::getLibraryClass('Search\Elastic\Client'),
[new Reference($smfName)]
);
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.