query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
public void set(float val, Layout.Axis axis) {
switch (axis) {
case X:
x = val;
break;
case Y:
y = val;
break;
case Z:
z = val;
| break;
default:
throw new RuntimeAssertion("Bad axis specified: %s", axis);
}
} | csn_ccr |
Builds canonical in book url from a pages metadata. | def get_canonical_url(metadata, request):
"""Builds canonical in book url from a pages metadata."""
slug_title = u'/{}'.format('-'.join(metadata['title'].split()))
settings = get_current_registry().settings
canon_host = settings.get('canonical-hostname',
re.sub('archive.',... | csn |
Proxy method to help with test mocking
@param array $query
@param array $update
@param array $options
@return UpdateOneResult
@codeCoverageIgnore | protected function updateTransaction($query, $update, $options)
{
return $this->transaction_collection->updateOne($query, $update, $options);
} | csn |
func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger {
return &SimpleLogger{
DEBUG: log.New(out, fmt.Sprintf("%s [debug] ", prefix), flag),
ERR: log.New(out, fmt.Sprintf("%s [error] ", prefix), flag),
INFO: | log.New(out, fmt.Sprintf("%s [info] ", prefix), flag),
WARN: log.New(out, fmt.Sprintf("%s [warn] ", prefix), flag),
level: l,
}
} | csn_ccr |
Normalize column lists
EXAMPLE:
$list = [
'column_a',
'column_b' => value,
];
return [
'column_a' => $default,
'column_b' => value,
];
NOTE:
- Columns can not contain only numbers
@param mixed[] $list Array to be normalized
@param mixed $default Value to columns listed as value
@return mixed[] | final protected static function normalizeColumnList($list, $default = null)
{
$result = [];
foreach ($list as $key => $value) {
if (is_int($key)) {
$result[$value] = $default;
} else {
$result[$key] = $value;
}
}
ret... | csn |
Takes an input dir and returns the du on that local directory. Very basic
implementation.
@param dir
The input dir to get the disk space of this local dir
@return The total disk space of the input local directory | public static long getDU(File dir) {
long size = 0;
if (!dir.exists())
return 0;
if (!dir.isDirectory()) {
return dir.length();
} else {
size = dir.length();
File[] allFiles = dir.listFiles();
for (int i = 0; i < allFiles.length; i++) {
size = size + getDU(allFiles[... | csn |
Render unordered list tag
@param string $content
@param array $attributes
@return string | public static function ul(
string $content = null,
array $attributes = []
) : string
{
return self::tag("ul", $content, $attributes);
} | csn |
// AddDatapoints sample length of slice and pass on | func (h *HistoCounter) AddDatapoints(ctx context.Context, points []*datapoint.Datapoint, next Sink) error {
h.DatapointBucket.Add(float64(len(points)))
return h.sink.AddDatapoints(ctx, points, next)
} | csn |
public function eachWeeks($weeks = 1, \Closure $callback, $onlyFullWeek = false)
{
if ($this->lengthInWeeks() > 0) {
return $this->each(
new \DateInterval("P{$weeks}W"),
function (CarbonPeriod $period) use ($weeks, $callback, $onlyFullWeek) {
i... | (!$onlyFullWeek || $period->lengthInWeeks() === $weeks) {
call_user_func_array($callback, func_get_args());
}
}
);
}
return $this;
} | csn_ccr |
private static void configure(InputStream input, Map<String, String> substitutionVariables) {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(configureContext(lc, substitutionVariables));
... | } catch (JoranException e) {
// StatusPrinter will handle this
} finally {
IOUtils.closeQuietly(input);
}
StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
} | csn_ccr |
public function load($uri, $validate = false)
{
$this->loadImplementation($uri, $validate, | false);
// We now are sure that the URI is valid.
$this->setUrl($uri);
} | csn_ccr |
public static String quoteComment(String comment) {
int len = comment.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
char c = comment.charAt(i);
if | (c == '(' || c == ')' || c == '\\') {
sb.append('\\');
}
sb.append(c);
}
return sb.toString();
} | csn_ccr |
Returns the remainder after number is divided by divisor | def mod(ctx, number, divisor):
"""
Returns the remainder after number is divided by divisor
"""
number = conversions.to_decimal(number, ctx)
divisor = conversions.to_decimal(divisor, ctx)
return number - divisor * _int(ctx, number / divisor) | csn |
def word_slice(ctx, text, start, stop=0, by_spaces=False):
"""
Extracts a substring spanning from start up to but not-including stop
"""
text = conversions.to_string(text, ctx)
start = conversions.to_integer(start, ctx)
stop = conversions.to_integer(stop, ctx)
by_spaces = conversions.to_bool... | stop = None
elif stop > 0:
stop -= 1 # convert to a zero-based offset
words = __get_words(text, by_spaces)
selection = operator.getitem(words, slice(start, stop))
# re-combine selected words with a single space
return ' '.join(selection) | csn_ccr |
Ideal gas Helmholtz free energy and derivatives
Parameters
----------
tau : float
Inverse reduced temperature Tc/T, [-]
delta : float
Reduced density rho/rhoc, [-]
Returns
-------
prop : dictionary with ideal adimensional helmholtz energy... | def _phi0(self, tau, delta):
"""Ideal gas Helmholtz free energy and derivatives
Parameters
----------
tau : float
Inverse reduced temperature Tc/T, [-]
delta : float
Reduced density rho/rhoc, [-]
Returns
-------
prop : dictionary ... | csn |
Update a mysql password for the provided username changing the
leader settings
To update root's password pass `None` in the username | def set_mysql_password(self, username, password):
"""Update a mysql password for the provided username changing the
leader settings
To update root's password pass `None` in the username
"""
if username is None:
username = 'root'
# get root password via lead... | csn |
// GetBranch return branch of the Che project which location matches codebase URL | func getBranch(projects []che.WorkspaceProject, codebaseURL string) string {
for _, p := range projects {
if p.Source.Location == codebaseURL {
return p.Source.Parameters.Branch
}
}
return ""
} | csn |
def close(self):
"""
Close the stream. Assumes stream has 'close' method.
"""
self.out_stream.close()
| # If we're asked to write in place, substitute the named
# temporary file for the current file
if self.in_place:
shutil.move(self.temp_file.name, self.out) | csn_ccr |
public static FlowType getKey(int ordinal) {
if (ordinal >= 0 && ordinal < _values.length) {
return | _values[ordinal];
}
return null;
} | csn_ccr |
Answers an array containing the values of the viewport fields.
@return array | public function getViewportValues()
{
$values = [];
foreach ($this->getViewports() as $viewport) {
$values[$viewport] = $this->getViewportField($viewport)->dataValue();
}
return $values;
} | csn |
func encodeDateTime(t time.Time) (res []byte) {
// base date in days since Jan 1st 1900
basedays := gregorianDays(1900, 1)
// days since Jan 1st 1900 (same TZ as t)
days := gregorianDays(t.Year(), t.YearDay()) - basedays
tm := 300*(t.Second()+t.Minute()*60+t.Hour()*60*60) + t.Nanosecond()*300/1e9
// minimum and m... | 0
}
if days > maxdays {
days = maxdays
tm = (23*60*60+59*60+59)*300 + 299
}
res = make([]byte, 8)
binary.LittleEndian.PutUint32(res[0:4], uint32(days))
binary.LittleEndian.PutUint32(res[4:8], uint32(tm))
return
} | csn_ccr |
func (p *point) RoundedString(d time.Duration) string {
if p.Time().IsZero() {
return fmt.Sprintf("%s | %s", p.Key(), string(p.fields))
}
return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
p.time.Round(d).UnixNano())
} | csn_ccr |
Handles "authorizeSecurityGroupEgress" request to SecurityGroup and returns response with a SecurityGroup.
@param groupId group Id for SecurityGroup.
@param ipProtocol Ip protocol Name.
@param fromPort from port ranges.
@param toPort to port ranges.
@param cidrIp cidr Ip for Permission
@return a AuthorizeSecurityGroup... | private AuthorizeSecurityGroupEgressResponseType authorizeSecurityGroupEgress(final String groupId,
final String ipProtocol, final Integer fromPort, final Integer toPort, final String cidrIp) {
AuthorizeSecurityGroupEgressResponseType ret = new AuthorizeSecurityGroupEgressResponseType();
ret.se... | csn |
Regenerates the users API key.
@param \CachetHQ\Cachet\Models\User $user
@return \Illuminate\View\View | public function regenerateApiKey(User $user)
{
$user->api_key = User::generateApiKey();
$user->save();
event(new UserRegeneratedApiTokenEvent($user));
return cachet_redirect('dashboard.user');
} | csn |
def train_vine(self, tree_type):
"""Train vine."""
LOGGER.debug('start building tree : 0')
tree_1 = Tree(tree_type)
tree_1.fit(0, self.n_var, self.tau_mat, self.u_matrix)
self.trees.append(tree_1)
LOGGER.debug('finish building tree : 0')
for k in range(1, min(sel... |
# get constraints from previous tree
self.trees[k - 1]._get_constraints()
tau = self.trees[k - 1].get_tau_matrix()
LOGGER.debug('start building tree: {0}'.format(k))
tree_k = Tree(tree_type)
tree_k.fit(k, self.n_var - k, tau, self.trees[k - 1])
... | csn_ccr |
function findBlinkSticks (filter) {
if (filter === undefined) filter = function () { return true; };
var result = [], device, i, devices;
if (isWin) {
devices = usb.devices();
for (i in devices) {
device = devices[i];
if (device.vendorId === VENDOR_ID &&
... | }
} else {
devices = usb.getDeviceList();
for (i in devices) {
device = devices[i];
if (device.deviceDescriptor.idVendor === VENDOR_ID &&
device.deviceDescriptor.idProduct === PRODUCT_ID &&
filter(device))
result.push(new... | csn_ccr |
Validates insert values against the constraint of a modifiable view.
@param validatorTable Table that may wrap a ModifiableViewTable
@param source The values being inserted
@param targetRowType The target type for the view | private void checkConstraint(
SqlValidatorTable validatorTable,
SqlNode source,
RelDataType targetRowType) {
final ModifiableViewTable modifiableViewTable =
validatorTable.unwrap(ModifiableViewTable.class);
if (modifiableViewTable != null && source instanceof SqlCall) {
final Table table = modifiableVie... | csn |
Read the GML representation with a specified SRID
@param gmlFile
@param srid
@return
@throws org.xml.sax.SAXException
@throws java.io.IOException
@throws javax.xml.parsers.ParserConfigurationException | public static Geometry toGeometry(String gmlFile, int srid) throws SAXException, IOException, ParserConfigurationException {
if (gmlFile == null) {
return null;
}
if (gf == null) {
gf = new GeometryFactory(new PrecisionModel(), srid);
}
GMLReader gMLReader... | csn |
Annotate a parameter of the action being defined.
@param name: name of the parameter defined.
@type name: unicode or str
@param value_info: the parameter value information.
@type value_info: value.IValueInfo
@param is_required: if the parameter is required or optional.
@type is_required: bool
... | def param(name, value_info, is_required=True, label=None, desc=None):
"""
Annotate a parameter of the action being defined.
@param name: name of the parameter defined.
@type name: unicode or str
@param value_info: the parameter value information.
@type value_info: value.IValueInfo
@param is_... | csn |
Generic resource.present state method. Pagerduty state modules should be a thin wrapper over this method,
with a custom diff function.
This method calls create_or_update_resource() and formats the result as a salt state return value.
example:
resource_present("users", ["id","name","email"]) | def resource_present(resource, identifier_fields, diff=None, profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Generic resource.present state method. Pagerduty state modules should be a thin wrapper over this method,
with a custom diff function.
This method calls create_or_update_reso... | csn |
Remove a custom event. Call without parameters to remove all events.
@param {String} event Event name.
@param {Function} fn Listener to remove. Leave empty to remove all.
@param {Number} id (optional) Only remove events for this sound.
@return {Howl} | function(event, fn, id) {
var self = this;
var events = self['_on' + event];
var i = 0;
// Allow passing just an event and ID.
if (typeof fn === 'number') {
id = fn;
fn = null;
}
if (fn || id) {
// Loop through event store and remove the passed functio... | csn |
Connects to the specified given connection using the given auth key. | async def connect(self, connection):
"""
Connects to the specified given connection using the given auth key.
"""
if self._user_connected:
self._log.info('User is already connected!')
return
self._connection = connection
await self._connect()
... | csn |
func (s *Server) StartMonitoring() error {
// Snapshot server options.
opts := s.getOpts()
// Specifying both HTTP and HTTPS ports is a misconfiguration
if opts.HTTPPort != 0 && opts.HTTPSPort != 0 {
return fmt.Errorf("can't specify both HTTP (%v) and HTTPs (%v) ports", opts.HTTPPort, opts.HTTPSPort)
}
var err... | opts.HTTPPort != 0 {
err = s.startMonitoring(false)
} else if opts.HTTPSPort != 0 {
if opts.TLSConfig == nil {
return fmt.Errorf("TLS cert and key required for HTTPS")
}
err = s.startMonitoring(true)
}
return err
} | csn_ccr |
Initialize XLog. | private void initXlog() {
LogConfiguration config = new LogConfiguration.Builder()
.logLevel(BuildConfig.DEBUG ? LogLevel.ALL // Specify log level, logs below this level won't be printed, default: LogLevel.ALL
: LogLevel.NONE)
.tag(getString(R.string.global_tag)) ... | csn |
public function setEncoding($encoding = null)
{
if ($encoding !== null) {
if (!function_exists('mb_strtolower')) {
throw new Exception\ExtensionNotLoadedException(sprintf(
'%s requires mbstring extension to be loaded',
get_class($this)
... | throw new Exception\InvalidArgumentException(sprintf(
"Encoding '%s' is not supported by mbstring extension",
$encoding
));
}
}
$this->options['encoding'] = $encoding;
return $this;
} | csn_ccr |
public function parseResponse($response)
{
$this->responseRaw = $response;
try {
$parser = new \Genesis\Parser('xml');
$parser->skipRootNode();
$parser->parseDocument($response);
$this->responseObj = $parser->getObject();
} catch (\Exception ... | 'Unknown transaction status',
isset($this->responseObj->code) ? $this->responseObj->code : 0
);
}
if ($state->isError() && !$this->suppressReconciliationException()) {
throw new \Genesis\Exceptions\ErrorAPI(
... | csn_ccr |
function (out) {
// PENDING
if (this.transformNeedsUpdate()) {
this.updateWorldTransform();
}
var m = this.worldTransform.array;
| if (out) {
var arr = out.array;
arr[0] = m[12];
arr[1] = m[13];
arr[2] = m[14];
return out;
}
else {
return new Vector3(m[12], m[13], m[14]);
}
} | csn_ccr |
function setTimeAttackSynchStartPeriod($synch, $multicall = false)
{
if (!is_int($synch)) {
throw new InvalidArgumentException('synch = ' . print_r($synch, true));
} |
return $this->execute(ucfirst(__FUNCTION__), array($synch), $multicall);
} | csn_ccr |
def list_farms():
"""
List all farms you can manage. If you have selected a farm already, the
name of that farm will be prefixed with an asterisk in the returned list.
"""
utils.check_for_cloud_server()
utils.check_for_cloud_user()
server = Server(config["cloud_server"]["url"])
server.lo... | "No farms exist. Run `openag cloud create_farm` to create one"
)
active_farm_name = config["cloud_server"]["farm_name"]
for farm_name in farms_list:
if farm_name == active_farm_name:
click.echo("*"+farm_name)
else:
click.echo(farm_name) | csn_ccr |
You are given two sorted arrays that contain only integers. Your task is to find a way to merge them into a single one, sorted in **ascending order**. Complete the function `mergeArrays(arr1, arr2)`, where `arr1` and `arr2` are the original sorted arrays.
You don't need to worry about validation, since `arr1` and `arr... | def merge_arrays(arr1, arr2):
return sorted(set(arr1+arr2)) | apps |
def get_mechs_available():
"""
Returns a list of auth mechanisms that are available to the local
GSSAPI instance. Because we are interacting with Windows, we only
care if SPNEGO, Kerberos and NTLM are available where NTLM is the
only wildcard that may not be available by default.... |
"username",
"password"
)
ntlm_context.step()
set_sec_context_option(reset_mech, context=ntlm_context,
value=b"\x00" * 4)
except gssapi.exceptions.GSSError as exc:
# failed to init NTLM and verify ... | csn_ccr |
// StopWord sets the stopwords. Any word in this set is considered
// "uninteresting" and ignored. Even if your Analyzer allows stopwords,
// you might want to tell the MoreLikeThis code to ignore them, as for
// the purposes of document similarity it seems reasonable to assume that
// "a stop word is never interesting... | func (q *MoreLikeThisQuery) StopWord(stopWords ...string) *MoreLikeThisQuery {
q.stopWords = append(q.stopWords, stopWords...)
return q
} | csn |
def __is_valid_pos(pos_tuple, valid_pos):
# type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool
"""This function checks token's pos is with in POS set that user specified.
If token meets all conditions, Return True; else return False
"""
def is_valid_pos(valid_pos_tuple):
# type: (... | return True
else:
return False
seq_bool_flags = [is_valid_pos(valid_pos_tuple) for valid_pos_tuple in valid_pos]
if True in set(seq_bool_flags):
return True
else:
return False | csn_ccr |
if unescapedPart is non null, then escapes any characters in it that aren't
valid characters in a url and also escapes any special characters that
appear in extra.
@param unescapedPart {string}
@param extra {RegExp} a character set of characters in [\01-\177].
@return {string|null} null iff unescapedPart == null. | function encodeIfExists2(unescapedPart, extra) {
if ('string' == typeof unescapedPart) {
return encodeURI(unescapedPart).replace(extra, encodeOne);
}
return null;
} | csn |
function addAvailableRoutes(router) {
return (req, res, next) => {
const routes = router.stack
.filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff)
.map((r) => r.route.path); | // pull out their paths
res.locals.routes = routes; // and add them to the locals
next();
};
} | csn_ccr |
python correctly specify tensorflow as a dependency | def unit_ball_L2(shape):
"""A tensorflow variable tranfomed to be constrained in a L2 unit ball.
EXPERIMENTAL: Do not use for adverserial examples if you need to be confident
they are strong attacks. We are not yet confident in this code.
"""
x = tf.Variable(tf.zeros(shape))
return constrain_L2(x) | cosqa |
Get the comment for the requested entry | def get_comment(self, item):
"""
Get the comment for the requested entry
"""
key = item.upper()
if key not in self._record_map:
raise KeyError("unknown record: %s" % key)
if 'comment' not in self._record_map[key]:
return None
else:
... | csn |
def _produce_output(report, failed, setup):
'''
Produce output from the report dictionary generated by _generate_report
'''
report_format = setup.get('report_format', 'yaml')
log.debug('highstate output format: %s', report_format)
if report_format == 'json':
report_text = salt.utils.js... | subject = setup.get('smtp_failure_subject', 'Installation failure')
else:
subject = setup.get('smtp_success_subject', 'Installation success')
subject = _sprinkle(subject)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipients
log.debug('h... | csn_ccr |
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Give... | class Solution:
def getPermutation(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
nums = list("123456789")
k -= 1
factor = 1
for i in range(1, n):
factor *= i
res = []
for i in reversed(list(... | apps |
Shorter and fast way to select multiple nodes in the DOM
@param { String } selector - DOM selector
@param { Object } ctx - DOM node where the targets of our search will is located
@returns { Object } dom nodes found | function $$(selector, ctx) {
return Array.prototype.slice.call((ctx || document).querySelectorAll(selector))
} | csn |
static function validate($schema, $value, $helper = NULL) {
foreach (self::parseConstraints($schema) as $c) { // The constraints are in a numeric array as the order matters.
$constraint = key($c);
$params = $c[$constraint];
if | (self::isBlank($value) && ! preg_match('/require|notblank/i', $constraint)) continue; // Only *require* validators should check blank values.
$value = self::constrain($value, $constraint, self::parseParams($params, $schema), $helper);
}
return $value;
} | csn_ccr |
public function render($parent_id = false)
{
// Available options for this menu.
$container_tag = array_get($this->option, 'tag', 'ul');
$item_tag = array_get($this->option, 'item_tag', 'li');
$item_callback = array_get($this->option, 'item_callback', null);
$text_only = arra... | $item->setItemTagOption($item_tag)
->setContainerTagOption($container_tag);
if (!is_null($item_callback) && is_callable($item_callback)) {
$item_callback($item);
$item->setItemCallbackOption($item_callback);
}
$html .= $item-... | csn_ccr |
private V binarySearch(final K iKey) {
int low = 0;
int high = getSize() - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) >>> 1;
Object midVal = getKeyAt(mid);
if (tree.comparator != null)
tree.pageItemComparator = tree.comparator.compare((K) midVal, iKey)... | tree.pageItemComparator = ((Comparable<? super K>) midVal).compareTo(iKey);
if (tree.pageItemComparator == 0) {
// FOUND: SET THE INDEX AND RETURN THE NODE
tree.pageItemFound = true;
tree.pageIndex = mid;
return getValueAt(tree.pageIndex);
}
if (low == h... | csn_ccr |
public function getRoute($route = '', $fqr = true, $escape = true)
{
if(is_string($route)) {
parse_str(trim($route), $parts);
} else {
$parts = $route;
}
//Check to see if there is component information in the route if not add it
if (!isset($parts['co... | if (!isset($parts['layout']) && !empty($this->_layout))
{
if (($parts['component'] == $this->getIdentifier()->package) && ($parts['view'] == $this->getName())) {
$parts['layout'] = $this->getLayout();
}
}
return parent::getRoute($parts, $fqr, $escape);... | csn_ccr |
func buildHuffmanTree(symFreqs []int) huffmanTree {
var trees treeHeap
for v, w := range symFreqs {
if w == 0 {
w = 1
}
trees = append(trees, &huffmanLeaf{w, v})
}
n := 40
heap.Init(&trees)
for trees.Len() > 1 {
| a := heap.Pop(&trees).(huffmanTree)
b := heap.Pop(&trees).(huffmanTree)
heap.Push(&trees, &huffmanNode{a.Weight() + b.Weight(), n, a, b})
n++
}
return heap.Pop(&trees).(huffmanTree)
} | csn_ccr |
def runGetReadGroupSet(self, id_):
"""
Returns a readGroupSet with the given id_
"""
compoundId = datamodel.ReadGroupSetCompoundId.parse(id_)
dataset | = self.getDataRepository().getDataset(compoundId.dataset_id)
readGroupSet = dataset.getReadGroupSet(id_)
return self.runGetRequest(readGroupSet) | csn_ccr |
function validateMode() {
if (angular.isUndefined(attr.mdMode)) {
var hasValue = angular.isDefined(attr.value);
var mode = hasValue ? MODE_DETERMINATE : MODE_INDETERMINATE;
var info = "Auto-adding the missing | md-mode='{0}' to the ProgressLinear element";
element.attr("md-mode", mode);
attr.mdMode = mode;
}
} | csn_ccr |
python show max width and max columns | def getFieldsColumnLengths(self):
"""
Gets the maximum length of each column in the field table
"""
nameLen = 0
descLen = 0
for f in self.fields:
nameLen = max(nameLen, len(f['title']))
descLen = max(descLen, len(f['description']))
return (... | cosqa |
func (m *Memory) Print() {
fmt.Printf("### mem %d bytes ###\n", len(m.store))
if len(m.store) > 0 {
addr := 0
for i := 0; i+32 <= len(m.store); i += 32 {
fmt.Printf("%03d: % x\n", addr, m.store[i:i+32])
| addr++
}
} else {
fmt.Println("-- empty --")
}
fmt.Println("####################")
} | csn_ccr |
protected function addLookups(Route $route)
{
$action = $route->getAction();
if (isset($action['as'])) {
| $this->names[$action['as']] = $route;
}
if (isset($action['controller'])) {
$this->actions[$action['controller']] = $route;
}
} | csn_ccr |
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
CLI Example:
.. code-block:: bash
salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]'
'''
keyword = None
match = re.match('^(... | return False
try:
cur_repo, cur_use = _vartree().dbapi.aux_get(cpv, ['repository', 'USE'])
except KeyError:
return False
des_repo = re.match(r'^.+::([^\[]+).*$', atom)
if des_repo and des_repo.group(1) != cur_repo:
return False
des_uses = set(portage.dep.dep_getusedeps(... | csn_ccr |
Adapted from
pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound | def _maybe_cast_slice_bound(self, label, side, kind):
"""Adapted from
pandas.tseries.index.DatetimeIndex._maybe_cast_slice_bound"""
if isinstance(label, str):
parsed, resolution = _parse_iso8601_with_reso(self.date_type,
label... | csn |
python remove all xml namespaces | def remove_namespaces(root):
"""Call this on an lxml.etree document to remove all namespaces"""
for elem in root.getiterator():
if not hasattr(elem.tag, 'find'):
continue
i = elem.tag.find('}')
if i >= 0:
elem.tag = elem.tag[i + 1:]
objectify.deannotate(root... | cosqa |
If the item belongs to an activation group, add it
@param item | public void addItemToActivationGroup(final AgendaItem item) {
if ( item.isRuleAgendaItem() ) {
throw new UnsupportedOperationException("defensive programming, making sure this isn't called, before removing");
}
String group = item.getRule().getActivationGroup();
if ( group !=... | csn |
// validate returns an error if s is not a known task status. | func (s TaskStatus) validate(allowEmpty bool) error {
if allowEmpty && s == "" {
return nil
}
if s == TaskActive || s == TaskInactive {
return nil
}
return fmt.Errorf("invalid task status: %q", s)
} | csn |
There is a big staircase with $N$ steps (numbered $1$ through $N$) in ChefLand. Let's denote the height of the top of step $i$ by $h_i$. Chef Ada is currently under the staircase at height $0$ and she wants to reach the top of the staircase (the top of the last step). However, she can only jump from height $h_i$ to the... | # cook your dish here
import numpy as np
def minstairs(n,k):
stairsHeight=[]
stairs=0
current = 0
stairsHeight=list(map(int, input().split()))
stairsHeight=np.array(stairsHeight)
curr=0
for i in range(n):
if stairsHeight[i]-curr<=k:
curr=stairsHeight[i]
else:
if (stairsHeight[i]-curr)%k==0:
sta... | apps |
// Output allows setting an output writer for logging to be written to | func Output(out io.Writer) Option {
return func(l *handler) {
l.out = out
}
} | csn |
Finalizes the upload on the API server. | def _finalize_upload(self):
"""
Finalizes the upload on the API server.
"""
from sevenbridges.models.file import File
try:
response = self._api.post(
self._URL['upload_complete'].format(upload_id=self._upload_id)
).json()
self._... | csn |
Sets the code of the currency.
@param string $key Code of the currency | public function setCode( $key )
{
if ( $key == $this->getCode() ) { return; }
if ( strlen($key) != 3 || ctype_alpha( $key ) === false ) {
throw new MShop_Locale_Exception( sprintf( 'Invalid characters in ISO currency code "%1$s"', $key ) );
}
$this->_values['code'] = strtoupper( $key );
$this->_modified... | csn |
python best way to see if file has changed | def has_changed (filename):
"""Check if filename has changed since the last check. If this
is the first check, assume the file is changed."""
key = os.path.abspath(filename)
mtime = get_mtime(key)
if key not in _mtime_cache:
_mtime_cache[key] = mtime
return True
return mtime > _m... | cosqa |
Triggers object focus
@alias module:lib3d.onMouseMove
@param {Object} event - mouse event
@param {Environment} env - affected environment
@param {Boolean} isSideEffectsDisabled - disable side effects like focusing, selecting, moving objects | function onMouseMove(event, env, isSideEffectsDisabled) {
event.preventDefault();
mouse.move(event, env ? env.camera : null);
if (!env || isSideEffectsDisabled) {
return;
}
if(mouse.keys[1] && !mouse.keys[3]) {
moveObject(env.library, env.camera, env.selector);
} else {
... | csn |
python union of nonoverlapping intervals | def union_overlapping(intervals):
"""Union any overlapping intervals in the given set."""
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:... | cosqa |
determine timezone pytz function python | def now(timezone=None):
"""
Return a naive datetime object for the given ``timezone``. A ``timezone``
is any pytz- like or datetime.tzinfo-like timezone object. If no timezone
is given, then UTC is assumed.
This method is best used with pytz installed::
pip install pytz
"""
d = dat... | cosqa |
Copy a bitset.
Note: Bits beyond mincap <em>may</em> be retained!
@param v Array to copy
@param mincap Target <em>minimum</em> capacity
@return Copy with space for at least "capacity" bits | public static long[] copy(long[] v, int mincap) {
int words = ((mincap - 1) >>> LONG_LOG2_SIZE) + 1;
if(v.length == words) {
return Arrays.copyOf(v, v.length);
}
long[] ret = new long[words];
System.arraycopy(v, 0, ret, 0, Math.min(v.length, words));
return ret;
} | csn |
public function dividedBy(int $divisor) : Duration
{
if ($divisor === 0) {
throw new DateTimeException('Cannot divide a Duration by zero.');
}
if ($divisor === 1) {
return $this;
}
$seconds = $this->seconds;
$nanos = $this->nanos;
if... | = LocalTime::NANOS_PER_SECOND % $divisor;
$nanos += $remainder * \intdiv(LocalTime::NANOS_PER_SECOND, $divisor);
$nanos += \intdiv($r1 + $remainder * $r2, $divisor);
if ($nanos < 0) {
$seconds--;
$nanos = LocalTime::NANOS_PER_SECOND + $nanos;
}
return n... | csn_ccr |
jaccard similarity product labelling python | def compute_jaccard_index(x_set, y_set):
"""Return the Jaccard similarity coefficient of 2 given sets.
Args:
x_set (set): first set.
y_set (set): second set.
Returns:
float: Jaccard similarity coefficient.
"""
if not x_set or not y_set:
return 0.0
intersection... | cosqa |
Prepares a PDOStatement for execution and returns it.
@return PDOStatement | protected function getPdoStatement()
{
$statement = $this->connection->prepare($this->getSql());
if ($this->dataRowClass !== null) {
$statement->setFetchMode(PDO::FETCH_CLASS, $this->dataRowClass);
} else {
$statement->setFetchMode(PDO::FETCH_OBJ);
}
r... | csn |
how to make 80th percentile on python histogram | def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis) | cosqa |
Creates a new buffer which wraps the specified NIO buffer's current
slice. A modification on the specified buffer's content will be
visible to the returned buffer. | public static ByteBuf wrappedBuffer(ByteBuffer buffer) {
if (!buffer.hasRemaining()) {
return EMPTY_BUFFER;
}
if (!buffer.isDirect() && buffer.hasArray()) {
return wrappedBuffer(
buffer.array(),
buffer.arrayOffset() + buffer.positio... | csn |
Get the rendered center | function getRenderedCenter(target, renderedDimensions){
let pos = target.renderedPosition();
let dimensions = renderedDimensions(target);
let offsetX = dimensions.w / 2;
let offsetY = dimensions.h / 2;
return {
x : (pos.x - offsetX),
y : (pos.y - offsetY)
};
} | csn |
Ensure elements capacity. | protected void ensureElementsCapacity() {
final int elStackSize = elName.length;
// assert (depth + 1) >= elName.length;
// we add at least one extra slot ...
final int newSize = (depth >= 7 ? 2 * depth : 8) + 2; // = lucky 7 + 1
// //25
if (TRACE_SIZING) {
System.err.println(getClass().get... | csn |
Logout path for given user
@see Wallaby::Configuration::Security#logout_path
@param user [Object]
@param app [Object]
@return [String] URL to log out | def logout_path(user = current_user, app = main_app)
path = security.logout_path
path ||=
if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
"destroy_#{scope}_session_path"
end
ModuleUtils.try_to app, path
end | csn |
def fetch_data(self):
"""Get the latest data from HydroQuebec."""
# Get http session
yield from self._get_httpsession()
# Get login page
login_url = yield from self._get_login_page()
# Post login page
yield from self._post_login_page(login_url)
# Get p_p_i... | daily_data = yield from self._get_daily_data(p_p_id, start_date, end_date)
except Exception: # pylint: disable=W0703
daily_data = []
# We have to test daily_data because it's empty
# At the end/starts of a period
if daily_data:
... | csn_ccr |
public function selectFieldOption($locator, $value, $multiple = false)
{
$field = $this->findField($locator);
if (null === $field) {
throw new | ElementNotFoundException($this->getDriver(), 'form field', 'id|name|label|value', $locator);
}
$field->selectOption($value, $multiple);
} | csn_ccr |
// Continue the execution of this thread.
//
// If we are currently at a breakpoint, we'll clear it
// first and then resume execution. Thread will continue until
// it hits a breakpoint or is signaled. | func (t *Thread) Continue() error {
pc, err := t.PC()
if err != nil {
return err
}
// Check whether we are stopped at a breakpoint, and
// if so, single step over it before continuing.
if _, ok := t.dbp.FindBreakpoint(pc); ok {
if err := t.StepInstruction(); err != nil {
return err
}
}
return t.resume(... | csn |
Find if an user exists in a specific database on the MS SQL server.
domain, if provided, will be prepended to username
CLI Example:
.. code-block:: bash
salt minion mssql.user_exists 'USERNAME' [database='DBNAME'] | def user_exists(username, domain='', database=None, **kwargs):
'''
Find if an user exists in a specific database on the MS SQL server.
domain, if provided, will be prepended to username
CLI Example:
.. code-block:: bash
salt minion mssql.user_exists 'USERNAME' [database='DBNAME']
'''
... | csn |
function prepareResponse($endform=false) {
$return_url = $this->returnUrl();
$parms = $this->getContentItemSelection();
$parms = LTIX::signParameters($parms, $return_url, "POST", "Install Content");
$endform = '<a href="index.php" class="btn btn-warning">Back | to Store</a>';
$content = LTI::postLaunchHTML($parms, $return_url, true, false, $endform);
return $content;
} | csn_ccr |
def evaluate(context, *args, &block)
self.result = if block
context.define_singleton_method(:__callback__, &self)
ret = context.send :__callback__, *args, &block
context.class_eval { | send :remove_method, :__callback__ }
ret
else
context.instance_exec(*args, &self)
end
end | csn_ccr |
def _update_states(self, uid, states):
"""
Got states of all buttons from a controller. Now check if something changed and create events if neccesary.
:param uid: Unique id of the controller
:param states: Buttons states
:type uid: str
:type states: str
"""
... | self.queue.put_nowait(e)
elif int(old_states[key]) < int(states[key]):
e = Event(uid, E_KEYDOWN, key)
self.queue.put_nowait(e)
self.controllers[uid][2] = states
self.controllers[uid][3... | csn_ccr |
Set the protocol version
@param string $version
@return $this | public function withProtocolVersion($version)
{
if (!is_string($version)) {
throw new \InvalidArgumentException("Expected protocol version to be a string");
}
$this->protocolVersion = $version;
$this->sendStatusHeader();
return $this;
... | csn |
Get column name by order column index.
@param int $index
@return string | protected function getColumnNameByIndex($index)
{
$name = (isset($this->columns[$index]) && $this->columns[$index] != '*')
? $this->columns[$index] : $this->getPrimaryKeyName();
return in_array($name, $this->extraColumns, true) ? $this->getPrimaryKeyName() : $name;
} | csn |
func (s *RPCServer) ListTypes(arg ListTypesIn, out *ListTypesOut) error {
tps, err := s.debugger.Types(arg.Filter)
if err | != nil {
return err
}
out.Types = tps
return nil
} | csn_ccr |
def update_property_node(node_to_insert, field_uri):
""" Helper function - generates a SetItemField which tells Exchange you want to overwrite the contents of a field."""
root = T.SetItemField(
| T.FieldURI(FieldURI=field_uri),
T.CalendarItem(node_to_insert)
)
return root | csn_ccr |
adds link to collection of links
@param string $rel
@param \stubbles\peer\http\HttpUri $uri
@return \stubbles\webapp\routing\api\Link | public function add(string $rel, HttpUri $uri): Link
{
$link = new Link($rel, $uri);
if (isset($this->links[$rel])) {
if (!is_array($this->links[$rel])) {
$this->links[$rel] = [$this->links[$rel]];
}
$this->links[$rel][] = $link;
} else {
... | csn |
def hsl2rgb(hsl):
"""Convert HSL representation towards RGB
:param h: Hue, position around the chromatic circle (h=1 equiv h=0)
:param s: Saturation, color saturation (0=full gray, 1=full color)
:param l: Ligthness, Overhaul lightness (0=full black, 1=full white)
:rtype: 3-uple for RGB values in fl... | (1.0, 0.0, 0.0)
>>> hsl2rgb((1 , 1.0, 0.5))
(1.0, 0.0, 0.0)
>>> hsl2rgb((1.0/3 , 1.0, 0.5))
(0.0, 1.0, 0.0)
>>> hsl2rgb((2.0/3 , 1.0, 0.5))
(0.0, 0.0, 1.0)
Of course:
>>> hsl2rgb((0.0, 2.0, 0.5)) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: Satu... | csn_ccr |
// services returns a list of services that are currently configured in the
// kernel IPVS table. If a specific service is given, an exact match will be
// attempted and a single service will be returned if it is found. | func services(svc *Service) ([]*Service, error) {
var flags int
if svc == nil {
flags = netlink.MFDump
}
msg, err := netlink.NewMessage(C.IPVS_CMD_GET_SERVICE, family, flags)
if err != nil {
return nil, err
}
defer msg.Free()
if svc != nil {
ic := &ipvsCommand{Service: newIPVSService(svc)}
if err := m... | csn |
function( userId, id ) {
return this.memory.leaveRoom( userId, id )
.then( function( numUsers ) {
if( numUsers == 0 ) {
// remove all listeners from room since there should be one
rooms[ id ].removeAllListeners();
rooms[ | id ].setPrivate();
delete rooms[ id ];
return promise.resolve( null );
} else {
return promise.resolve( rooms[ id ] );
}
});
} | csn_ccr |
public function doUpload()
{
$mimes = $this->getOption('mimes') ? '|mimes:' . $this->getOption('mimes') : '';
//use the multup library to perform the upload
$result = Multup::open('file', 'max:' . $this->getOption('size_limit') * 1000 . $mimes, $this->getOption('location'),
| $this->getOption('naming') === 'random')
->set_length($this->getOption('length'))
->upload();
return $result[0];
} | csn_ccr |
add millsecond to time stamp in python | def ms_to_datetime(ms):
"""
Converts a millisecond accuracy timestamp to a datetime
"""
dt = datetime.datetime.utcfromtimestamp(ms / 1000)
return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc) | cosqa |
public void write(ByteCodeWriter out)
throws IOException
{
out.writeShort(_entries.size());
for (int i = 1; i < _entries.size(); i++) {
| ConstantPoolEntry entry = _entries.get(i);
if (entry != null)
entry.write(out);
}
} | csn_ccr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.