query large_stringlengths 4 15k | positive large_stringlengths 5 289k | source stringclasses 6
values |
|---|---|---|
private void addToTail(final WComponent component) {
WContainer tail = (WContainer) | getDecoratedLabel().getTail();
if (null != tail) { // bloody well better not be...
tail.add(component);
}
} | csn_ccr |
Determine if the constraints on this definition are as-constrained or more-constrained than those on the supplied
definition.
@param other the property definition to compare; may not be null
@param context the execution context used to parse any values within the constraints
@return true if this property definition is... | boolean isAsOrMoreConstrainedThan( PropertyDefinition other,
ExecutionContext context ) {
String[] otherConstraints = other.getValueConstraints();
if (otherConstraints == null || otherConstraints.length == 0) {
// The ancestor's definition is less const... | csn |
This method distringuishes notifications caused by Matched orders
from those caused by placed orders | def _callbackPlaceFillOrders(self, d):
""" This method distringuishes notifications caused by Matched orders
from those caused by placed orders
"""
if isinstance(d, FilledOrder):
self.onOrderMatched(d)
elif isinstance(d, Order):
self.onOrderPlaced(d)
... | csn |
// ClassicWithoutStatic creates a classic Martini without a default Static. | func ClassicWithoutStatic() *martini.ClassicMartini {
r := martini.NewRouter()
m := martini.New()
m.Use(martini.Logger())
m.Use(martini.Recovery())
m.MapTo(r, (*martini.Routes)(nil))
m.Action(r.Handle)
return &martini.ClassicMartini{m, r}
} | csn |
Put users.
putUsers
@return ApiResponse<PutUsers>
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | public ApiResponse<PutUsers> putUsersWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = putUsersValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<PutUsers>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} | csn |
public function getSurvey($surveyId, $includePages = false)
{
if ($includePages) {
return $this->sendRequest(
$this->createRequest('GET', sprintf('surveys/%d/details', | $surveyId))
);
} else {
return $this->sendRequest(
$this->createRequest('GET', sprintf('surveys/%d', $surveyId))
);
}
} | csn_ccr |
function(model, options) {
options = options ? _.clone(options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) | this.add(model, options);
return this._callAdapter('addToIndex', options, model);
} | csn_ccr |
function getViewCombinations(action) {
const pathes = [action];
const positions = [];
let i;
let j;
for (i = 0; i < action.length; i++) {
if (action[i] === '-') {
positions.push(i);
}
}
const len = positions.length;
const combinations = [];
for (i = 1; i < (1 << len); i++) {
const c = [];
for (j ... | {
c.push(positions[j]);
}
}
combinations.push(c);
}
combinations.forEach((combination) => {
let combinationPath = action;
combination.forEach((pos) => {
combinationPath = replaceAt(combinationPath, pos, '/');
});
pathes.push(combinationPath);
});
return pathes;
} | csn_ccr |
def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None):
"""
Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string co... | 2,
"minorEdit": false
}
}
"""
assert isinstance(new_metadata, dict) and set(new_metadata.keys()) >= self.ATTACHMENT_METADATA_KEYS
return self._service_put_request("rest/api/content/{id}/child/attachment/{attachment_id}"
... | csn_ccr |
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note:
points.length == 3
points[i].len... | class Solution:
def isBoomerang(self, points: List[List[int]]) -> bool:
x1, y1 = points[0]
x2, y2 = points[1]
x3, y3 = points[2]
return (y2 - y1) * (x3 - x1) != (y3 - y1) * (x2 - x1)
| apps |
function (mappingObject) {
this.writeDebug('mapping',arguments);
var _this = this;
var orig_lat, orig_lng, geocodeData, origin, originPoint, page;
if (!this.isEmptyObject(mappingObject)) {
orig_lat = mappingObject.lat;
orig_lng = mappingObject.lng;
geocodeData = mappingObject.geocodeResult;
... | }
else {
// Do the data request - doing this in mapping so the lat/lng and address can be passed over and used if needed
dataRequest = _this._getData(olat, olng, origin, geocodeData, mappingObject);
}
}
// Check filters here to handle selected filtering after page reload
if (_this.settings.... | csn_ccr |
Defines a local type alias, the given string should be a Puppet Language type alias expression
in string form without the leading 'type' keyword.
Calls to local_type must be made before the first parameter definition or an error will
be raised.
@param assignment_string [String] a string on the form 'AliasType = Ex... | def type(assignment_string)
# Get location to use in case of error - this produces ruby filename and where call to 'type' occurred
# but strips off the rest of the internal "where" as it is not meaningful to user.
#
rb_location = caller[0]
begin
result = parser.parse_string("type ... | csn |
Clear all cache files
@return sFire\Cache\Filesystem | public function clear() {
$files = glob(Path :: get('cache-shared') . '*');
if(true === is_array($files)) {
foreach($files as $file) {
$file = new File($file);
$file -> delete();
}
}
return $this;
} | csn |
def get_account_by_id(budget_id, account_id, opts = {})
data, _status_code, _headers = | get_account_by_id_with_http_info(budget_id, account_id, opts)
data
end | csn_ccr |
protected function addWithNotInvited(Builder $builder): void
{
$builder->macro('withNotInvited', function (Builder $builder) {
| return $builder->withoutGlobalScope($this);
});
} | csn_ccr |
public synchronized int clear() {
final int count = taskQueue.size();
for (final TaskEntity task : taskQueue) {
| canceledTasks.add(task);
}
taskQueue.clear();
return count;
} | csn_ccr |
def page_not_found(request, template_name='404.html'):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/')
"""
response = render_in_page(request, template_name)
if response:
... |
'<p>The requested URL {{ request_path }} was not found on this server.</p>')
body = template.render(RequestContext(
request, {'request_path': request.path}))
return http.HttpResponseNotFound(body, content_type=CONTENT_TYPE) | csn_ccr |
Run flux analysis command. | def run(self):
"""Run flux analysis command."""
# Load compound information
def compound_name(id):
if id not in self._model.compounds:
return id
return self._model.compounds[id].properties.get('name', id)
# Reaction genes information
def ... | csn |
func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool {
emitter.anchor_data.anchor = nil
emitter.tag_data.handle = nil
emitter.tag_data.suffix = nil
emitter.scalar_data.value = nil
switch event.typ {
case yaml_ALIAS_EVENT:
if !yaml_emitter_analyze_anchor(emitter, event.anchor, tru... | > 0 && (emitter.canonical || !event.implicit) {
if !yaml_emitter_analyze_tag(emitter, event.tag) {
return false
}
}
case yaml_MAPPING_START_EVENT:
if len(event.anchor) > 0 {
if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
return false
}
}
if len(event.tag) > 0 && (emitter.... | csn_ccr |
public function getFiles(Project $p)
{
if ($this->isReference()) {
$ret = $this->getRef($p);
$ret = $ret->getFiles($p);
return $ret;
}
| if ($this->listfile !== null) {
$this->readListFile($p);
}
return $this->filenames;
} | csn_ccr |
// Join two Mods together, resulting in a new structure where each modification
// list is sorted alphabetically. | func (mod Mod) Join(b Mod) Mod {
return Mod{
Changed: joinLists(mod.Changed, b.Changed),
Deleted: joinLists(mod.Deleted, b.Deleted),
Added: joinLists(mod.Added, b.Added),
}
} | csn |
public function createBucket($bucketName, $options = [])
{
$this->beginProfile($token = " > create bucket $bucketName ...");
| $this->db->createBucket($bucketName, $options);
$this->endProfile($token);
} | csn_ccr |
public function logout(Adapter\AdapterInterface $adapter = null, Request $request = null)
{
$event = $this->prepareEvent($adapter, $request);
$event->setResult($event->getAdapter()->logout());
| $this->clearIdentity();
return $this->triggerEventResult(AuthenticationEvent::AUTH_LOGOUT, $event);
} | csn_ccr |
// CreateSessionIDer provides a default implement for extracting the session from a cookie jar | func CreateSessionIDer(jar http.CookieJar) RequestIDer {
return func(req *http.Request) string {
for _, c := range jar.Cookies(req.URL) {
if c.Name == RETSSessionID {
return c.Value
}
}
return ""
}
} | csn |
Sets this to a perspective projection matrix. The formula comes from the OpenGL
documentation for the glFrustum function.
@return a reference to this matrix, for chaining. | public Matrix4 setToFrustum (
double left, double right, double bottom, double top, double near, double far) {
return setToFrustum(left, right, bottom, top, near, far, Vector3.UNIT_Z);
} | csn |
def remove(self, id_option_pool):
"""Remove Option pool by identifier and all Environment related .
:param id_option_pool: Identifier of the Option Pool. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: Option Pool identifier is null and invalid.
... |
:raise optionpoolError: Option Pool associated with Pool.
:raise DataBaseError: Networkapi failed to access the database.
:raise XMLError: Networkapi failed to generate the XML response.
"""
if not is_valid_int_param(id_option_pool):
raise InvalidParameterError(
... | csn_ccr |
protected TupleWritable createInternalValue() {
Writable[] vals = new Writable[kids.length];
for (int i = 0; i < vals.length; ++i) {
| vals[i] = kids[i].createValue();
}
return new TupleWritable(vals);
} | csn_ccr |
A list of supported calendars and their names.
@return string[] | public static function calendarNames(): array
{
return [
/* I18N: The gregorian calendar */
'gregorian' => I18N::translate('Gregorian'),
/* I18N: The julian calendar */
'julian' => I18N::translate('Julian'),
/* I18N: The French calendar */
... | csn |
def regular_index(*dfs):
"""
Change & restore the indices of dataframes
Dataframe with duplicate values can be hard to work with.
When split and recombined, you cannot restore the row order.
This can be the case even if the index has unique but
irregular/unordered. This contextmanager resets th... | pd.DataFrame([3, 2, 1], index=[3, 0, 0])
>>> df3 = pd.DataFrame([11, 12, 13], index=[11, 12, 13])
Within the contexmanager all frames have nice range indices
>>> with regular_index(df1, df2, df3):
... print(df1.index)
... print(df2.index)
... print(df3.index)
RangeIndex(start=... | csn_ccr |
from goto import goto, label
label .start
for i in range(1, 4):
print i
if i == 2:
try:
output = message
except NameError:
print "Oops - forgot to define 'message'! Start again."
message = "Hello world"
goto .start
print output, "\n"
| #include <iostream>
#include <utility>
using namespace std;
int main(void)
{
cout << "Find a solution to i = 2 * j - 7\n";
pair<int, int> answer;
for(int i = 0; true; i++)
{
for(int j = 0; j < i; j++)
{
if( i == 2 * j - 7)
{
ans... | codetrans_contest |
Make one or multiple DELETE requests.
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | public static function delete($urls, $data = null, callable $callback = null)
{
return static::make('delete', $urls, $data, $callback);
} | csn |
func (d *Daemon) WithClone(ctx context.Context, fn func(*git.Checkout) error) error {
co, err := d.Repo.Clone(ctx, d.GitConfig)
if | err != nil {
return err
}
defer co.Clean()
return fn(co)
} | csn_ccr |
func MIMEType(hdr []byte) string {
hlen := len(hdr)
for _, pte := range matchTable {
if pte.fn != nil {
if pte.fn(hdr) {
return pte.mtype
}
continue
}
plen := pte.offset + len(pte.prefix)
if hlen > plen && bytes.Equal(hdr[pte.offset:plen], pte.prefix) {
return pte.mtype
| }
}
t := http.DetectContentType(hdr)
t = strings.Replace(t, "; charset=utf-8", "", 1)
if t != "application/octet-stream" && t != "text/plain" {
return t
}
return ""
} | csn_ccr |
Validate that min_count and max_count is set to 1-100 | def validate_nodes_count(namespace):
"""Validate that min_count and max_count is set to 1-100"""
if namespace.min_count is not None:
if namespace.min_count < 1 or namespace.min_count > 100:
raise CLIError('--min-count must be in the range [1,100]')
if namespace.max_count is not None:
... | csn |
Bi-directional example, which can only be asynchronous. Send some chat messages, and print any
chat messages that are sent from the server. | public CountDownLatch routeChat() {
info("*** RouteChat");
final CountDownLatch finishLatch = new CountDownLatch(1);
StreamObserver<RouteNote> requestObserver =
asyncStub.routeChat(new StreamObserver<RouteNote>() {
@Override
public void onNext(RouteNote note) {
info("... | csn |
Method to list out all files, or directory if no file exists, under a specified path. | public static List<FileStatus> listMostNestedPathRecursively(FileSystem fs, Path path)
throws IOException {
return listMostNestedPathRecursively(fs, path, NO_OP_PATH_FILTER);
} | csn |
function createClean(inPath) {
if (!inPath) {
throw new Error('Input path argument is required');
}
return function cleanDir() {
| return gulp.src(inPath, { read: false }).pipe(clean());
};
} | csn_ccr |
%prog fromagp agpfile componentfasta objectfasta
Generate chain file from AGP format. The components represent the old
genome (target) and the objects represent new genome (query). | def fromagp(args):
"""
%prog fromagp agpfile componentfasta objectfasta
Generate chain file from AGP format. The components represent the old
genome (target) and the objects represent new genome (query).
"""
from jcvi.formats.agp import AGP
from jcvi.formats.sizes import Sizes
p = Opti... | csn |
func (observer *Observer) GetAllQueues() (queues []string, err error) {
| return observer.redisClient.SMembers(masterQueueKey()).Result()
} | csn_ccr |
keep for uniqueness check | function mw(store) {
if (savedStore && savedStore !== store) {
throw new Error('cannot assign logicMiddleware instance to multiple stores, create separate instance for each');
}
savedStore = store;
return next => {
savedNext = next;
const { action$, sub, logicCount: cnt } =
... | csn |
Display index - debug page, login page, or account page | public function actionIndex()
{
if (defined('YII_DEBUG') && YII_DEBUG) {
$actions = $this->module->getActions();
return $this->render('index', ["actions" => $actions]);
} elseif (Yii::$app->user->isGuest) {
return $this->redirect(["/user/login"]);
} else {... | csn |
private void setQuestionnareAnswerForResearchTrainingPlan(
ResearchTrainingPlan researchTrainingPlan) {
researchTrainingPlan.setHumanSubjectsIndefinite(YesNoDataType.N_NO);
researchTrainingPlan.setVertebrateAnimalsIndefinite(YesNoDataType.N_NO);
researchTrainingPlan.setHumanSubjectsIndefinite(Ye... | case VERT:
researchTrainingPlan
.setVertebrateAnimalsIndefinite(answer
.equals(YnqConstant.YES.code()) ? YesNoDataType.Y_YES
: YesNoDataType.N_NO);
break;
case CLINICAL:
researchTrainingPlan
.setClinicalTrial(answer
.equals(YnqConstant.YES.code()) ? YesNoDa... | csn_ccr |
// SetIgnoreHTTP1xx sets ignore http 1xx on the health check. | func (h *HealthCheck) SetIgnoreHTTP1xx(ignore bool) *HealthCheck {
h.IgnoreHTTP1xx = &ignore
return h
} | csn |
public double getDouble(String key) {
addToDefaults(key, null);
String | value = getRequired(key);
return Double.valueOf(value);
} | csn_ccr |
func (s *WriterSender) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if err := s.writer.Flush(); err != nil {
| return err
}
s.Send(message.NewBytesMessage(s.priority, bytes.TrimRightFunc(s.buffer.Bytes(), unicode.IsSpace)))
s.buffer.Reset()
s.writer.Reset(s.buffer)
return nil
} | csn_ccr |
Meanwhile, the kingdom of K is getting ready for the marriage of the King's daughter. However, in order not to lose face in front of the relatives, the King should first finish reforms in his kingdom. As the King can not wait for his daughter's marriage, reforms must be finished as soon as possible.
The kingdom curren... | import sys
from collections import deque
def solve():
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
writelines = sys.stdout.writelines
N = int(readline())
G = [[] for i in range(N)]
for i in range(N-1):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G... | apps |
Require a provider
@param string $message
@return boolean | private function requireProvider($message = '')
{
if (empty($this->cacheProvider)) {
if (!empty($this->log)) $this->log->notice("Cache provider is not available. " . $message);
return false;
}
return true;
} | csn |
// Add the sink to the broadcaster.
//
// The provided sink must be comparable with equality. Typically, this just
// works with a regular pointer type. | func (b *Broadcaster) Add(sink Sink) error {
return b.configure(b.adds, sink)
} | csn |
// if name is still to short we will add spaces | func (l *Logger) normalizeNameLen() {
length := len(l.Name)
missing := curnamelen - length
for i := 0; i < missing; i++ {
l.Name += " "
}
} | csn |
return block for the diff of the values | def diff(self, n, axis=1):
""" return block for the diff of the values """
new_values = algos.diff(self.values, n, axis=axis)
return [self.make_block(values=new_values)] | csn |
Check if next window of specified size is available.
@param windowSize Size of window. May be smaller or larger than default window size.
@param increment The increment by which to move the window at each iteration. Note that this
method does not actually change the position. However, it checks the sign of the increme... | public boolean hasNext( int windowSize, int increment )
{
if( windowSize <= 0 )
{
throw new IllegalArgumentException( "Window size must be positive." );
}
try
{
if( increment > 0 )
{
return windowSize == mBounds.suffix( mPosition ).prefix( windowSize ).length();
}
else
{
if( mPosit... | csn |
def list_tab(user):
'''
Return the contents of the specified user's crontab
CLI Example:
.. code-block:: bash
salt '*' cron.list_tab root
'''
data = raw_cron(user)
ret = {'pre': [],
'crons': [],
'special': [],
'env': []}
flag = False
commen... | if comment is None:
comment = comment_line
else:
comment += '\n' + comment_line
elif line.find('=') > 0 and (' ' not in line or line.index('=') < line.index(' ')):
# Appears to be a ENV setup line
comps = line.split('... | csn_ccr |
def get_field_keys(self, pattern=None):
"""
Builds a set of all field keys used in the pattern including nested fields.
:param pattern: The kmatch pattern to get field keys from or None to use self.pattern
:type pattern: list or None
:returns: A set object of all field keys used... | if len(pattern) == 2 and pattern[0] not in self._KEY_FILTER_MAP:
if pattern[0] in ('&', '|', '^'):
# Pass each nested pattern to get_field_keys
for filter_item in pattern[1]:
keys = keys.union(self.get_field_keys(filter_item))
else:
... | csn_ccr |
Get the filesystem configuration liaison.
@return Liaison | public function getFileConfig()
{
if (!$this->fileConfig) {
$this->fileConfig = new Liaison($this->app->make('config'), $this->getPackageHandle());
}
return $this->fileConfig;
} | csn |
// NewMockTransactional creates a new mock instance | func NewMockTransactional(ctrl *gomock.Controller) *MockTransactional {
mock := &MockTransactional{ctrl: ctrl}
mock.recorder = &MockTransactionalMockRecorder{mock}
return mock
} | csn |
public function boot(Router $router)
{
if (!$this->app->routesAreCached()) {
$router->group([
| 'namespace' => $this->namespace,
], function (Router $router) {
require __DIR__.'/../routes/web.php';
});
}
} | csn_ccr |
Dispatch a log output message.
@param string $message
@param array $context
@throws LoggingException | private function dispatch($message, $context)
{
$output = $this->interpolate($message, $context) . PHP_EOL;
if ($this->getOption('outputToFile') === true) {
$file = $this->getOption('logFile');
if (!is_writable($file)) {
throw new AsposeCloudException('The f... | csn |
def tupletree(table, start='start', stop='stop', value=None):
"""
Construct an interval tree for the given table, where each node in the tree
is a row of the table.
"""
import intervaltree
tree = intervaltree.IntervalTree()
it = iter(table)
hdr = next(it)
flds = list(map(text_type,... | field not recognised'
assert stop in flds, 'stop field not recognised'
getstart = itemgetter(flds.index(start))
getstop = itemgetter(flds.index(stop))
if value is None:
getvalue = tuple
else:
valueindices = asindices(hdr, value)
assert len(valueindices) > 0, 'invalid value f... | csn_ccr |
def module(command, *args):
"""Run the modulecmd tool and use its Python-formatted output to set the
environment variables."""
if 'MODULESHOME' not in os.environ:
print('payu: warning: No Environment Modules found; skipping {0} call.'
''.format(command))
return
modulecmd ... |
cmd = '{0} python {1} {2}'.format(modulecmd, command, ' '.join(args))
envs, _ = subprocess.Popen(shlex.split(cmd),
stdout=subprocess.PIPE).communicate()
exec(envs) | csn_ccr |
public static WsLogRecord createWsLogRecord(TraceComponent tc, Level level, String msg, Object[] msgParms) {
WsLogRecord retMe = new WsLogRecord(level, msg);
retMe.setLoggerName(tc.getName());
retMe.setParameters(msgParms);
| retMe.setTraceClass(tc.getTraceClass());
retMe.setResourceBundleName(tc.getResourceBundleName());
if (level.intValue() >= Level.INFO.intValue()) {
retMe.setLocalizable(REQUIRES_LOCALIZATION);
}
else {
retMe.setLocalizable(REQUIRES_NO_LOCALIZATION);
... | csn_ccr |
public function handleUpdate(SS_HTTPRequest $request)
{
if (!$this->file->canEdit()) {
return $this->httpError(403);
}
parse_str($request->getBody(), $vars);
if (isset($vars['parentID'])) {
$this->file->ParentID = $vars['parentID'];
$this->file->... | if (isset($vars['filename']) && !empty($vars['filename'])) {
$this->file->Filename = $this->file->Parent()->Filename . '/' . $vars['filename'];
}
$this->file->write();
return $this->jsonResponse($this->buildJSON());
} | csn_ccr |
func ValidateRemoteURL(remote string) error {
u, _ := url.Parse(remote)
if u == nil || u.Scheme == "" {
// This is either an invalid remote name (maybe the user made a typo
// when selecting a named remote) or a bare SSH URL like
// "x@y.com:path/to/resource.git". Guess that this is a URL in the latter
// for... |
return nil
} else {
return fmt.Errorf("Invalid remote name: %q", remote)
}
}
switch u.Scheme {
case "ssh", "http", "https", "git":
return nil
default:
return fmt.Errorf("Invalid remote url protocol %q in %q", u.Scheme, remote)
}
} | csn_ccr |
Add a new page to the web application. Only available after that the Plugin Manager is loaded | def add_page(self, pattern, classname):
""" Add a new page to the web application. Only available after that the Plugin Manager is loaded """
if not self._loaded:
raise PluginManagerNotLoadedException()
self._app.add_mapping(pattern, classname) | csn |
import tensorflow as tf
from IPython import display
from d2l import tensorflow as d2l
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
num_inputs = 784
num_outputs = 10
W = tf.Variable(tf.random.normal(shape=(num_inputs, num_outputs), mean=0, stddev=0.01))
b = tf.Variable(tf.zeros(num_ou... | import warnings
from d2l import paddle as d2l
warnings.filterwarnings("ignore")
import paddle
from IPython import display
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
num_inputs = 784
num_outputs = 10
W = paddle.normal(0, 0.01, shape=(num_inputs, num_outputs))
b = paddle.zeros(shape=... | codetrans_dl |
HTTP Client.
@return \GuzzleHttp\ClientInterface|null | public function getHttpClient()
{
if (!is_null($this->httpClient)) {
return $this->httpClient;
}
return $this->httpClient = new Client([
'base_uri' => $this->storageUrl(),
'headers' => [
'X-Auth-Token' => $this->token(),
],
... | csn |
Your task is to define a function that understands basic mathematical expressions and solves them.
For example:
```python
calculate("1 + 1") # => 2
calculate("18 + 4*6") # => 42
calculate("245 - 826") # => -581
calculate("09 + 000482") # => 491
calculate("8 / 4 + 6") # => 8
calculate("5 + 1 / 5") ... | import re
def calculate(input):
try:
return eval(re.sub(r'(\d+)', lambda m: str(int(m.group(1))), input))
except:
return False | apps |
Sets a configuration value in the array.
@param array $config Configuration sub-part
@param array $path Configuration path parts
@param array $value The new value | protected function _set( $config, $path, $value )
{
if( ( $current = array_shift( $path ) ) !== null )
{
if( isset( $config[$current] ) ) {
$config[$current] = $this->_set( $config[$current], $path, $value );
} else {
$config[$current] = $this->_set( array(), $path, $value );
}
return $config;... | csn |
def _detect(env):
"""
Detect all the command line tools that we might need for creating
the requested output formats.
"""
global prefer_xsltproc
if env.get('DOCBOOK_PREFER_XSLTPROC',''):
prefer_xsltproc = True
if ((not has_libxml2 and not has_lxml) or (prefer_xsltproc))... | XSLT processors
__detect_cl_tool(env, 'DOCBOOK_XSLTPROC', xsltproc_com, xsltproc_com_priority)
__detect_cl_tool(env, 'DOCBOOK_XMLLINT', xmllint_com)
__detect_cl_tool(env, 'DOCBOOK_FOP', fop_com, ['fop','xep','jw']) | csn_ccr |
"Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are the same, ``upload``
deletes the file if ``remove==True`` and retur... | def upload(self, filepath, service_path, remove=False):
'''
"Upload" a file to a service
This copies a file from the local filesystem into the ``DataService``'s
filesystem. If ``remove==True``, the file is moved rather than copied.
If ``filepath`` and ``service_path`` paths are... | csn |
python int cast with default | def safe_int(val, default=None):
"""
Returns int() of val if val is not convertable to int use default
instead
:param val:
:param default:
"""
try:
val = int(val)
except (ValueError, TypeError):
val = default
return val | cosqa |
Adds a child element to this node. | public Long addChildElement(Element childElement, ElementWriter elementWriter) {
synchronized(lock) {
checkNotFrozen();
if(childElements == null) childElements = new ArrayList<>();
childElements.add(childElement);
if(elementWriters == null) elementWriters = new HashMap<>();
IdGenerator idGenerator = id... | csn |
Recursively step through the clusters to build the hulls.
@param clu Current cluster
@param hier Clustering hierarchy
@param hulls Hull map | private DoubleObjPair<Polygon> buildHullsRecursively(Cluster<Model> clu, Hierarchy<Cluster<Model>> hier, Map<Object, DoubleObjPair<Polygon>> hulls, Relation<? extends NumberVector> coords) {
final DBIDs ids = clu.getIDs();
FilteredConvexHull2D hull = new FilteredConvexHull2D();
for(DBIDIter iter = ids.iter... | csn |
protected function getExactTrace($exception)
{
$traces=$exception->getTrace();
foreach($traces as $trace)
{
// property access exception
| if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
return $trace;
}
return null;
} | csn_ccr |
Create the File Writer.
Returns:
FileWriter: An instance of :class:`.writer.BaseFileWriter`. | def _build_file_writer(cls, session: AppSession):
'''Create the File Writer.
Returns:
FileWriter: An instance of :class:`.writer.BaseFileWriter`.
'''
args = session.args
if args.delete_after:
return session.factory.new('FileWriter') # is a NullWriter
... | csn |
async def create_account(self, **params):
"""Describes, validates data.
"""
logging.debug("\n\n[+] -- Create account debugging. ")
model = {
"unique": ["email", "public_key"],
"required": ("public_key",),
"default": {"count":len(settings.AVAILABLE_COIN_ID),
"level":2,
"news_count":0,
"em... | row.update({i:model["default"][i] for i in model["default"]})
if data.get("email"):
row["email"] = data.get("email")
row.update({"id":await self.autoincrement()})
await self.collection.insert_one(row)
account = await self.collection.find_one({"public_key":row["public_key"]})
# Create wallets
for coini... | csn_ccr |
public function events($events=array())
{
if (!isset($this->_events)) {
$this->_events = new Events(array(), self::schema()->events());
$this->_registerDefaultEventHandlers();
}
if(count($events))
| foreach($events as $event=>$callback)
$this->_events->register($event, $callback);
return $this->_events;
} | csn_ccr |
protected function modulo10($number)
{
$next = 0;
for ($i=0; $i < strlen($number); $i++) {
$next = $this->moduloTable[($next + | intval(substr($number, $i, 1))) % 10];
}
return (10 - $next) % 10;
} | csn_ccr |
def image_write(image, filename, ri=False):
"""
Write an ANTsImage to file
ANTsR function: `antsImageWrite`
Arguments
---------
image : ANTsImage
image to save to file
filename : string
name of file to which image will be saved
ri : boolean
if True, return ima... | if False, do not return image
"""
if filename.endswith('.npy'):
img_array = image.numpy()
img_header = {'origin': image.origin,'spacing': image.spacing,
'direction': image.direction.tolist(), 'components': image.components}
np.save(filename, img_array)
... | csn_ccr |
def get(self, transform=None):
"""
Return the JSON defined at the S3 location in the constructor.
The get method will reload the S3 object after the TTL has
expired.
Fetch the JSON object from cache or S3 if necessary
| """
if not self.has_expired() and self._cached_copy is not None:
return self._cached_copy, False
return self._refresh_cache(transform), True | csn_ccr |
Try to interrupt all of the given threads, and join on them.
If interrupted, returns false, indicating some threads may
still be running. | private boolean interruptAndJoinThreads(List<Thread> threads) {
// interrupt and wait for all ongoing create threads
for(Thread t : threads) {
t.interrupt();
}
for(Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
DataNode.LOG.warn("interruptOngoi... | csn |
Compare two DBIDs.
@param id1 First ID
@param id2 Second ID
@return Comparison result | public static int compare(DBIDRef id1, DBIDRef id2) {
return DBIDFactory.FACTORY.compare(id1, id2);
} | csn |
// NewFileSink creates a new file sink with the given configuration | func NewFileSink(conf *sink.SinkConfig) (sink.Sink, error) {
if conf.Logger == nil {
return nil, errors.New("nil logger provided")
}
conf.Logger.Info("creating file sink")
f := &fileSink{
logger: conf.Logger,
}
pathRaw, ok := conf.Config["path"]
if !ok {
return nil, errors.New("'path' not specified for ... | csn |
Parses a directory and searches for options.module subdir. If found subdir is searched for required files
@param options
@param iterationInfo
@returns {{}} | function (options, iterationInfo) {
var files;
var modules = {};
var result = {};
// remember the starting directory
try {
files = fs.readdirSync(iterationInfo.dirName);
} catch (e) {
if (options.optional)
return {};
el... | csn |
Creates \Google\Protobuf\SourceCodeInfo object from serialized Protocol Buffers message.
@param string $input
@param SourceCodeInfo $object
@param int $start
@param int $end
@throws \Exception
@return SourceCodeInfo | public static function fromProtobuf($input, $object = NULL, &$start = 0, $end = NULL)
{
if ($object === null) {
$object = new SourceCodeInfo();
}
if ($end === null) {
$end = strlen($input);
}
while ($start < $end) {
$tag = Binary::decodeVarint($input, $start);
$wireType = $tag & 0x7;
$number... | csn |
Sanitizes title, replacing whitespace with dashes.
Limits the output to alphanumeric characters, underscore (_) and dash (-).
Whitespace becomes a dash.
@param string $title The title to be sanitized.
@return string The sanitized title. | public static function slugify($title, $length = 200) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);... | csn |
Returns an estimate of the number of active threads in this thread
group and its subgroups. Recursively iterates over all subgroups in
this thread group.
<p> The value returned is only an estimate because the number of
threads may change dynamically while this method traverses internal
data structures, and might be af... | public int activeCount() {
int result;
// Snapshot sub-group data so we don't hold this lock
// while our children are computing.
int ngroupsSnapshot;
ThreadGroup[] groupsSnapshot;
synchronized (this) {
if (destroyed) {
return 0;
}
... | csn |
// Log entry for req similar to Apache Common Log Format.
// ts is the timestamp with which the entry should be logged.
// status, size are used to provide the response HTTP status and size. | 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... | csn |
func (sm *storeManager) leave(w *Multiwatcher) {
for e := sm.all.list.Front(); e != nil; {
next := e.Next()
entry := e.Value.(*entityEntry)
if entry.creationRevno <= w.revno {
// The watcher has seen | this entry.
if entry.removed && entry.revno <= w.revno {
// The entity has been removed and the
// watcher has already been informed of that,
// so its refcount has already been decremented.
e = next
continue
}
sm.all.decRef(entry)
}
e = next
}
} | csn_ccr |
The default event handler fired when the user mouses over the
context element.
@method onContextMouseOver
@param {DOMEvent} e The current DOM event
@param {Object} obj The object argument | function (e, obj) {
var context = this;
if (context.title) {
obj._tempTitle = context.title;
context.title = "";
}
// Fire first, to honor disabled set in the listner
if (obj.fireEvent("contextMouseOver", context, e) !== false... | csn |
public static boolean isAlphaNumericOrContainsOnlyCharacters(String in, String chars) {
char c = 0;
for (int i = 0; i < in.length(); i++) {
c = in.charAt(i);
if | (Character.isLetterOrDigit(c) == (chars.indexOf(c) != -1)) {
return false;
}
}
return true;
} | csn_ccr |
Applies the contents of two or more objects together into the first object.
@param {object} target - The target object in which all objects are merged into.
@param {object} arg1 - Object containing additional properties to merge in target.
@param {object} argN - Additional objects containing properties to merge in targ... | function(target) {
var setFn = function(value, key) {
target[key] = value;
};
for (var i = 1, ilen = arguments.length; i < ilen; ++i) {
helpers.each(arguments[i], setFn);
}
return target;
} | csn |
Get the default parameter values for this annotation, if this is an annotation class.
@return A list of {@link AnnotationParameterValue} objects for each of the default parameter values for this
annotation, if this is an annotation class with default parameter values, otherwise the empty list. | public AnnotationParameterValueList getAnnotationDefaultParameterValues() {
if (!scanResult.scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableAnnotationInfo() before #scan()");
}
if (!isAnnotation) {
throw new IllegalArgumen... | csn |
Sets the color scheme to use when printing help.
@param colorScheme the new color scheme
@see #execute(String...)
@see #usage(PrintStream)
@see #usage(PrintWriter)
@see #getUsageMessage()
@since 4.0 | public CommandLine setColorScheme(Help.ColorScheme colorScheme) {
this.colorScheme = Assert.notNull(colorScheme, "colorScheme");
for (CommandLine sub : getSubcommands().values()) { sub.setColorScheme(colorScheme); }
return this;
} | csn |
public static function semanticalErrorConstants($identifier, $context = null)
{
return self::semanticalError(sprintf(
"Couldn't find constant %s%s.",
| $identifier,
$context ? ', ' . $context : ''
));
} | csn_ccr |
Returns the target path as relative reference from the base path.
Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
Both paths must be absolute and not contain relative parts.
Relative URLs from one resource to another are useful when generating self-contained do... | public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && ... | csn |
def is_error_transition_for?(event_name, error)
| is_same_event?(event_name) && from.is_a?(Class) && error.is_a?(from)
end | csn_ccr |
def get_computation(self,
message: Message,
transaction_context: 'BaseTransactionContext') -> 'BaseComputation':
"""
Return a computation instance for the given `message` and `transaction_context`
"""
if self.computation_class is None:
... | raise AttributeError("No `computation_class` has been set for this State")
else:
computation = self.computation_class(self, message, transaction_context)
return computation | csn_ccr |
Pretty prints a task list of rebalancing tasks.
@param infos list of rebalancing tasks (RebalancePartitionsInfo)
@return pretty-printed string | public static String taskListToString(List<RebalanceTaskInfo> infos) {
StringBuffer sb = new StringBuffer();
for (RebalanceTaskInfo info : infos) {
sb.append("\t").append(info.getDonorId()).append(" -> ").append(info.getStealerId()).append(" : [");
for (String storeName : info.ge... | csn |
Aborts the current cache generation process.
Does so by rolling back the current transaction, which should be the
.generating file lock | public function abortCacheGeneration()
{
eZDebugSetting::writeDebug( 'kernel-clustering', 'Aborting cache generation', "dfs::abortCacheGeneration( '{$this->filePath}' )" );
self::$dbbackend->_abortCacheGeneration( $this->filePath );
$this->filePath = $this->realFilePath;
$this->realF... | csn |
Return true if an object and is empty
@param obj
@returns {boolean} | function isEmptyObject(obj) {
if (obj === null) {
return true;
}
if (!isObject(obj)) {
return false;
}
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
return false;
}
}
return true;
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.