query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
Disposes of any system resources or security-sensitive information the
SaslClient might be using. | @Override
public synchronized void dispose() {
if (saslClient != null) {
try {
saslClient.dispose();
} catch (SaslException e) {
// ignore
} finally {
saslClient = null;
}
}
} | csn |
Set the operator used for comparing field and value.
@param string $operator The comparison operator.
@throws InvalidArgumentException If the parameter is not a valid operator.
@return self | public function setOperator($operator)
{
if (!is_string($operator)) {
throw new InvalidArgumentException(
'Operator should be a string.'
);
}
$operator = strtoupper($operator);
if (!in_array($operator, $this->validOperators())) {
t... | csn |
// Backoff returns the delay for the current amount of retries | func (bc Config) Backoff(retries int) time.Duration {
if retries == 0 {
return bc.BaseDelay
}
backoff, max := float64(bc.BaseDelay), float64(bc.MaxDelay)
for backoff < max && retries > 0 {
backoff *= bc.Factor
retries--
}
if backoff > max {
backoff = max
}
// Randomize backoff delays so that if a cluste... | csn |
This method is only ever called from the framework's clear method which is
only
called when the framework is being destroyed or when automated tests are
clearing
out the frameworks config. | public void destroyInternal() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "destroyInternal; " + this);
}
// Stop and destroy the chain. Ignore exceptions
try {
this.cf.stopChainInternal(getChain(), 0);
this.cf.dest... | csn |
public function sendError($error)
{
if (@ob_get_length()) {
@ob_end_clean();
}
if ($error instanceof \Concrete\Core\Error\ErrorList\ErrorList) {
$error->outputJSON();
} else {
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request', true, 400);
... | header('Content-Type: text/plain; charset=' . APP_CHARSET, true);
echo($error instanceof Exception) ? $error->getMessage() : $error;
}
die();
} | csn_ccr |
def _dmi_data(dmi_raw, clean, fields):
'''
Parse the raw DMIdecode output of a single handle
into a nice dict
'''
dmi_data = {}
key = None
key_data = [None, []]
for line in dmi_raw:
if re.match(r'\t[^\s]+', line):
# Finish previous key
if key is not None:... | vlist.insert(0, value)
dmi_data[key] = vlist
elif value is not None:
dmi_data[key] = value
# Family: Core i5
# Keyboard Password Status: Not Implemented
key, val = line.split(':', 1)
key = key.strip().l... | csn_ccr |
Deselects all child items of the provided item.
@param item the item for which all childs should be deselected.d | private void deselectChildren(CmsTreeItem item) {
for (String childId : m_childrens.get(item.getId())) {
CmsTreeItem child = m_categories.get(childId);
deselectChildren(child);
child.getCheckBox().setChecked(false);
if (m_selectedCategories.contains(childId... | csn |
def randomise_proposed_value(self):
"""Creates a randomly the proposed value.
Raises
------
TypeError
Raised if this method is called on a static value.
TypeError
Raised if the parameter type is unknown.
"""
if self.parameter_type is MMCPa... | self.proposed_value = random.choice(
numpy.arange(min_v, max_v, step))
elif self.parameter_type is MMCParameterType.LIST:
self.proposed_value = random.choice(self.static_dist_or_list)
elif self.parameter_type is MMCParameterType.STATIC_VALUE:
raise TypeError('Thi... | csn_ccr |
computed the stack size | private int calcStackSize() {
int i, max;
int result;
int[] startStack;
ExceptionInfo e;
int tmp;
int unreachable;
IntBitSet todo;
List<Jsr> jsrs;
jsrs = Jsr.findJsrs(this);
startStack = new int[instructions.size()];
for (i = 0; i ... | csn |
private void initRestTemplate() {
boolean isContainsConverter = false;
for (HttpMessageConverter<?> httpMessageConverter : this.restTemplate.getMessageConverters()) {
if (MappingJacksonRPC2HttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())) {
isContainsConverter = true;
break;
... | messageConverter.setObjectMapper(this.getObjectMapper());
final List<HttpMessageConverter<?>> restMessageConverters = new ArrayList<>();
restMessageConverters.addAll(this.restTemplate.getMessageConverters());
// Place JSON-RPC converter on the first place!
restMessageConverters.add(0, messageConverter);
... | csn_ccr |
Get the highest-priority item out of this queue.
Returns the item, or None if no items are available. The item
must be either ``return_item()`` or ``renew_item()`` before
``expiration`` seconds pass, or it will become available to
future callers. The item will be marked as being owned... | def check_out_item(self, expiration):
"""Get the highest-priority item out of this queue.
Returns the item, or None if no items are available. The item
must be either ``return_item()`` or ``renew_item()`` before
``expiration`` seconds pass, or it will become available to
future... | csn |
// NewMockRunner creates a new mock instance | func NewMockRunner(ctrl *gomock.Controller) *MockRunner {
mock := &MockRunner{ctrl: ctrl}
mock.recorder = &MockRunnerMockRecorder{mock}
return mock
} | csn |
private List<Class<?>> getValidJPAAnnotationsFromMethod(Class<?> clazz, Method method, int numberOfParams,
Class<?> entityClazz)
{
List<Class<?>> annotations = new ArrayList<Class<?>>();
for (Annotation methodAnnotation : method.getAnnotations())
{
Class<?> me... | if (paramTypes.length != numberOfParams)
{
log.info("Skipped method(" + clazz.getName() + "." + method.getName() + ") Must have "
+ numberOfParams + " parameter.");
continue;
}
if (numberO... | csn_ccr |
Determine scale factor difference between edge triangulation and world | static double determineScale(View base , Motion edge )
throws Exception
{
View viewA = edge.viewSrc;
View viewB = edge.viewDst;
boolean baseIsA = base == viewA;
// determine the scale factor difference
Point3D_F64 worldInBase3D = new Point3D_F64();
Point3D_F64 localInBase3D = new Point3D_F64();
GrowQ... | csn |
func (s *ProbesService) Create(k RRSetKey, dp ProbeInfoDTO) (*http.Response, error) {
| return s.client.post(k.ProbesURI(), dp, nil)
} | csn_ccr |
You are given an integer array A. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps.
You may from index i jump forward to index j (with i < j) in the foll... | class Solution:
def oddEvenJumps(self, A: List[int]) -> int:
def findNextHighestIdx(B: List[int]) -> List[int]:
next_idx_list = [None] * len(B)
stack = []
for i in B:
while stack and stack[-1] < i:
next_idx_list[stack.pop()] = i
... | apps |
@When("^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)' with:$")
public void readFileToVariable(String baseData, String type, String envVar, DataTable modifications) throws Exception {
// Retrieve data
String retrievedData = commonspec.retrieveData(baseData, type);
... | String modifiedData = commonspec.modifyData(retrievedData, type, modifications).toString();
// Save in environment variable
ThreadProperty.set(envVar, modifiedData);
} | csn_ccr |
Find the correct metadata expression for the expression.
Parameters
----------
field : {'deltas', 'checkpoints'}
The kind of metadata expr to lookup.
expr : Expr
The baseline expression.
metadata_expr : Expr, 'auto', or None
The metadata argument. If this is 'auto', then the... | def _get_metadata(field, expr, metadata_expr, no_metadata_rule):
"""Find the correct metadata expression for the expression.
Parameters
----------
field : {'deltas', 'checkpoints'}
The kind of metadata expr to lookup.
expr : Expr
The baseline expression.
metadata_expr : Expr, 'a... | csn |
Report a mandatory warning. | public void report(DiagnosticPosition pos, String msg, Object... args) {
JavaFileObject currentSource = log.currentSourceFile();
if (verbose) {
if (sourcesWithReportedWarnings == null)
sourcesWithReportedWarnings = new HashSet<JavaFileObject>();
if (log.nwarning... | csn |
// AttachStreams attaches the container's streams to the AttachConfig | func (c *Config) AttachStreams(cfg *AttachConfig) {
if cfg.UseStdin {
cfg.CStdin = c.StdinPipe()
}
if cfg.UseStdout {
cfg.CStdout = c.StdoutPipe()
}
if cfg.UseStderr {
cfg.CStderr = c.StderrPipe()
}
} | csn |
def inserir(self, name):
"""Inserts a new Division Dc and returns its identifier.
:param name: Division Dc name. String with a minimum 2 and maximum of 80 characters
:return: Dictionary with the following structure:
::
{'division_dc': {'id': < id_division_dc >}}
... | DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
division_dc_map = dict()
division_dc_map['name'] = name
code, xml = self.submit(
{'division_dc': division_dc_map}, 'POST', 'divisiondc/')
... | csn_ccr |
Returns a list of all directories in the Library, optionally excluding some of them.
@param array $exclude A list of folders to exclude from the result list.
The folder paths should be specified relative to the Library root.
@return array | public function listAllDirectories($exclude = [])
{
$fullPath = $this->getMediaPath('/');
$folders = $this->getStorageDisk()->allDirectories($fullPath);
$folders = array_unique($folders, SORT_LOCALE_STRING);
$result = [];
foreach ($folders as $folder) {
$folde... | csn |
public function admin_modal_bail_pod( $id, $params, $obj ) {
if ( ! pods_is_modal_window() ) {
return;
}
if ( ! $obj ) {
$obj = pods( $params['pod'] );
}
if ( ! $obj || ! $obj->fetch( $id ) ) {
return;
}
$item_id = $obj->id();
$item_title = $obj->index();
$field_args = (object) array(... | 'pick_val' => $obj->pod,
),
'value' => array(
$obj->id() => $item_title,
),
);
$this->admin_modal_bail_JSON( $item_id, $item_title, $field_args );
} | csn_ccr |
Loads the given formula expressed in infix notation, and sets the engine
holding the variables to which the formula refers.
@param formula is the right-hand side of a mathematical equation expressed
in infix notation
@param engine is the engine to which the formula can refer
@throws RuntimeException if the formula has... | public void load(String formula, Engine engine) {
this.root = parse(formula);
this.formula = formula;
this.engine = engine;
} | csn |
left right function in python | def value_left(self, other):
"""
Returns the value of the other type instance to use in an
operator method, namely when the method's instance is on the
left side of the expression.
"""
return other.value if isinstance(other, self.__class__) else other | cosqa |
public void writeJson(JsonParser parser, JsonGenerator jgen) throws IOException {
checkNotNull(parser, "JsonParser cannot be null for writeJson.");
| checkNotNull(jgen, "JsonGenerator cannot be null for writeJson.");
JsonToken curToken = parser.nextToken();
while (curToken != null) {
curToken = processToken(curToken, parser, jgen);
}
jgen.flush();
} | csn_ccr |
function setCurrentUser(UserInterface $user)
{
$this->currentUser = $user;
// accessing the current user from the
// DI | container is deprecated
$this->app['user'] = $user;
return $this;
} | csn_ccr |
def cancel(self, *ids):
"""Try to cancel jobs with associated ids.
Return the actual number of jobs cancelled.
"""
ncancelled = 0 |
with self.lock:
for id in ids:
try:
if self._status[id] == 'SUBMITTED':
self._status[id] = 'CANCELLED'
ncancelled += 1
except IndexError:
pass
return ncancelled | csn_ccr |
public function path($file = '', $theme = null)
{
if (is_null($theme)) {
$theme = $this->getCurrent();
}
| $theme = $this->format($theme);
return base_path("themes/{$theme}/{$file}");
} | csn_ccr |
def RunValidationOutputFromOptions(feed, options):
"""Validate feed, output results per options and return an exit code."""
if options.output.upper() == "CONSOLE":
| return RunValidationOutputToConsole(feed, options)
else:
return RunValidationOutputToFilename(feed, options, options.output) | csn_ccr |
// Turn the contents of the specified file into a gerb template | func ParseFile(cache bool, paths ...string) (TemplateChain, error) {
all := make([][]byte, len(paths))
for index, path := range paths {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
all[index] = data
}
return Parse(cache, all...)
} | csn |
python check element exist | def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELE... | cosqa |
# Story&Task
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all houses in the city were built in one row.
Let's enumerate all the houses from left to right, starting with 0. A house is considered to be luxurious if the number of floors in it is strictl... | def luxhouse(houses):
return [max(0, max(houses[i:]) - h + 1) for i, h in enumerate(houses[:-1], 1)] + [0] | apps |
func (pv *MockPV) String() string {
addr := | pv.GetPubKey().Address()
return fmt.Sprintf("MockPV{%v}", addr)
} | csn_ccr |
XAConnection interface. | @Override
public Connection getConnection() throws SQLException {
Connection conn = super.getConnection();
// When we're outside an XA transaction, autocommit
// is supposed to be true, per usual JDBC convention.
// When an XA transaction is in progress, it should be
// false.
if (state == St... | csn |
Get a list of all hosting devices. | def get_all_hosting_devices(self, context):
"""Get a list of all hosting devices."""
cctxt = self.client.prepare()
return cctxt.call(context,
'get_all_hosting_devices',
host=self.host) | csn |
private function updateLayoutModifiedDate(Layout $layout): void
{
$updatedLayout = clone $layout;
| $updatedLayout->modified = time();
$this->queryHandler->updateLayout($updatedLayout);
} | csn_ccr |
public final boolean isReconfigurable(WSConnectionRequestInfoImpl cri, boolean reauth)
{
// The CRI is only reconfigurable if all fields which cannot be changed already match.
// Although sharding keys can sometimes be changed via connection.setShardingKey,
// the spec does not guarantee th... |
// selecting a connection from the pool.
if (reauth)
{
return ivConfigID == cri.ivConfigID;
} else {
return match(ivUserName, cri.ivUserName) &&
match(ivPassword, cri.ivPassword) &&
match(ivShardingKey, cri.ivShardingKey) &... | csn_ccr |
func (formats Formats) GetByNames(names ...string) (Formats, error) {
var types []Format
for _, name := range names { |
tpe, ok := formats.GetByName(name)
if !ok {
return types, fmt.Errorf("OutputFormat with key %q not found", name)
}
types = append(types, tpe)
}
return types, nil
} | csn_ccr |
public static Rule getRule(final Stack stack) {
if (stack.size() < 1) {
throw new IllegalArgumentException(
"Invalid EXISTS rule - expected one parameter but received " |
+ stack.size());
}
return new ExistsRule(stack.pop().toString());
} | csn_ccr |
public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) {
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) {
Element replacedM... | for arg-type match elements.
List<Element> argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT);
for (Element argTypeEle : argTypeEles) {
replaceOverride.addTypeIdentifier(argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE));
}
replaceOverride.se... | csn_ccr |
Throws an error if the message server is not enabled due to missing configuration | function assertMsgServerIsEnabled() {
assert(cfgMmrp.bind, 'No MMRP bindings configured');
assert(cfgMsgStream, 'The message stream has been disabled.');
assert(cfgMsgStream.transports, 'The message stream has no configured transports.');
assert(serviceDiscovery.isEnabled(), 'Service discovery has not been configur... | csn |
Sets a date if it's set in data.
@param array$data
@param string $key
@param DateTIme|null $currentDate
@param callable $setCallback | protected function setDate($data, $key, DateTIme $currentDate, callable $setCallback)
{
$date = $this->getProperty($data, $key, $currentDate);
if ($date !== null) {
if (is_string($date)) {
$date = new DateTime($data[$key]);
}
call_user_func($setCal... | csn |
func (h loggingHandler) writeLogLine(username, upstream string, req *http.Request, url url.URL, ts time.Time, status int, size int) {
if username == "" {
username = "-"
}
if upstream == "" {
upstream = "-"
}
if url.User != nil && username == "-" {
if name := url.User.Username(); name != "" {
username = na... | RequestURI: fmt.Sprintf("%q", url.RequestURI()),
ResponseSize: fmt.Sprintf("%d", size),
StatusCode: fmt.Sprintf("%d", status),
Timestamp: ts.Format("02/Jan/2006:15:04:05 -0700"),
Upstream: upstream,
UserAgent: fmt.Sprintf("%q", req.UserAgent()),
Username: username,
... | csn_ccr |
func LoadHistory(path string) error {
p := C.CString(path)
e := C.read_history(p)
C.free(unsafe.Pointer(p))
| if e == 0 {
return nil
}
return syscall.Errno(e)
} | csn_ccr |
func (m *Resource) Validate() error {
if m == nil {
return nil
}
// no validation rules for Name
// no validation rules for Version
{
tmp := m.GetResource()
if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {
if err := v.Validate(); err != | nil {
return ResourceValidationError{
field: "Resource",
reason: "embedded message failed validation",
cause: err,
}
}
}
}
return nil
} | csn_ccr |
public function getCurrencyObject($name)
{
$search = $this->getCurrencyArray();
foreach ($search as $cur) {
| if ($cur->name == $name) {
return $cur;
}
}
} | csn_ccr |
Create a formatted packet from a request.
:type request: str
:param request: Formatted zabbix request
:rtype: str
:return: Data packet for zabbix | def _create_packet(self, request):
"""Create a formatted packet from a request.
:type request: str
:param request: Formatted zabbix request
:rtype: str
:return: Data packet for zabbix
"""
data_len = struct.pack('<Q', len(request))
packet = b'ZBXD\x01' +... | csn |
Set YARN user. This method can be called only once per class instance.
@param name Name of the new proxy user.
@param hostUser User credentials to copy. Must be an instance of YarnProxyUser. | @Override
public void set(final String name, final UserCredentials hostUser) throws IOException {
assert this.proxyUGI == null;
assert hostUser instanceof YarnProxyUser;
LOG.log(Level.FINE, "UGI: user {0} copy from: {1}", new Object[] {name, hostUser});
final UserGroupInformation hostUGI = ((YarnPr... | csn |
ben-elastic entry point | def main(argv=None):
"""ben-elastic entry point"""
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es'])
es_export.export()
if argv is not None:
return es_export | csn |
Searches for query in the given IMAP criteria and returns
the message numbers that match as a list of strings.
Criteria without values (eg DELETED) should be keyword args
with KEY=True, or else not passed. Criteria with values should
be keyword args of the form KEY="VALUE" where KEY is ... | def __imap_search(self, ** criteria_dict):
""" Searches for query in the given IMAP criteria and returns
the message numbers that match as a list of strings.
Criteria without values (eg DELETED) should be keyword args
with KEY=True, or else not passed. Criteria with values should
... | csn |
Return a local map spill index file created earlier
@param mapTaskId a map task id
@param spillNumber the number | public Path getSpillIndexFile(TaskAttemptID mapTaskId, int spillNumber)
throws IOException {
return lDirAlloc.getLocalPathToRead(TaskTracker.getIntermediateOutputDir(
jobId.toString(), mapTaskId.toString())
+ "/spill" +
spillNumber + ".out.in... | csn |
Load proxies from file | def load(self, filename):
"""Load proxies from file"""
with open(filename, 'r') as fin:
proxies = json.load(fin)
for protocol in proxies:
for proxy in proxies[protocol]:
self.proxies[protocol][proxy['addr']] = Proxy(
proxy['addr'], prox... | csn |
This method sorts elements in array using order field.
Example:
<code>
$obj1 = new stdClass();
$obj1->name = 'a';
$obj1->description = '1';
$obj2 = new stdClass();
$obj2->name = 'c';
$obj2->description = '2';
$obj3 = new stdClass();
$obj3->name = 'b';
$obj3->description = '3';
$array = array($obj1, $obj2, $obj3);
$... | public static function orderBy(array $elements, $orderField)
{
usort($elements, function ($a, $b) use ($orderField) {
return $a->$orderField < $b->$orderField ? -1 : 1;
});
return $elements;
} | csn |
public TagDependentBodyTransformer getBodyTransformer() throws TagLibException {
if (!hasTDBTClassDefinition()) return null;
if (tdbt != null) return tdbt; |
try {
tdbt = (TagDependentBodyTransformer) tdbtCD.getClazz().newInstance();
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
throw new TagLibException(t);
}
return tdbt;
} | csn_ccr |
Hide the loading layer | function () {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration || 100,
complete: function () {
css(loadingDiv, { display: NONE });
}
});
}
this.loadingShown = false;
} | csn |
Adds an authentication mechanism directly to the deployment. This mechanism will be last in the list.
In general you should just use {@link #addAuthenticationMechanism(String, io.undertow.security.api.AuthenticationMechanismFactory)}
and allow the user to configure the methods they want by name.
This method is essent... | public DeploymentInfo addLastAuthenticationMechanism(final String name, final AuthenticationMechanism mechanism) {
authenticationMechanisms.put(name, new ImmediateAuthenticationMechanismFactory(mechanism));
if(loginConfig == null) {
loginConfig = new LoginConfig(null);
}
logi... | csn |
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks.
I knew a rating of 100 is pretty good, but never knew what makes up the rating.
So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating
## Formula
There are... | def passer_rating(att, yds, comp, td, ints):
limit = lambda x: min(max(x, 0), 2.375)
att = float(att) # for python 2 compatibility
A = ((comp / att) - .3) * 5
B = ((yds / att) - 3) * .25
C = (td / att) * 20
D = 2.375 - ((ints / att) * 25)
A, B, C, D = map(limit, (A, B, C, D... | apps |
func cloneParameters(params *Parameters) {
if params == nil {
return
}
params.Optional | = append(make([]NamedParameter, 0), params.Optional...)
for i := range params.Optional {
clone(¶ms.Optional[i].DefaultArg)
}
} | csn_ccr |
func (tx *tx) delete(table, id string) error {
n := tx.lookup(table, indexID, id)
if n == nil {
return | ErrNotExist
}
err := tx.memDBTx.Delete(table, n)
if err == nil {
tx.changelist = append(tx.changelist, n.EventDelete())
}
return err
} | csn_ccr |
Wrap things up and write xlsx.
@param string $fileName | public function writeToFile($fileName = 'report.xlsx')
{
$this->output = fopen($fileName, 'w');
$finalizer = new Finalizer($this->sheet, $this->styler, $this->sheetFile);
$finalizer->finalize($this->output);
} | csn |
func (p *propertySet) filterAllocs(allocs []*structs.Allocation, filterTerminal bool) []*structs.Allocation {
n := len(allocs)
for i := 0; i < n; i++ {
remove := false
if filterTerminal {
remove = allocs[i].TerminalStatus()
}
// If the constraint is on the task group filter the allocations to just
// th... | remove = remove || allocs[i].TaskGroup != p.taskGroup
}
if remove {
allocs[i], allocs[n-1] = allocs[n-1], nil
i--
n--
}
}
return allocs[:n]
} | csn_ccr |
Rebuild a full declaration name from its components.
for every string x, we have `join(split(x)) == x`. | def join(cls, root, subkey):
"""Rebuild a full declaration name from its components.
for every string x, we have `join(split(x)) == x`.
"""
if subkey is None:
return root
return enums.SPLITTER.join((root, subkey)) | csn |
Loads the given file using the appropriate InferenceFile class.
If ``filetype`` is not provided, this will try to retreive the ``filetype``
from the file's ``attrs``. If the file does not exist yet, an IOError will
be raised if ``filetype`` is not provided.
Parameters
----------
path : str
... | def loadfile(path, mode=None, filetype=None, **kwargs):
"""Loads the given file using the appropriate InferenceFile class.
If ``filetype`` is not provided, this will try to retreive the ``filetype``
from the file's ``attrs``. If the file does not exist yet, an IOError will
be raised if ``filetype`` is ... | csn |
Pop up the help in a browser window. By default, this tries to
show the help for the current task. With the option arguments, it can
be used to show any help string. | def htmlHelp(self, helpString=None, title=None, istask=False, tag=None):
""" Pop up the help in a browser window. By default, this tries to
show the help for the current task. With the option arguments, it can
be used to show any help string. """
# Check the help string. If it turns o... | csn |
public static function startsWith($check, $string)
{
if ($check === "" || $check === $string) {
return true;
| } else {
return strpos($string, $check) === 0;
}
} | csn_ccr |
Called before notify a listener about the event.
@param mixed $listener The listener to notify with that $event
@param string $eventName The event name
@param Event $event The event
@return Event | protected function preNotify($listener, $eventName, Event $event)
{
if (Events::SUCCESS == $eventName
&& $event instanceof GenericEvent
) {
/*
* 'ast' argument of 'reflect.success' event is used only by the cache plugin.
* Remove it improve performa... | csn |
Returns a set of all fields matching the supplied filter
declared in the clazz class.
@param clazz The class to inspect.
@param filter Filter to use.
@return All matching fields declared by the clazz class. | public static Set<Field> getDeclaredFields(Class<?> clazz, FieldFilter filter) {
Set<Field> fields = new HashSet<Field>();
Field[] allFields = clazz.getDeclaredFields();
for(Field field : allFields) {
if(filter.passFilter(field)) {
fields.add(field);
}
... | csn |
return file and line number of called position
@param int $back
@return array | public static function caller(int $back = 0)
{
$bt = debug_backtrace();
$trace = $bt[$back] ?? null;
$file = $trace['file'] ?? '';
$line = $trace['line'] ?? -1;
return array( $file, intval($line) );
} | csn |
Generates the url, lineNumber, and Column number of the error. | function findStackData(stack) {
// If the stack is not in the error we cannot get any information and
// should return immediately.
if (stack === undefined || stack === null) {
return {
'url': Canadarm.constant.UNKNOWN_LOG,
'lineNumber': Canadarm.constant.UNKNOWN_LOG,
'columnNu... | csn |
def qhalf(options, halfspaces, interior_point):
"""
Similar to qvoronoi command in command-line qhull.
Args:
option:
An options string. Up to two options separated by spaces
are supported. See Qhull's qhalf help for info. Typically
used options are:
F... | data.append(map(repr, interior_point))
data.append([len(points[0])])
data.append([len(points)])
data.extend([map(repr, row) for row in points])
prep_str = [" ".join(map(str, line)) for line in data]
output = getattr(hull, "qhalf")(options, "\n".join(prep_str))
return list(map(str.strip, outpu... | csn_ccr |
If X or Y is null, return an empty Point | private Point makePointValid(Point point) {
CoordinateSequence sequence = point.getCoordinateSequence();
GeometryFactory factory = point.getFactory();
CoordinateSequenceFactory csFactory = factory.getCoordinateSequenceFactory();
if (sequence.size() == 0) {
return point;
... | csn |
Create a composition of a song that changes its length
to a given duration.
:param song: Song to retarget
:type song: :py:class:`radiotool.composer.Song`
:param duration: Duration of retargeted song (in seconds)
:type duration: float
:param start: Start the retargeted song at the
... | def retarget_to_length(song, duration, start=True, end=True, slack=5,
beats_per_measure=None):
"""Create a composition of a song that changes its length
to a given duration.
:param song: Song to retarget
:type song: :py:class:`radiotool.composer.Song`
:param duration: Duratio... | csn |
func (e *E2eProcessingLatencyAggregate) Add(e2 *E2eProcessingLatencyAggregate) {
e.Addr = "*"
p := e.Percentiles
e.Count += e2.Count
for _, value := range e2.Percentiles {
i := -1
for j, v := range p {
if value["quantile"] == v["quantile"] {
i = j
break
}
}
if i == -1 {
i = len(p)
e.Perc... | append(p, make(map[string]float64))
p = e.Percentiles
p[i]["quantile"] = value["quantile"]
}
p[i]["max"] = math.Max(value["max"], p[i]["max"])
p[i]["min"] = math.Min(value["max"], p[i]["max"])
p[i]["count"] += value["count"]
if p[i]["count"] == 0 {
p[i]["average"] = 0
continue
}
delta := valu... | csn_ccr |
// Decrement adds a decrement operation to this mutation operation set. | func (spec MutateInSpec) Decrement(path string, delta int64, opts *MutateInSpecCounterOptions) MutateInOp {
if opts == nil {
opts = &MutateInSpecCounterOptions{}
}
var flags SubdocFlag
if opts.CreatePath {
flags |= SubdocFlagCreatePath
}
if opts.IsXattr {
flags |= SubdocFlagXattr
}
encoder := opts.Encode... | csn |
12.6.3 The for Statement | private ParseTree parseForStatement(SourcePosition start, ParseTree initializer) {
if (initializer == null) {
initializer = new NullTree(getTreeLocation(getTreeStartLocation()));
}
eat(TokenType.SEMI_COLON);
ParseTree condition;
if (!peek(TokenType.SEMI_COLON)) {
condition = parseExpres... | csn |
Send the application stats to statsd. | def statsd_middleware_factory(app, handler):
"""Send the application stats to statsd."""
@coroutine
def middleware(request):
"""Send stats to statsd."""
timer = Timer()
timer.start()
statsd = yield from app.ps.metrics.client()
pipe = statsd.pipe()
pipe.incr('... | csn |
def delete(self, *args):
"""Remove the currently selected item from my store"""
key = self.name_wid.text or self.name_wid.hint_text
if not hasattr(self.store, key):
# TODO feedback about missing key
return
| delattr(self.store, key)
try:
return min(kee for kee in dir(self.store) if kee > key)
except ValueError:
return '+' | csn_ccr |
Performs an ajax request
@param string $method The http method (get, post, delete, put, head)
@param string $url The url of the request
@param string $responseElement selector of the HTML element displaying the answer
@param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>t... | public function ajax($method,$url, $responseElement="", $parameters=[]) {
$parameters["immediatly"]=true;
return $this->_ajax($method,$url,$responseElement,$parameters);
} | csn |
function createAdapter(type) {
var adapterConfig = adaptersConfig[type];
if (!adapterConfig) {
throw new Error('Adapter type ' + type + ' has not | been registered.');
}
return new DebugAdapter(adaptersConfig[type], adaptersCwd[type]);
} | csn_ccr |
def cli(env):
"""List IPSec VPN tunnel contexts"""
manager = SoftLayer.IPSECManager(env.client)
contexts = manager.get_tunnel_contexts()
table = formatting.Table(['id',
'name',
'friendly name',
'internal peer IP a... |
table.add_row([context.get('id', ''),
context.get('name', ''),
context.get('friendlyName', ''),
context.get('internalPeerIpAddress', ''),
context.get('customerPeerIpAddress', ''),
context.get('cre... | csn_ccr |
// runCmd is a convenience function to run a command in a given directory and return its output | func (m *nativeGitClient) runCmd(command string, args ...string) (string, error) {
cmd := exec.Command(command, args...)
return m.runCmdOutput(cmd)
} | csn |
func (m *MockMetricsCollector) TotalConnections() prometheus.Counter | {
ret := m.ctrl.Call(m, "TotalConnections")
ret0, _ := ret[0].(prometheus.Counter)
return ret0
} | csn_ccr |
def register(self, collector):
"""Add a collector to the registry."""
with self._lock:
names = self._get_names(collector)
duplicates = set(self._names_to_collectors).intersection(names)
if duplicates:
raise ValueError(
'Duplicated t... | duplicates))
for name in names:
self._names_to_collectors[name] = collector
self._collector_to_names[collector] = names | csn_ccr |
function layoutUnrealizedRange() {
if (that._groups.length === 0) {
return Promise.wrap();
}
var realizedItemRange = that._getRealizationRange(),
// Last group before the realized range which... | layoutPromises.push(layoutGroupContent(before, realizedItemRange, false));
stop = false;
before--;
}
if (after < groupCount) {
layoutPromises.push(layoutGroup... | csn_ccr |
function parseBody()
{
$request = $this->getMessageObject();
$reqID = spl_object_hash($request);
if ( isset(self::$_parsed[$reqID]) )
// parse from cached
return self::$_parsed[$reqID];
if ($request->headers()->has('content-type')) {
$contentTy... | $parsedData = $this->_parseUrlEncodeDataFromRequest($request);
break;
case strpos($contentType, 'multipart') !== false:
$parsedData = $this->_parseMultipartDataFromRequest($request);
break;
default:
throw new \Exception(sp... | csn_ccr |
Modify grid column
@param $columnId
@param $key
@param $value
@return $this | public function updateColumn($columnId, $key, $value)
{
if (isset($this->_columns[$columnId]) && $this->_columns[$columnId] instanceof Varien_Object) {
$this->_columns[$columnId]->setData($key, $value);
}
return $this;
} | csn |
turn an integer into date python | def int_to_date(date):
"""
Convert an int of form yyyymmdd to a python date object.
"""
year = date // 10**4
month = date % 10**4 // 10**2
day = date % 10**2
return datetime.date(year, month, day) | cosqa |
def adjust!(attributes = {}, reload = false)
return true if attributes.empty?
reload_conditions = if reload
model_key = model.key(repository.name)
Query.target_conditions(self, model_key, model_key) |
end
adjust_attributes = adjust_attributes(attributes)
repository.adjust(adjust_attributes, self)
if reload_conditions
@query.clear
@query.update(:conditions => reload_conditions)
self.reload
end
true
end | csn_ccr |
This is almost the same with `add_nodes`. The difference is that
it will add slaves in two slower way.
This is mainly used to avoid huge overhead caused by full sync
when large amount of slaves are added to cluster.
If fast_mode is False, there is only one master node doing
repli... | def add_slaves(self, new_slaves, fast_mode=False):
'''This is almost the same with `add_nodes`. The difference is that
it will add slaves in two slower way.
This is mainly used to avoid huge overhead caused by full sync
when large amount of slaves are added to cluster.
If fast_mo... | csn |
public function getPayPalBasketVatValue()
{
$basketVatValue = 0;
$basketVatValue += $this->getPayPalProductVat();
$basketVatValue += $this->getPayPalWrappingVat();
$basketVatValue += $this->getPayPalGiftCardVat();
$basketVatValue += $this->getPayPalPayCostVat();
|
if ($this->getDeliveryCosts() < round($this->getDeliveryCosts(), 2)) {
return floor($basketVatValue * 100) / 100;
}
return $basketVatValue;
} | csn_ccr |
Format the day of the month, optionally zero-padded. | void formatDayOfMonth(StringBuilder b, ZonedDateTime d, int width) {
int day = d.getDayOfMonth();
zeroPad2(b, day, width);
} | csn |
function initThemeFilesWatch(app) {
utils.tick(function () {
var viewsPath = utils.getViewsPath();
var dbAction = new DBActions.DBActions(app.set("db"), {modelName: "Theme"});
dbAction.get("getAll", null, function (err, themes) {
if (err) throw err;
| themes.forEach(function (theme) {
cacheAndWatchTheme(app, theme);
});
})
});
} | csn_ccr |
def run_tensorboard(logdir, listen_on="0.0.0.0", port=0, tensorboard_args=None, timeout=10):
"""
Launch a new TensorBoard instance.
:param logdir: Path to a TensorFlow summary directory
:param listen_on: The IP address TensorBoard should listen on.
:param port: Port number to listen on. 0 for a ran... | raise TensorboardNotFoundError(ex)
# Wait for a message that signaliezes start of Tensorboard
start = time.time()
data = ""
while time.time() - start < timeout:
line = tensorboard_instance.read_line_stderr(time_limit=timeout)
data += line
if "at http://" in line:
... | csn_ccr |
create a database, including user name and pwd | function createDb(config, dbUser, dbUserPass, dbName, cb) {
log.logger.trace({user: dbUser, pwd: dbUserPass, name: dbName}, 'creating new datatbase');
var url = config.mongoUrl;
var admin = config.mongo.admin_auth.user;
var admin_pass = config.mongo.admin_auth.pass;
MongoClient.connect(url, function(err, db)... | 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 |
def largest_indices(arr, n):
"Returns the `n` largest indices from a numpy array `arr`."
#https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array
flat = arr.flatten()
| indices = np.argpartition(flat, -n)[-n:]
indices = indices[np.argsort(-flat[indices])]
return np.unravel_index(indices, arr.shape) | csn_ccr |
Parse the lines of an os-release file.
Parameters:
* lines: Iterable through the lines in the os-release file.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A dictionary containing all information items. | def _parse_os_release_content(lines):
"""
Parse the lines of an os-release file.
Parameters:
* lines: Iterable through the lines in the os-release file.
Each line must be a unicode string or a UTF-8 encoded byte
string.
Returns:
A ... | csn |
def WriteSignedBinaryBlobs(binary_urn,
blobs,
token = None):
"""Saves signed blobs to the datastore.
If a signed binary with the given URN already exists, its contents will get
overwritten.
Args:
binary_urn: RDFURN that should serve as a unique identif... |
for blob in blobs:
fd.Add(blob, mutation_pool=mutation_pool)
if data_store.RelationalDBEnabled():
blob_references = rdf_objects.BlobReferences()
current_offset = 0
for blob in blobs:
blob_id = data_store.BLOBS.WriteBlobWithUnknownHash(
blob.SerializeToString())
bl... | csn_ccr |
Returns the date that the specified entry started being processed.
This method will return <b>FALSE</b> if the list has not yet been filled.
The time will be in the ISO8601 date format.
@param int $i [optional] <p>List index to retrieve the value from. Defaults to 0.</p>
@return string|boolean single value, or <b>FALS... | public function getDateStarted($i = 0){
if (is_numeric($i) && isset($this->feedList) && is_array($this->feedList) && isset($this->feedList[$i]['StartedProcessingDate'])){
return $this->feedList[$i]['StartedProcessingDate'];
} else {
return false;
}
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.