id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
13,529
def isRat(x): return isinstance(x, Rat)
[ "def", "isRat", "(", "x", ")", ":", "return", "isinstance", "(", "x", ",", "Rat", ")" ]
test wheter an object is an instance of the rat class .
train
false
13,531
@register.function @jinja2.contextfunction def hub_breadcrumbs(context, addon=None, items=None, add_default=False): crumbs = [(reverse('ecosystem.landing'), _('Developers'))] title = _('My Submissions') link = reverse('mkt.developers.apps') if addon: if ((not addon) and (not items)): crumbs.append((None, title)) else: crumbs.append((link, title)) if items: url = addon.get_dev_url() else: url = None crumbs.append((url, addon.name)) if items: crumbs.extend(items) if (len(crumbs) == 1): crumbs = [] return mkt_breadcrumbs(context, items=crumbs)
[ "@", "register", ".", "function", "@", "jinja2", ".", "contextfunction", "def", "hub_breadcrumbs", "(", "context", ",", "addon", "=", "None", ",", "items", "=", "None", ",", "add_default", "=", "False", ")", ":", "crumbs", "=", "[", "(", "reverse", "(", ...
wrapper function for breadcrumbs .
train
false
13,532
def readWriteDeleteHypertextHelp(documentDirectoryPath, hypertextFileIndex, hypertextFiles, transferredFileNames): fileName = os.path.basename(hypertextFiles[hypertextFileIndex]) print ('readWriteDeleteHypertextHelp ' + fileName) filePath = os.path.join(documentDirectoryPath, fileName) fileText = archive.getFileText(fileName) fileText = getWrappedHypertext(fileText, hypertextFileIndex, hypertextFiles) if (fileText.find('This page is in the table of contents.') > (-1)): fileText = fileText.replace('This page is in the table of contents.', '') transferredFileNames.append(fileName) archive.writeFileText(filePath, fileText) os.remove(fileName)
[ "def", "readWriteDeleteHypertextHelp", "(", "documentDirectoryPath", ",", "hypertextFileIndex", ",", "hypertextFiles", ",", "transferredFileNames", ")", ":", "fileName", "=", "os", ".", "path", ".", "basename", "(", "hypertextFiles", "[", "hypertextFileIndex", "]", ")...
read the pydoc hypertext help documents .
train
false
13,534
def _a_encode_none(value, mapping): return ['0n']
[ "def", "_a_encode_none", "(", "value", ",", "mapping", ")", ":", "return", "[", "'0n'", "]" ]
none --> [0 .
train
false
13,535
def get_cxxflags(): return get_var('CXXFLAGS')
[ "def", "get_cxxflags", "(", ")", ":", "return", "get_var", "(", "'CXXFLAGS'", ")" ]
get the value of cxxflags variable in the make .
train
false
13,536
def getPointsFromLoop(loop, radius, thresholdRatio=0.9): radius = abs(radius) points = [] for pointIndex in xrange(len(loop)): pointBegin = loop[pointIndex] pointEnd = loop[((pointIndex + 1) % len(loop))] points.append(pointBegin) addPointsFromSegment(pointBegin, pointEnd, points, radius, thresholdRatio) return points
[ "def", "getPointsFromLoop", "(", "loop", ",", "radius", ",", "thresholdRatio", "=", "0.9", ")", ":", "radius", "=", "abs", "(", "radius", ")", "points", "=", "[", "]", "for", "pointIndex", "in", "xrange", "(", "len", "(", "loop", ")", ")", ":", "poin...
get the points from every point on a loop and between points .
train
false
13,540
def extract_variables(log_format): if (log_format == 'combined'): log_format = LOG_FORMAT_COMBINED for match in re.findall(REGEX_LOG_FORMAT_VARIABLE, log_format): (yield match)
[ "def", "extract_variables", "(", "log_format", ")", ":", "if", "(", "log_format", "==", "'combined'", ")", ":", "log_format", "=", "LOG_FORMAT_COMBINED", "for", "match", "in", "re", ".", "findall", "(", "REGEX_LOG_FORMAT_VARIABLE", ",", "log_format", ")", ":", ...
extract all variables from a log format string .
train
true
13,541
def handleEventException(source, event, args, kw, exc_info): try: c = source t = event if hasattr(c, '__class__'): c = c.__class__.__name__ if isinstance(t, Event): t = t.__class__.__name__ elif issubclass(t, Event): t = t.__name__ except: pass import sys sys.stderr.write(('Exception while handling %s!%s...\n' % (c, t))) import traceback traceback.print_exception(*exc_info)
[ "def", "handleEventException", "(", "source", ",", "event", ",", "args", ",", "kw", ",", "exc_info", ")", ":", "try", ":", "c", "=", "source", "t", "=", "event", "if", "hasattr", "(", "c", ",", "'__class__'", ")", ":", "c", "=", "c", ".", "__class_...
called when an exception is raised by an event handler when the event was raised by raiseeventnoerrors() .
train
false
13,542
def _do_mb_query(entity, id, includes=[], params={}): if (not isinstance(includes, list)): includes = [includes] _check_includes(entity, includes) auth_required = _get_auth_type(entity, id, includes) args = dict(params) if (len(includes) > 0): inc = ' '.join(includes) args['inc'] = inc path = ('%s/%s' % (entity, id)) return _mb_request(path, 'GET', auth_required, args=args)
[ "def", "_do_mb_query", "(", "entity", ",", "id", ",", "includes", "=", "[", "]", ",", "params", "=", "{", "}", ")", ":", "if", "(", "not", "isinstance", "(", "includes", ",", "list", ")", ")", ":", "includes", "=", "[", "includes", "]", "_check_inc...
make a single get call to the musicbrainz xml api .
train
false
13,543
def new_create_tag(name=u'', ref=u'', sign=False, settings=None, parent=None): opts = TagOptions(name, ref, sign) view = CreateTag(opts, settings=settings, parent=parent) return view
[ "def", "new_create_tag", "(", "name", "=", "u''", ",", "ref", "=", "u''", ",", "sign", "=", "False", ",", "settings", "=", "None", ",", "parent", "=", "None", ")", ":", "opts", "=", "TagOptions", "(", "name", ",", "ref", ",", "sign", ")", "view", ...
entry point for external callers .
train
false
13,544
def prints(*args, **kwargs): file = kwargs.get('file', sys.stdout) sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') enc = preferred_encoding safe_encode = kwargs.get('safe_encode', False) if ('CALIBRE_WORKER' in os.environ): enc = 'utf-8' for (i, arg) in enumerate(args): if isinstance(arg, unicode): try: arg = arg.encode(enc) except UnicodeEncodeError: try: arg = arg.encode('utf-8') except: if (not safe_encode): raise arg = repr(arg) if (not isinstance(arg, str)): try: arg = str(arg) except ValueError: arg = unicode(arg) if isinstance(arg, unicode): try: arg = arg.encode(enc) except UnicodeEncodeError: try: arg = arg.encode('utf-8') except: if (not safe_encode): raise arg = repr(arg) try: file.write(arg) except: import repr as reprlib file.write(reprlib.repr(arg)) if (i != (len(args) - 1)): file.write(bytes(sep)) file.write(bytes(end))
[ "def", "prints", "(", "*", "args", ",", "**", "kwargs", ")", ":", "file", "=", "kwargs", ".", "get", "(", "'file'", ",", "sys", ".", "stdout", ")", "sep", "=", "kwargs", ".", "get", "(", "'sep'", ",", "' '", ")", "end", "=", "kwargs", ".", "get...
print unicode arguments safely by encoding them to preferred_encoding has the same signature as the print function from python 3 .
train
false
13,545
def print_title(text): print_col('==================== {} ===================='.format(text), 'yellow')
[ "def", "print_title", "(", "text", ")", ":", "print_col", "(", "'==================== {} ===================='", ".", "format", "(", "text", ")", ",", "'yellow'", ")" ]
print a title .
train
false
13,546
def channel_data_files(dest=None): channel_data_filename = 'channel_data.json' if dest: if (not channel_data_path): sourcedir = os.path.dirname(path) sourcefile = ((os.path.basename(path) + '.json') if os.path.exists((os.path.basename(path) + '.json')) else channel_data_filename) else: sourcedir = channel_data_path sourcefile = channel_data_filename shutil.copy(os.path.join(sourcedir, sourcefile), os.path.join(dest, channel_data_filename)) shutil.rmtree(os.path.join(dest, 'images'), ignore_errors=True) shutil.copytree(os.path.join(sourcedir, 'images'), os.path.join(dest, 'images'))
[ "def", "channel_data_files", "(", "dest", "=", "None", ")", ":", "channel_data_filename", "=", "'channel_data.json'", "if", "dest", ":", "if", "(", "not", "channel_data_path", ")", ":", "sourcedir", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", ...
copies all remaining files to appropriate channel data directory .
train
false
13,547
def session_view(request): request.session['tobacconist'] = 'hovercraft' t = Template('This is a view that modifies the session.', name='Session Modifying View Template') c = Context() return HttpResponse(t.render(c))
[ "def", "session_view", "(", "request", ")", ":", "request", ".", "session", "[", "'tobacconist'", "]", "=", "'hovercraft'", "t", "=", "Template", "(", "'This is a view that modifies the session.'", ",", "name", "=", "'Session Modifying View Template'", ")", "c", "="...
a view that modifies the session .
train
false
13,548
def get_job_output(job_id): return job_models.JobModel.get_by_id(job_id).output
[ "def", "get_job_output", "(", "job_id", ")", ":", "return", "job_models", ".", "JobModel", ".", "get_by_id", "(", "job_id", ")", ".", "output" ]
returns the output of a job .
train
false
13,549
def nearlyEqual(lst1, lst2, tolerance=0.001): return all(((abs((i - j)) <= tolerance) for (i, j) in zip(lst1, lst2)))
[ "def", "nearlyEqual", "(", "lst1", ",", "lst2", ",", "tolerance", "=", "0.001", ")", ":", "return", "all", "(", "(", "(", "abs", "(", "(", "i", "-", "j", ")", ")", "<=", "tolerance", ")", "for", "(", "i", ",", "j", ")", "in", "zip", "(", "lst...
tell whether the itemwise differences of the two lists is never bigger than tolerance .
train
false
13,550
def get_latest_versions(versions, num=1): versions = group_versions(versions) return [versions[index][0] for index in range(num)]
[ "def", "get_latest_versions", "(", "versions", ",", "num", "=", "1", ")", ":", "versions", "=", "group_versions", "(", "versions", ")", "return", "[", "versions", "[", "index", "]", "[", "0", "]", "for", "index", "in", "range", "(", "num", ")", "]" ]
return a list of the most recent versions for each major .
train
false
13,551
def are_content_experiments_enabled(course): return (('split_test' in ADVANCED_COMPONENT_TYPES) and ('split_test' in course.advanced_modules))
[ "def", "are_content_experiments_enabled", "(", "course", ")", ":", "return", "(", "(", "'split_test'", "in", "ADVANCED_COMPONENT_TYPES", ")", "and", "(", "'split_test'", "in", "course", ".", "advanced_modules", ")", ")" ]
returns true if content experiments have been enabled for the course .
train
false
13,553
def beta_from_features(dataset, **kwargs): return beta_from_design(dataset.X, **kwargs)
[ "def", "beta_from_features", "(", "dataset", ",", "**", "kwargs", ")", ":", "return", "beta_from_design", "(", "dataset", ".", "X", ",", "**", "kwargs", ")" ]
returns the marginal precision of the features in a dataset .
train
false
13,554
def basic_clean_up_f(f): deletion_list = [l.strip() for l in f] remove_all(deletion_list) return True
[ "def", "basic_clean_up_f", "(", "f", ")", ":", "deletion_list", "=", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "f", "]", "remove_all", "(", "deletion_list", ")", "return", "True" ]
removes list of files in f f: file containing list of filepaths example f: f1 .
train
false
13,555
def generate_open_shard_key(): open_shards = get_open_shards() shard_id = random.choice(open_shards) key = (shard_id << 48) return key
[ "def", "generate_open_shard_key", "(", ")", ":", "open_shards", "=", "get_open_shards", "(", ")", "shard_id", "=", "random", ".", "choice", "(", "open_shards", ")", "key", "=", "(", "shard_id", "<<", "48", ")", "return", "key" ]
return the key that can be passed into session_scope() for an open shard .
train
false
13,556
def GetCurrentTimestamp(): return (_TEST_TIME if (_TEST_TIME is not None) else time.time())
[ "def", "GetCurrentTimestamp", "(", ")", ":", "return", "(", "_TEST_TIME", "if", "(", "_TEST_TIME", "is", "not", "None", ")", "else", "time", ".", "time", "(", ")", ")" ]
if _test_time has been set .
train
false
13,557
@command('fileset', optional=['filename']) def fileset_command(options, input_filename=None): with open_input_file(input_filename) as input_file: descriptor_content = input_file.read() dest_dir = os.path.expanduser(options.dest_dir) if ((not os.path.isdir(dest_dir)) and os.path.exists(dest_dir)): fatal_error(("Destination '%s' is not a directory" % dest_dir)) file_set = protobuf.decode_message(descriptor.FileSet, descriptor_content) for file_descriptor in file_set.files: generate_file_descriptor(dest_dir, file_descriptor=file_descriptor, force_overwrite=options.force)
[ "@", "command", "(", "'fileset'", ",", "optional", "=", "[", "'filename'", "]", ")", "def", "fileset_command", "(", "options", ",", "input_filename", "=", "None", ")", ":", "with", "open_input_file", "(", "input_filename", ")", "as", "input_file", ":", "desc...
generate source directory structure from fileset .
train
false
13,558
def random_urlsafe_str(): return base64.urlsafe_b64encode(uuid.uuid4().bytes)[:(-2)].decode('utf-8')
[ "def", "random_urlsafe_str", "(", ")", ":", "return", "base64", ".", "urlsafe_b64encode", "(", "uuid", ".", "uuid4", "(", ")", ".", "bytes", ")", "[", ":", "(", "-", "2", ")", "]", ".", "decode", "(", "'utf-8'", ")" ]
generate a random url-safe string .
train
false
13,559
def test_Trapezoid1D(): model = models.Trapezoid1D(amplitude=4.2, x_0=2.0, width=1.0, slope=3) xx = np.linspace(0, 4, 8) yy = model(xx) yy_ref = [0.0, 1.41428571, 3.12857143, 4.2, 4.2, 3.12857143, 1.41428571, 0.0] assert_allclose(yy, yy_ref, rtol=0, atol=1e-06)
[ "def", "test_Trapezoid1D", "(", ")", ":", "model", "=", "models", ".", "Trapezoid1D", "(", "amplitude", "=", "4.2", ",", "x_0", "=", "2.0", ",", "width", "=", "1.0", ",", "slope", "=", "3", ")", "xx", "=", "np", ".", "linspace", "(", "0", ",", "4...
regression test for URL .
train
false
13,560
def handle_shared_float32(tf): if tf: theano.compile.shared_constructor(float32_shared_constructor) else: theano.compile.shared_constructor(float32_shared_constructor, True) assert (float32_shared_constructor not in theano.compile.shared.constructors)
[ "def", "handle_shared_float32", "(", "tf", ")", ":", "if", "tf", ":", "theano", ".", "compile", ".", "shared_constructor", "(", "float32_shared_constructor", ")", "else", ":", "theano", ".", "compile", ".", "shared_constructor", "(", "float32_shared_constructor", ...
set the default shared type for float32 tensor to cudandarraytype .
train
false
13,561
def _acquire_subtask_lock(task_id): key = 'subtask-{}'.format(task_id) succeeded = cache.add(key, 'true', SUBTASK_LOCK_EXPIRE) if (not succeeded): TASK_LOG.warning("task_id '%s': already locked. Contains value '%s'", task_id, cache.get(key)) return succeeded
[ "def", "_acquire_subtask_lock", "(", "task_id", ")", ":", "key", "=", "'subtask-{}'", ".", "format", "(", "task_id", ")", "succeeded", "=", "cache", ".", "add", "(", "key", ",", "'true'", ",", "SUBTASK_LOCK_EXPIRE", ")", "if", "(", "not", "succeeded", ")",...
mark the specified task_id as being in progress .
train
false
13,562
def http_log_req(method, uri, args, kwargs): if (not pyrax.get_http_debug()): return string_parts = [('curl -i -X %s' % method)] for element in args: string_parts.append(('%s' % element)) for element in kwargs['headers']: header = ("-H '%s: %s'" % (element, kwargs['headers'][element])) string_parts.append(header) string_parts.append(uri) log = logging.getLogger('pyrax') log.debug(('\nREQ: %s\n' % ' '.join(string_parts))) if ('body' in kwargs): pyrax._logger.debug(('REQ BODY: %s\n' % kwargs['body'])) if ('data' in kwargs): pyrax._logger.debug(('REQ DATA: %s\n' % kwargs['data']))
[ "def", "http_log_req", "(", "method", ",", "uri", ",", "args", ",", "kwargs", ")", ":", "if", "(", "not", "pyrax", ".", "get_http_debug", "(", ")", ")", ":", "return", "string_parts", "=", "[", "(", "'curl -i -X %s'", "%", "method", ")", "]", "for", ...
when pyrax .
train
true
13,563
def dmp_zz_wang_test_points(f, T, ct, A, u, K): if (not dmp_eval_tail(dmp_LC(f, K), A, (u - 1), K)): raise EvaluationFailed('no luck') g = dmp_eval_tail(f, A, u, K) if (not dup_sqf_p(g, K)): raise EvaluationFailed('no luck') (c, h) = dup_primitive(g, K) if K.is_negative(dup_LC(h, K)): (c, h) = ((- c), dup_neg(h, K)) v = (u - 1) E = [dmp_eval_tail(t, A, v, K) for (t, _) in T] D = dmp_zz_wang_non_divisors(E, c, ct, K) if (D is not None): return (c, h, E) else: raise EvaluationFailed('no luck')
[ "def", "dmp_zz_wang_test_points", "(", "f", ",", "T", ",", "ct", ",", "A", ",", "u", ",", "K", ")", ":", "if", "(", "not", "dmp_eval_tail", "(", "dmp_LC", "(", "f", ",", "K", ")", ",", "A", ",", "(", "u", "-", "1", ")", ",", "K", ")", ")", ...
wang/eez: test evaluation points for suitability .
train
false
13,564
def filter_formatdate(val, format): encoding = locale.getpreferredencoding() if (not isinstance(val, (datetime, date, time))): return val return native_str_to_text(val.strftime(text_to_native_str(format, encoding=encoding)), encoding=encoding)
[ "def", "filter_formatdate", "(", "val", ",", "format", ")", ":", "encoding", "=", "locale", ".", "getpreferredencoding", "(", ")", "if", "(", "not", "isinstance", "(", "val", ",", "(", "datetime", ",", "date", ",", "time", ")", ")", ")", ":", "return",...
returns a string representation of a datetime object according to format string .
train
false
13,565
def get_monitor_doc(var): doc = None if (var.__doc__ is not var.__class__.__doc__): doc = var.__doc__ return doc
[ "def", "get_monitor_doc", "(", "var", ")", ":", "doc", "=", "None", "if", "(", "var", ".", "__doc__", "is", "not", "var", ".", "__class__", ".", "__doc__", ")", ":", "doc", "=", "var", ".", "__doc__", "return", "doc" ]
returns the __doc__ field of var or none .
train
false
13,566
@public def xring(symbols, domain, order=lex): _ring = PolyRing(symbols, domain, order) return (_ring, _ring.gens)
[ "@", "public", "def", "xring", "(", "symbols", ",", "domain", ",", "order", "=", "lex", ")", ":", "_ring", "=", "PolyRing", "(", "symbols", ",", "domain", ",", "order", ")", "return", "(", "_ring", ",", "_ring", ".", "gens", ")" ]
construct a polynomial ring returning (ring .
train
false
13,567
def _get_branch_opts(branch, local_branch, all_local_branches, desired_upstream, git_ver=None): if ((branch is not None) and (branch not in all_local_branches)): return None if (git_ver is None): git_ver = _LooseVersion(__salt__['git.version'](versioninfo=False)) ret = [] if (git_ver >= _LooseVersion('1.8.0')): ret.extend(['--set-upstream-to', desired_upstream]) else: ret.append('--set-upstream') ret.append((local_branch if (branch is None) else branch)) ret.append(desired_upstream) return ret
[ "def", "_get_branch_opts", "(", "branch", ",", "local_branch", ",", "all_local_branches", ",", "desired_upstream", ",", "git_ver", "=", "None", ")", ":", "if", "(", "(", "branch", "is", "not", "None", ")", "and", "(", "branch", "not", "in", "all_local_branch...
dry helper to build list of opts for git .
train
true
13,569
@pytest.fixture(scope=u'session') def celery_session_worker(request, celery_session_app, celery_includes, celery_worker_pool, celery_worker_parameters): if (not NO_WORKER): for module in celery_includes: celery_session_app.loader.import_task_module(module) with worker.start_worker(celery_session_app, pool=celery_worker_pool, **celery_worker_parameters) as w: (yield w)
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "u'session'", ")", "def", "celery_session_worker", "(", "request", ",", "celery_session_app", ",", "celery_includes", ",", "celery_worker_pool", ",", "celery_worker_parameters", ")", ":", "if", "(", "not", "NO_WORK...
session fixture: start worker that lives throughout test suite .
train
false
13,571
@register.inclusion_tag(u'includes/editable_loader.html', takes_context=True) def editable_loader(context): user = context[u'request'].user template_vars = {u'has_site_permission': has_site_permission(user), u'request': context[u'request']} if (settings.INLINE_EDITING_ENABLED and template_vars[u'has_site_permission']): t = get_template(u'includes/editable_toolbar.html') template_vars[u'REDIRECT_FIELD_NAME'] = REDIRECT_FIELD_NAME template_vars[u'editable_obj'] = context.get(u'editable_obj', context.get(u'page', None)) template_vars[u'accounts_logout_url'] = context.get(u'accounts_logout_url', None) template_vars[u'toolbar'] = t.render(Context(template_vars)) template_vars[u'richtext_media'] = RichTextField().formfield().widget.media return template_vars
[ "@", "register", ".", "inclusion_tag", "(", "u'includes/editable_loader.html'", ",", "takes_context", "=", "True", ")", "def", "editable_loader", "(", "context", ")", ":", "user", "=", "context", "[", "u'request'", "]", ".", "user", "template_vars", "=", "{", ...
set up the required js/css for the in-line editing toolbar and controls .
train
false
13,572
def CorrelatedGenerator(rho): x = random.gauss(0, 1) (yield x) sigma = math.sqrt((1 - (rho ** 2))) while True: x = random.gauss((x * rho), sigma) (yield x)
[ "def", "CorrelatedGenerator", "(", "rho", ")", ":", "x", "=", "random", ".", "gauss", "(", "0", ",", "1", ")", "(", "yield", "x", ")", "sigma", "=", "math", ".", "sqrt", "(", "(", "1", "-", "(", "rho", "**", "2", ")", ")", ")", "while", "True...
generates standard normal variates with serial correlation .
train
false
13,573
def replace_patterns(x, replace): for (from_, to) in iteritems(replace): x = x.replace(str(from_), str(to)) return x
[ "def", "replace_patterns", "(", "x", ",", "replace", ")", ":", "for", "(", "from_", ",", "to", ")", "in", "iteritems", "(", "replace", ")", ":", "x", "=", "x", ".", "replace", "(", "str", "(", "from_", ")", ",", "str", "(", "to", ")", ")", "ret...
replace replace in string x .
train
false
13,574
def expm_frechet_block_enlarge(A, E): n = A.shape[0] M = np.vstack([np.hstack([A, E]), np.hstack([np.zeros_like(A), A])]) expm_M = scipy.linalg.expm(M) return (expm_M[:n, :n], expm_M[:n, n:])
[ "def", "expm_frechet_block_enlarge", "(", "A", ",", "E", ")", ":", "n", "=", "A", ".", "shape", "[", "0", "]", "M", "=", "np", ".", "vstack", "(", "[", "np", ".", "hstack", "(", "[", "A", ",", "E", "]", ")", ",", "np", ".", "hstack", "(", "...
this is a helper function .
train
false
13,575
def test_solve_fixed_trajectory(): (t0, k0) = (0, np.array([5.0])) results = _compute_fixed_length_solns(model, t0, k0) for (integrator, numeric_solution) in results.items(): ti = numeric_solution[:, 0] analytic_solution = solow_analytic_solution(ti, k0, *valid_params) np.testing.assert_allclose(numeric_solution, analytic_solution)
[ "def", "test_solve_fixed_trajectory", "(", ")", ":", "(", "t0", ",", "k0", ")", "=", "(", "0", ",", "np", ".", "array", "(", "[", "5.0", "]", ")", ")", "results", "=", "_compute_fixed_length_solns", "(", "model", ",", "t0", ",", "k0", ")", "for", "...
testing computation of fixed length solution trajectory .
train
false
13,576
def parse_ansi(string, strip_ansi=False, parser=ANSI_PARSER, xterm256=False, mxp=False): return parser.parse_ansi(string, strip_ansi=strip_ansi, xterm256=xterm256, mxp=mxp)
[ "def", "parse_ansi", "(", "string", ",", "strip_ansi", "=", "False", ",", "parser", "=", "ANSI_PARSER", ",", "xterm256", "=", "False", ",", "mxp", "=", "False", ")", ":", "return", "parser", ".", "parse_ansi", "(", "string", ",", "strip_ansi", "=", "stri...
parses a string .
train
false
13,579
def validate_badge_image(image): if (image.width != image.height): raise ValidationError(_(u'The badge image must be square.')) if (not (image.size < (250 * 1024))): raise ValidationError(_(u'The badge image file size must be less than 250KB.'))
[ "def", "validate_badge_image", "(", "image", ")", ":", "if", "(", "image", ".", "width", "!=", "image", ".", "height", ")", ":", "raise", "ValidationError", "(", "_", "(", "u'The badge image must be square.'", ")", ")", "if", "(", "not", "(", "image", ".",...
validates that a particular image is small enough to be a badge and square .
train
false
13,580
def max_score(scores): lst = sorted_score(scores) max_score = lst[0][1] return [(i[0], i[1]) for i in lst if (i[1] == max_score)]
[ "def", "max_score", "(", "scores", ")", ":", "lst", "=", "sorted_score", "(", "scores", ")", "max_score", "=", "lst", "[", "0", "]", "[", "1", "]", "return", "[", "(", "i", "[", "0", "]", ",", "i", "[", "1", "]", ")", "for", "i", "in", "lst",...
the max scroe and the persons name .
train
false
13,581
def p_jump_statement_1(t): pass
[ "def", "p_jump_statement_1", "(", "t", ")", ":", "pass" ]
jump_statement : goto id semi .
train
false
13,582
def _crawl(expr, func, *args, **kwargs): val = func(expr, *args, **kwargs) if (val is not None): return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args)
[ "def", "_crawl", "(", "expr", ",", "func", ",", "*", "args", ",", "**", "kwargs", ")", ":", "val", "=", "func", "(", "expr", ",", "*", "args", ",", "**", "kwargs", ")", "if", "(", "val", "is", "not", "None", ")", ":", "return", "val", "new_args...
crawl the expression tree .
train
false
13,584
def get_lang_dict(fortype, name=None): from frappe.translate import get_dict return get_dict(fortype, name)
[ "def", "get_lang_dict", "(", "fortype", ",", "name", "=", "None", ")", ":", "from", "frappe", ".", "translate", "import", "get_dict", "return", "get_dict", "(", "fortype", ",", "name", ")" ]
returns all languages in dict format .
train
false
13,586
def test_label_problems_at_runtime(): @_preprocess_data(label_namer='z') def func(*args, **kwargs): pass with pytest.warns(RuntimeWarning): func(None, x='a', y='b') def real_func(x, y): pass @_preprocess_data(label_namer='x') def func(*args, **kwargs): real_func(**kwargs) with pytest.raises(TypeError): func(None, x='a', y='b')
[ "def", "test_label_problems_at_runtime", "(", ")", ":", "@", "_preprocess_data", "(", "label_namer", "=", "'z'", ")", "def", "func", "(", "*", "args", ",", "**", "kwargs", ")", ":", "pass", "with", "pytest", ".", "warns", "(", "RuntimeWarning", ")", ":", ...
tests for behaviour which would actually be nice to get rid of .
train
false
13,587
def course_ids_between(start_word, end_word): valid_courses = [] for course in modulestore().get_courses(): course_id = course.id.to_deprecated_string() if (start_word.lower() <= course_id.lower() <= end_word.lower()): valid_courses.append(course.id) return valid_courses
[ "def", "course_ids_between", "(", "start_word", ",", "end_word", ")", ":", "valid_courses", "=", "[", "]", "for", "course", "in", "modulestore", "(", ")", ".", "get_courses", "(", ")", ":", "course_id", "=", "course", ".", "id", ".", "to_deprecated_string", ...
returns a list of all valid course_ids that fall alphabetically between start_word and end_word .
train
false
13,588
def formatnumber(n): parts = list(str(n)) for i in range((len(parts) - 3), 0, (-3)): parts.insert(i, ',') return ''.join(parts)
[ "def", "formatnumber", "(", "n", ")", ":", "parts", "=", "list", "(", "str", "(", "n", ")", ")", "for", "i", "in", "range", "(", "(", "len", "(", "parts", ")", "-", "3", ")", ",", "0", ",", "(", "-", "3", ")", ")", ":", "parts", ".", "ins...
format a number with beautiful commas .
train
false
13,589
def corpus2dense(corpus, num_terms, num_docs=None, dtype=np.float32): if (num_docs is not None): (docno, result) = ((-1), np.empty((num_terms, num_docs), dtype=dtype)) for (docno, doc) in enumerate(corpus): result[:, docno] = sparse2full(doc, num_terms) assert ((docno + 1) == num_docs) else: result = np.column_stack((sparse2full(doc, num_terms) for doc in corpus)) return result.astype(dtype)
[ "def", "corpus2dense", "(", "corpus", ",", "num_terms", ",", "num_docs", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "if", "(", "num_docs", "is", "not", "None", ")", ":", "(", "docno", ",", "result", ")", "=", "(", "(", "-", "...
convert corpus into a dense np array .
train
false
13,590
def make_global_ns(name): if is_private(name): raise ValueError(('cannot turn [%s] into a global name' % name)) if (not is_global(name)): name = (SEP + name) if (name[(-1)] != SEP): name = (name + SEP) return name
[ "def", "make_global_ns", "(", "name", ")", ":", "if", "is_private", "(", "name", ")", ":", "raise", "ValueError", "(", "(", "'cannot turn [%s] into a global name'", "%", "name", ")", ")", "if", "(", "not", "is_global", "(", "name", ")", ")", ":", "name", ...
convert name to a global name with a trailing namespace separator .
train
false
13,591
def get_targets(): logs = NodeLog.find((((((((((Q('action', 'eq', 'registration_initiated') | Q('action', 'eq', 'registration_approved')) | Q('action', 'eq', 'registration_cancelled')) | Q('action', 'eq', 'retraction_initiated')) | Q('action', 'eq', 'retraction_approved')) | Q('action', 'eq', 'retraction_cancelled')) | Q('action', 'eq', 'embargo_initiated')) | Q('action', 'eq', 'embargo_approved')) | Q('action', 'eq', 'embargo_completed')) | Q('action', 'eq', 'embargo_cancelled'))) return logs
[ "def", "get_targets", "(", ")", ":", "logs", "=", "NodeLog", ".", "find", "(", "(", "(", "(", "(", "(", "(", "(", "(", "(", "Q", "(", "'action'", ",", "'eq'", ",", "'registration_initiated'", ")", "|", "Q", "(", "'action'", ",", "'eq'", ",", "'re...
get addongithubnodesettings records with authorization and a non-null webhook .
train
false
13,592
def _massage_stats(request, stats): path = stats['path'] normalized = request.fs.normpath(path) return {'path': normalized, 'name': stats['name'], 'stats': stats.to_json_dict(), 'mtime': (datetime.fromtimestamp(stats['mtime']).strftime('%B %d, %Y %I:%M %p') if stats['mtime'] else ''), 'humansize': filesizeformat(stats['size']), 'type': filetype(stats['mode']), 'rwx': rwx(stats['mode'], stats['aclBit']), 'mode': stringformat(stats['mode'], 'o'), 'url': reverse('filebrowser.views.view', kwargs=dict(path=normalized)), 'is_sentry_managed': request.fs.is_sentry_managed(path)}
[ "def", "_massage_stats", "(", "request", ",", "stats", ")", ":", "path", "=", "stats", "[", "'path'", "]", "normalized", "=", "request", ".", "fs", ".", "normpath", "(", "path", ")", "return", "{", "'path'", ":", "normalized", ",", "'name'", ":", "stat...
massage a stats record as returned by the filesystem implementation into the format that the views would like it in .
train
false
13,593
def zero_remove(data, mask): new_mask = mask.copy() new_mask[(data == 0)] = 0 return new_mask
[ "def", "zero_remove", "(", "data", ",", "mask", ")", ":", "new_mask", "=", "mask", ".", "copy", "(", ")", "new_mask", "[", "(", "data", "==", "0", ")", "]", "=", "0", "return", "new_mask" ]
modify inputted mask to also mask out zero values .
train
false
13,594
def get_file_from_request(ext=None, folder=None, name='file'): if (ext is None): ext = [] print ('get_file_from_request() INVOKED. We have: request.files = %r' % request.files) if (name not in request.files): raise NotFoundError('File not found') uploaded_file = request.files[name] if (uploaded_file.filename == ''): raise NotFoundError('File not found') if (not _allowed_file(uploaded_file.filename, ext)): raise NotFoundError('Invalid file type') if (not folder): folder = app.config['UPLOAD_FOLDER'] else: with app.app_context(): folder = (app.config['BASE_DIR'] + folder) filename = secure_filename(uploaded_file.filename) uploaded_file.save(os.path.join(folder, filename)) return os.path.join(folder, filename)
[ "def", "get_file_from_request", "(", "ext", "=", "None", ",", "folder", "=", "None", ",", "name", "=", "'file'", ")", ":", "if", "(", "ext", "is", "None", ")", ":", "ext", "=", "[", "]", "print", "(", "'get_file_from_request() INVOKED. We have: request.files...
get file from a request .
train
false
13,595
def unixTime(): return systime.time()
[ "def", "unixTime", "(", ")", ":", "return", "systime", ".", "time", "(", ")" ]
return the current time in seconds with high precision (unix version .
train
false
13,596
def testing_warn(msg, stacklevel=3): filename = 'sqlalchemy.testing.warnings' lineno = 1 if isinstance(msg, util.string_types): warnings.warn_explicit(msg, sa_exc.SAWarning, filename, lineno) else: warnings.warn_explicit(msg, filename, lineno)
[ "def", "testing_warn", "(", "msg", ",", "stacklevel", "=", "3", ")", ":", "filename", "=", "'sqlalchemy.testing.warnings'", "lineno", "=", "1", "if", "isinstance", "(", "msg", ",", "util", ".", "string_types", ")", ":", "warnings", ".", "warn_explicit", "(",...
replaces sqlalchemy .
train
false
13,597
def toChunk(data): return (('%x\r\n' % len(data)), data, '\r\n')
[ "def", "toChunk", "(", "data", ")", ":", "return", "(", "(", "'%x\\r\\n'", "%", "len", "(", "data", ")", ")", ",", "data", ",", "'\\r\\n'", ")" ]
convert string to a chunk .
train
false
13,598
def gravatar(email, default_avatar_url=settings.DEFAULT_AVATAR_URL, size=175, rating='pg'): url = GRAVATAR_URL.format(emaildigest=md5(email).hexdigest()) url = urlparams(url, d=utils.absolutify(default_avatar_url), s=size, r=rating) return url
[ "def", "gravatar", "(", "email", ",", "default_avatar_url", "=", "settings", ".", "DEFAULT_AVATAR_URL", ",", "size", "=", "175", ",", "rating", "=", "'pg'", ")", ":", "url", "=", "GRAVATAR_URL", ".", "format", "(", "emaildigest", "=", "md5", "(", "email", ...
hacked from djangosnippets .
train
false
13,600
def getFeedRateMinute(feedRateMinute, splitLine): indexOfF = getIndexOfStartingWithSecond('F', splitLine) if (indexOfF > 0): return getDoubleAfterFirstLetter(splitLine[indexOfF]) return feedRateMinute
[ "def", "getFeedRateMinute", "(", "feedRateMinute", ",", "splitLine", ")", ":", "indexOfF", "=", "getIndexOfStartingWithSecond", "(", "'F'", ",", "splitLine", ")", "if", "(", "indexOfF", ">", "0", ")", ":", "return", "getDoubleAfterFirstLetter", "(", "splitLine", ...
get the feed rate per minute if the split line has a feed rate .
train
false
13,601
def humanitarian_id(): channel = settings.get_auth_humanitarian_id() if (not channel): redirect(URL(f='user', args=request.args, vars=get_vars)) from s3oauth import HumanitarianIDAccount auth.settings.login_form = HumanitarianIDAccount(channel) form = auth() return {'form': form}
[ "def", "humanitarian_id", "(", ")", ":", "channel", "=", "settings", ".", "get_auth_humanitarian_id", "(", ")", "if", "(", "not", "channel", ")", ":", "redirect", "(", "URL", "(", "f", "=", "'user'", ",", "args", "=", "request", ".", "args", ",", "vars...
login using humanitarian .
train
false
13,602
def runs(seq, op=gt): cycles = [] seq = iter(seq) try: run = [next(seq)] except StopIteration: return [] while True: try: ei = next(seq) except StopIteration: break if op(ei, run[(-1)]): run.append(ei) continue else: cycles.append(run) run = [ei] if run: cycles.append(run) return cycles
[ "def", "runs", "(", "seq", ",", "op", "=", "gt", ")", ":", "cycles", "=", "[", "]", "seq", "=", "iter", "(", "seq", ")", "try", ":", "run", "=", "[", "next", "(", "seq", ")", "]", "except", "StopIteration", ":", "return", "[", "]", "while", "...
group the sequence into lists in which successive elements all compare the same with the comparison operator .
train
false
13,603
@login_required @ensure_csrf_cookie @require_http_methods(('GET', 'POST', 'PUT', 'DELETE')) def course_team_handler(request, course_key_string=None, email=None): course_key = (CourseKey.from_string(course_key_string) if course_key_string else None) if ('application/json' in request.META.get('HTTP_ACCEPT', 'application/json')): return _course_team_user(request, course_key, email) elif (request.method == 'GET'): return _manage_users(request, course_key) else: return HttpResponseNotFound()
[ "@", "login_required", "@", "ensure_csrf_cookie", "@", "require_http_methods", "(", "(", "'GET'", ",", "'POST'", ",", "'PUT'", ",", "'DELETE'", ")", ")", "def", "course_team_handler", "(", "request", ",", "course_key_string", "=", "None", ",", "email", "=", "N...
the restful handler for course team users .
train
false
13,604
def Enum(*args, **kwargs): def getLabel(cls, val): ' Get a string label for the current value of the enum ' return cls.__labels[val] def validate(cls, val): ' Returns True if val is a valid value for the enumeration ' return (val in cls.__values) def getValues(cls): ' Returns a list of all the possible values for this enum ' return list(cls.__values) def getLabels(cls): ' Returns a list of all possible labels for this enum ' return list(cls.__labels.values()) def getValue(cls, label): ' Returns value given a label ' return cls.__labels[label] for arg in (list(args) + kwargs.keys()): if (type(arg) is not str): raise TypeError('Enum arg {0} must be a string'.format(arg)) if (not __isidentifier(arg)): raise ValueError("Invalid enum value '{0}'. '{0}' is not a valid identifier".format(arg)) kwargs.update(zip(args, args)) newType = type('Enum', (object,), kwargs) newType.__labels = dict(((v, k) for (k, v) in kwargs.iteritems())) newType.__values = set(newType.__labels.keys()) newType.getLabel = functools.partial(getLabel, newType) newType.validate = functools.partial(validate, newType) newType.getValues = functools.partial(getValues, newType) newType.getLabels = functools.partial(getLabels, newType) newType.getValue = functools.partial(getValue, newType) return newType
[ "def", "Enum", "(", "*", "args", ",", "**", "kwargs", ")", ":", "def", "getLabel", "(", "cls", ",", "val", ")", ":", "return", "cls", ".", "__labels", "[", "val", "]", "def", "validate", "(", "cls", ",", "val", ")", ":", "return", "(", "val", "...
enum is an adapter to another field: it will just change its display attribute .
train
true
13,605
def neutron_public_url(catalog): for i in catalog['access']['serviceCatalog']: if (i['type'] == 'network'): for endpoint in i['endpoints']: return endpoint['publicURL']
[ "def", "neutron_public_url", "(", "catalog", ")", ":", "for", "i", "in", "catalog", "[", "'access'", "]", "[", "'serviceCatalog'", "]", ":", "if", "(", "i", "[", "'type'", "]", "==", "'network'", ")", ":", "for", "endpoint", "in", "i", "[", "'endpoints...
get neutron publicurl .
train
false
13,608
def blast_genome(seqs, blast_db, e_value, max_hits, word_size, working_dir, blast_mat_root, extra_params=[], DEBUG=True): params = {'-M': 'BLOSUM62', '-a': '1', '-e': e_value, '-b': max_hits, '-W': word_size, '-v': max_hits, '-m': '9', '-p': 'blastn'} params.update(extra_params) output = blast_seqs(seqs, Blastall, blast_db=blast_db, params=params, WorkingDir=working_dir, add_seq_names=False, blast_mat_root=blast_mat_root) raw_output = [x for x in output['StdOut']] return raw_output
[ "def", "blast_genome", "(", "seqs", ",", "blast_db", ",", "e_value", ",", "max_hits", ",", "word_size", ",", "working_dir", ",", "blast_mat_root", ",", "extra_params", "=", "[", "]", ",", "DEBUG", "=", "True", ")", ":", "params", "=", "{", "'-M'", ":", ...
blast sequences against all genes in a genome seqs -- input sequences as strings blast_db -- path to blast database e_value -- e_value max_hits -- maximum sequences detected by blast to show word_size -- word size for initial blast screen .
train
false
13,609
def test_random_sample_size(): a = db.from_sequence(range(1000), npartitions=5) assert (10 < len(list(a.random_sample(0.1, 42))) < 300)
[ "def", "test_random_sample_size", "(", ")", ":", "a", "=", "db", ".", "from_sequence", "(", "range", "(", "1000", ")", ",", "npartitions", "=", "5", ")", "assert", "(", "10", "<", "len", "(", "list", "(", "a", ".", "random_sample", "(", "0.1", ",", ...
number of randomly sampled elements are in the expected range .
train
false
13,610
@testing.requires_testing_data def test_plot_source_spectrogram(): sample_src = read_source_spaces(op.join(subjects_dir, 'sample', 'bem', 'sample-oct-6-src.fif')) vertices = [s['vertno'] for s in sample_src] n_times = 5 n_verts = sum((len(v) for v in vertices)) stc_data = np.ones((n_verts, n_times)) stc = SourceEstimate(stc_data, vertices, 1, 1) plot_source_spectrogram([stc, stc], [[1, 2], [3, 4]]) assert_raises(ValueError, plot_source_spectrogram, [], []) assert_raises(ValueError, plot_source_spectrogram, [stc, stc], [[1, 2], [3, 4]], tmin=0) assert_raises(ValueError, plot_source_spectrogram, [stc, stc], [[1, 2], [3, 4]], tmax=7)
[ "@", "testing", ".", "requires_testing_data", "def", "test_plot_source_spectrogram", "(", ")", ":", "sample_src", "=", "read_source_spaces", "(", "op", ".", "join", "(", "subjects_dir", ",", "'sample'", ",", "'bem'", ",", "'sample-oct-6-src.fif'", ")", ")", "verti...
test plotting of source spectrogram .
train
false
13,613
def CohenEffectSize(group1, group2): diff = (group1.mean() - group2.mean()) (n1, n2) = (len(group1), len(group2)) var1 = group1.var() var2 = group2.var() pooled_var = (((n1 * var1) + (n2 * var2)) / (n1 + n2)) d = (diff / math.sqrt(pooled_var)) return d
[ "def", "CohenEffectSize", "(", "group1", ",", "group2", ")", ":", "diff", "=", "(", "group1", ".", "mean", "(", ")", "-", "group2", ".", "mean", "(", ")", ")", "(", "n1", ",", "n2", ")", "=", "(", "len", "(", "group1", ")", ",", "len", "(", "...
compute cohens d .
train
false
13,614
def dedent_lines(lines): return textwrap.dedent('\n'.join(lines)).split('\n')
[ "def", "dedent_lines", "(", "lines", ")", ":", "return", "textwrap", ".", "dedent", "(", "'\\n'", ".", "join", "(", "lines", ")", ")", ".", "split", "(", "'\\n'", ")" ]
deindent a list of lines maximally .
train
false
13,615
def getDisplayToolButtonsRepository(directoryPath, importantFileNames, names, repository): displayToolButtons = [] for name in names: displayToolButton = DisplayToolButton().getFromPath((name in importantFileNames), name, os.path.join(directoryPath, name), repository) displayToolButtons.append(displayToolButton) return displayToolButtons
[ "def", "getDisplayToolButtonsRepository", "(", "directoryPath", ",", "importantFileNames", ",", "names", ",", "repository", ")", ":", "displayToolButtons", "=", "[", "]", "for", "name", "in", "names", ":", "displayToolButton", "=", "DisplayToolButton", "(", ")", "...
get the display tool buttons .
train
false
13,617
def IsPacificDST(now): pst = time.gmtime(now) year = pst[0] assert (year >= 2007) begin = calendar.timegm((year, 3, 8, 2, 0, 0, 0, 0, 0)) while (time.gmtime(begin).tm_wday != SUNDAY): begin += DAY end = calendar.timegm((year, 11, 1, 2, 0, 0, 0, 0, 0)) while (time.gmtime(end).tm_wday != SUNDAY): end += DAY return (begin <= now < end)
[ "def", "IsPacificDST", "(", "now", ")", ":", "pst", "=", "time", ".", "gmtime", "(", "now", ")", "year", "=", "pst", "[", "0", "]", "assert", "(", "year", ">=", "2007", ")", "begin", "=", "calendar", ".", "timegm", "(", "(", "year", ",", "3", "...
helper for pacifictime to decide whether now is pacific dst .
train
false
13,619
def getAppExt(loops=0): bb = '!\xff\x0b' bb += 'NETSCAPE2.0' bb += '\x03\x01' if (loops == 0): loops = ((2 ** 16) - 1) bb += intToBin(loops) bb += '\x00' return bb
[ "def", "getAppExt", "(", "loops", "=", "0", ")", ":", "bb", "=", "'!\\xff\\x0b'", "bb", "+=", "'NETSCAPE2.0'", "bb", "+=", "'\\x03\\x01'", "if", "(", "loops", "==", "0", ")", ":", "loops", "=", "(", "(", "2", "**", "16", ")", "-", "1", ")", "bb",...
application extention .
train
false
13,620
def test_run_tb(): with TemporaryDirectory() as td: path = pjoin(td, 'foo.py') with open(path, 'w') as f: f.write('\n'.join(['def foo():', ' return bar()', 'def bar():', " raise RuntimeError('hello!')", 'foo()'])) with capture_output() as io: _ip.magic('run {}'.format(path)) out = io.stdout nt.assert_not_in('execfile', out) nt.assert_in('RuntimeError', out) nt.assert_equal(out.count('---->'), 3)
[ "def", "test_run_tb", "(", ")", ":", "with", "TemporaryDirectory", "(", ")", "as", "td", ":", "path", "=", "pjoin", "(", "td", ",", "'foo.py'", ")", "with", "open", "(", "path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "'\\n'", "....
test traceback offset in %run .
train
false
13,621
def _lg_undirected(G, selfloops=False, create_using=None): if (create_using is None): L = G.__class__() else: L = create_using get_edges = _edge_func(G) sorted_node = _node_func(G) shift = (0 if selfloops else 1) edges = set([]) for u in G: nodes = [sorted_node(*x) for x in get_edges(u)] if (len(nodes) == 1): L.add_node(nodes[0]) for (i, a) in enumerate(nodes): edges.update([_sorted_edge(a, b) for b in nodes[(i + shift):]]) L.add_edges_from(edges) return L
[ "def", "_lg_undirected", "(", "G", ",", "selfloops", "=", "False", ",", "create_using", "=", "None", ")", ":", "if", "(", "create_using", "is", "None", ")", ":", "L", "=", "G", ".", "__class__", "(", ")", "else", ":", "L", "=", "create_using", "get_e...
return the line graph l of the graph g .
train
false
13,622
def is_internal_attribute(obj, attr): if isinstance(obj, types.FunctionType): if (attr in UNSAFE_FUNCTION_ATTRIBUTES): return True elif isinstance(obj, types.MethodType): if ((attr in UNSAFE_FUNCTION_ATTRIBUTES) or (attr in UNSAFE_METHOD_ATTRIBUTES)): return True elif isinstance(obj, type): if (attr == 'mro'): return True elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)): return True elif isinstance(obj, types.GeneratorType): if (attr in UNSAFE_GENERATOR_ATTRIBUTES): return True elif (hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType)): if (attr in UNSAFE_COROUTINE_ATTRIBUTES): return True elif (hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType)): if (attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES): return True return attr.startswith('__')
[ "def", "is_internal_attribute", "(", "obj", ",", "attr", ")", ":", "if", "isinstance", "(", "obj", ",", "types", ".", "FunctionType", ")", ":", "if", "(", "attr", "in", "UNSAFE_FUNCTION_ATTRIBUTES", ")", ":", "return", "True", "elif", "isinstance", "(", "o...
test if the attribute given is an internal python attribute .
train
true
13,623
def glob(tgt, minion_id=None): if (minion_id is not None): if (not isinstance(minion_id, string_types)): minion_id = str(minion_id) else: minion_id = __grains__['id'] matcher = salt.minion.Matcher({'id': minion_id}, __salt__) try: return matcher.glob_match(tgt) except Exception as exc: log.exception(exc) return False
[ "def", "glob", "(", "tgt", ",", "minion_id", "=", "None", ")", ":", "if", "(", "minion_id", "is", "not", "None", ")", ":", "if", "(", "not", "isinstance", "(", "minion_id", ",", "string_types", ")", ")", ":", "minion_id", "=", "str", "(", "minion_id"...
iterates all filesystem paths that get matched by the glob pattern .
train
false
13,624
def _all_bookmarks(repo): return repo.bookmarks()[0]
[ "def", "_all_bookmarks", "(", "repo", ")", ":", "return", "repo", ".", "bookmarks", "(", ")", "[", "0", "]" ]
returns all bookmarks for the specified repo .
train
false
13,625
def getSpherical(azimuthDegrees, elevationDegrees, radius=1.0): return getSphericalByRadians(math.radians(azimuthDegrees), math.radians(elevationDegrees), radius)
[ "def", "getSpherical", "(", "azimuthDegrees", ",", "elevationDegrees", ",", "radius", "=", "1.0", ")", ":", "return", "getSphericalByRadians", "(", "math", ".", "radians", "(", "azimuthDegrees", ")", ",", "math", ".", "radians", "(", "elevationDegrees", ")", "...
get the spherical vector3 unit by degrees .
train
false
13,626
def funcname(func): if isinstance(func, functools.partial): return funcname(func.func) if isinstance(func, methodcaller): return func.method module_name = (getattr(func, '__module__', None) or '') type_name = (getattr(type(func), '__name__', None) or '') if (('toolz' in module_name) and ('curry' == type_name)): return func.func_name if (('multipledispatch' in module_name) and ('Dispatcher' == type_name)): return func.name try: name = func.__name__ if (name == '<lambda>'): return 'lambda' return name except: return str(func)
[ "def", "funcname", "(", "func", ")", ":", "if", "isinstance", "(", "func", ",", "functools", ".", "partial", ")", ":", "return", "funcname", "(", "func", ".", "func", ")", "if", "isinstance", "(", "func", ",", "methodcaller", ")", ":", "return", "func"...
get the name of a function .
train
false
13,628
def uniconvert(s, enc): if (not isinstance(s, unicode)): try: s = bin2unicode(s, enc) except UnicodeError: raise UnicodeError(('bad filename: ' + s)) return s.encode(enc)
[ "def", "uniconvert", "(", "s", ",", "enc", ")", ":", "if", "(", "not", "isinstance", "(", "s", ",", "unicode", ")", ")", ":", "try", ":", "s", "=", "bin2unicode", "(", "s", ",", "enc", ")", "except", "UnicodeError", ":", "raise", "UnicodeError", "(...
convert s to a string containing a unicode sequence encoded using encoding "enc" .
train
false
13,629
def _step4(state): C = (state.C == 0).astype(np.int) covered_C = (C * state.row_uncovered[:, np.newaxis]) covered_C *= astype(state.col_uncovered, dtype=np.int, copy=False) n = state.C.shape[0] m = state.C.shape[1] while True: (row, col) = np.unravel_index(np.argmax(covered_C), (n, m)) if (covered_C[(row, col)] == 0): return _step6 else: state.marked[(row, col)] = 2 star_col = np.argmax((state.marked[row] == 1)) if (not (state.marked[(row, star_col)] == 1)): state.Z0_r = row state.Z0_c = col return _step5 else: col = star_col state.row_uncovered[row] = False state.col_uncovered[col] = True covered_C[:, col] = (C[:, col] * astype(state.row_uncovered, dtype=np.int, copy=False)) covered_C[row] = 0
[ "def", "_step4", "(", "state", ")", ":", "C", "=", "(", "state", ".", "C", "==", "0", ")", ".", "astype", "(", "np", ".", "int", ")", "covered_C", "=", "(", "C", "*", "state", ".", "row_uncovered", "[", ":", ",", "np", ".", "newaxis", "]", ")...
find a noncovered zero and prime it .
train
false
13,630
def lowercase_keys(mapping): items = mapping.items() for (key, value) in items: del mapping[key] mapping[key.lower()] = value
[ "def", "lowercase_keys", "(", "mapping", ")", ":", "items", "=", "mapping", ".", "items", "(", ")", "for", "(", "key", ",", "value", ")", "in", "items", ":", "del", "mapping", "[", "key", "]", "mapping", "[", "key", ".", "lower", "(", ")", "]", "...
converts the values of the keys in mapping to lowercase .
train
false
13,631
def test_import_vispy(): modnames = loaded_vispy_modules('vispy', 2) assert_equal(modnames, set(_min_modules))
[ "def", "test_import_vispy", "(", ")", ":", "modnames", "=", "loaded_vispy_modules", "(", "'vispy'", ",", "2", ")", "assert_equal", "(", "modnames", ",", "set", "(", "_min_modules", ")", ")" ]
importing vispy should only pull in other vispy .
train
false
13,632
def query_all_issues(after): page = count(1) data = [] while True: page_data = query_issues(next(page), after) if (not page_data): break data.extend(page_data) return data
[ "def", "query_all_issues", "(", "after", ")", ":", "page", "=", "count", "(", "1", ")", "data", "=", "[", "]", "while", "True", ":", "page_data", "=", "query_issues", "(", "next", "(", "page", ")", ",", "after", ")", "if", "(", "not", "page_data", ...
hits the github api for all closed issues after the given date .
train
true
13,633
def switch_desc_to_dict(desc): r = {} for k in ['mfr_desc', 'hw_desc', 'sw_desc', 'serial_num', 'dp_desc']: r[k] = getattr(desc, k) return r
[ "def", "switch_desc_to_dict", "(", "desc", ")", ":", "r", "=", "{", "}", "for", "k", "in", "[", "'mfr_desc'", ",", "'hw_desc'", ",", "'sw_desc'", ",", "'serial_num'", ",", "'dp_desc'", "]", ":", "r", "[", "k", "]", "=", "getattr", "(", "desc", ",", ...
takes ofp_desc_stats response .
train
false
13,634
def copy_query_dict(query_dict, attr_list): res = QueryDict('', mutable=True) for attr in attr_list: if query_dict.has_key(attr): res[attr] = query_dict.get(attr) return res
[ "def", "copy_query_dict", "(", "query_dict", ",", "attr_list", ")", ":", "res", "=", "QueryDict", "(", "''", ",", "mutable", "=", "True", ")", "for", "attr", "in", "attr_list", ":", "if", "query_dict", ".", "has_key", "(", "attr", ")", ":", "res", "[",...
copy_query_dict -> querydict object copy the specified attributes to a new querydict .
train
false
13,635
def getBackOfLoops(loops): negativeFloat = (-999999999.7534235) back = negativeFloat for loop in loops: for point in loop: back = max(back, point.imag) if (back == negativeFloat): print 'This should never happen, there are no loops for getBackOfLoops in euclidean' return back
[ "def", "getBackOfLoops", "(", "loops", ")", ":", "negativeFloat", "=", "(", "-", "999999999.7534235", ")", "back", "=", "negativeFloat", "for", "loop", "in", "loops", ":", "for", "point", "in", "loop", ":", "back", "=", "max", "(", "back", ",", "point", ...
get the back of the loops .
train
false
13,636
def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if (not exists(name, region, key, keyid, profile)): return True if (policies is None): policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies {0} on ELB {1} backend server {2}'.format(policies, name, port)) except boto.exception.BotoServerError as e: log.debug(e) log.info('Failed to set policy {0} on ELB {1} backend server {2}: {3}'.format(policies, name, port, e.message)) return False return True
[ "def", "set_backend_policy", "(", "name", ",", "port", ",", "policies", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", ...
set the policies of an elb backend server .
train
true
13,637
def averageOnTimePerTimestep(vectors, numSamples=None): if (vectors.ndim == 1): vectors.shape = ((-1), 1) numTimeSteps = len(vectors) numElements = len(vectors[0]) if (numSamples is not None): import pdb pdb.set_trace() countOn = numpy.random.randint(0, numElements, numSamples) vectors = vectors[:, countOn] durations = numpy.zeros(vectors.shape, dtype='int32') for col in xrange(vectors.shape[1]): _fillInOnTimes(vectors[:, col], durations[:, col]) sums = vectors.sum(axis=1) sums.clip(min=1, max=numpy.inf, out=sums) avgDurations = (durations.sum(axis=1, dtype='float64') / sums) avgOnTime = (avgDurations.sum() / (avgDurations > 0).sum()) freqCounts = _accumulateFrequencyCounts(avgDurations) return (avgOnTime, freqCounts)
[ "def", "averageOnTimePerTimestep", "(", "vectors", ",", "numSamples", "=", "None", ")", ":", "if", "(", "vectors", ".", "ndim", "==", "1", ")", ":", "vectors", ".", "shape", "=", "(", "(", "-", "1", ")", ",", "1", ")", "numTimeSteps", "=", "len", "...
computes the average on-time of the outputs that are on at each time step .
train
true
13,638
def uniform_linear_layout(points): indices = numpy.argsort(points) space = numpy.asarray(linspace(len(points))) indices = invert_permutation_indices(indices) points = space[indices] return points.tolist()
[ "def", "uniform_linear_layout", "(", "points", ")", ":", "indices", "=", "numpy", ".", "argsort", "(", "points", ")", "space", "=", "numpy", ".", "asarray", "(", "linspace", "(", "len", "(", "points", ")", ")", ")", "indices", "=", "invert_permutation_indi...
layout the points in a uniform linear space while preserving the existing sorting order .
train
false
13,639
def _KNV0(B, ker_pole, transfer_matrix, j, poles): transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1) (Q, R) = s_qr(transfer_matrix_not_j, mode='full') mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T) yj = np.dot(mat_ker_pj, Q[:, (-1)]) if (not np.allclose(yj, 0)): xj = (yj / np.linalg.norm(yj)) transfer_matrix[:, j] = xj
[ "def", "_KNV0", "(", "B", ",", "ker_pole", ",", "transfer_matrix", ",", "j", ",", "poles", ")", ":", "transfer_matrix_not_j", "=", "np", ".", "delete", "(", "transfer_matrix", ",", "j", ",", "axis", "=", "1", ")", "(", "Q", ",", "R", ")", "=", "s_q...
algorithm "knv0" kautsky et al .
train
false
13,643
def get_qualitycheck_list(path_obj): result = [] checks = get_qualitychecks() for (check, cat) in checks.items(): result.append({'code': check, 'is_critical': (cat == Category.CRITICAL), 'title': (u'%s' % check_names.get(check, check)), 'url': path_obj.get_translate_url(check=check)}) def alphabetical_critical_first(item): critical_first = (0 if item['is_critical'] else 1) return (critical_first, item['title'].lower()) result = sorted(result, key=alphabetical_critical_first) return result
[ "def", "get_qualitycheck_list", "(", "path_obj", ")", ":", "result", "=", "[", "]", "checks", "=", "get_qualitychecks", "(", ")", "for", "(", "check", ",", "cat", ")", "in", "checks", ".", "items", "(", ")", ":", "result", ".", "append", "(", "{", "'...
returns list of checks sorted in alphabetical order but having critical checks first .
train
false
13,645
def apply_filters(records, filters): operators = {COMPARISON.LT: operator.lt, COMPARISON.MAX: operator.le, COMPARISON.EQ: operator.eq, COMPARISON.NOT: operator.ne, COMPARISON.MIN: operator.ge, COMPARISON.GT: operator.gt, COMPARISON.IN: operator.contains, COMPARISON.EXCLUDE: (lambda x, y: (not operator.contains(x, y))), COMPARISON.LIKE: (lambda x, y: re.search(y, x, re.IGNORECASE))} for record in records: matches = True for f in filters: right = f.value if (f.field == DEFAULT_ID_FIELD): if isinstance(right, int): right = str(right) left = record subfields = f.field.split('.') for subfield in subfields: if (not isinstance(left, dict)): break left = left.get(subfield) if (f.operator in (COMPARISON.IN, COMPARISON.EXCLUDE)): (right, left) = (left, right) elif (left is None): right_is_number = (isinstance(right, (int, float)) and (right not in (True, False))) if right_is_number: matches = False continue else: left = '' matches = (matches and operators[f.operator](left, right)) if matches: (yield record)
[ "def", "apply_filters", "(", "records", ",", "filters", ")", ":", "operators", "=", "{", "COMPARISON", ".", "LT", ":", "operator", ".", "lt", ",", "COMPARISON", ".", "MAX", ":", "operator", ".", "le", ",", "COMPARISON", ".", "EQ", ":", "operator", ".",...
use this method to apply an iterable of filters to a stream .
train
false
13,646
def nathanathan(function, yays=[], nays=[]): yay_set = set() nay_set = set() for yay in yays: if (yay in yay_set): print (yay + ' tried to vote more than once.') else: yay_set.add(yay) for nay in nays: if (nay in nay_set): print (nay + ' tried to vote more than once.') else: nay_set.add(nay) for yay_nay_vote in yay_set.intersection(nay_set): print (yay_nay_vote + ' voted yay and nay.') valid_names = nathanathan.__globals__.keys() for vote in yay_set.union(nay_set): if (vote not in valid_names): print (vote + ' is not a valid voter') if (vote in yay_set): yay_set.remove(vote) if (vote in nay_set): nay_set.remove(vote) if (len(yay_set) >= len(nay_set)): function()
[ "def", "nathanathan", "(", "function", ",", "yays", "=", "[", "]", ",", "nays", "=", "[", "]", ")", ":", "yay_set", "=", "set", "(", ")", "nay_set", "=", "set", "(", ")", "for", "yay", "in", "yays", ":", "if", "(", "yay", "in", "yay_set", ")", ...
this is a function for voting on whether functions should run .
train
false
13,647
def label_indivs(valuation, lexicon=False): domain = valuation.domain pairs = [(e, e) for e in domain] if lexicon: lex = make_lex(domain) with open(u'chat_pnames.cfg', u'w') as outfile: outfile.writelines(lex) valuation.update(pairs) return valuation
[ "def", "label_indivs", "(", "valuation", ",", "lexicon", "=", "False", ")", ":", "domain", "=", "valuation", ".", "domain", "pairs", "=", "[", "(", "e", ",", "e", ")", "for", "e", "in", "domain", "]", "if", "lexicon", ":", "lex", "=", "make_lex", "...
assign individual constants to the individuals in the domain of a valuation .
train
false
13,649
def sub_func_doit(eq, func, new): reps = {} repu = {} for d in eq.atoms(Derivative): u = Dummy('u') repu[u] = d.subs(func, new).doit() reps[d] = u return eq.subs(reps).subs(func, new).subs(repu)
[ "def", "sub_func_doit", "(", "eq", ",", "func", ",", "new", ")", ":", "reps", "=", "{", "}", "repu", "=", "{", "}", "for", "d", "in", "eq", ".", "atoms", "(", "Derivative", ")", ":", "u", "=", "Dummy", "(", "'u'", ")", "repu", "[", "u", "]", ...
when replacing the func with something else .
train
false
13,650
def tee(content, file): fd = open(file, 'a') fd.write((content + '\n')) fd.close() print content
[ "def", "tee", "(", "content", ",", "file", ")", ":", "fd", "=", "open", "(", "file", ",", "'a'", ")", "fd", ".", "write", "(", "(", "content", "+", "'\\n'", ")", ")", "fd", ".", "close", "(", ")", "print", "content" ]
write content to standard output and file .
train
false
13,652
def wrap_old_error_serializer(old_fn): def new_fn(req, resp, exception): (media_type, body) = old_fn(req, exception) if (body is not None): resp.body = body resp.content_type = media_type return new_fn
[ "def", "wrap_old_error_serializer", "(", "old_fn", ")", ":", "def", "new_fn", "(", "req", ",", "resp", ",", "exception", ")", ":", "(", "media_type", ",", "body", ")", "=", "old_fn", "(", "req", ",", "exception", ")", "if", "(", "body", "is", "not", ...
wraps an old-style error serializer to add body/content_type setting .
train
false
13,653
@ensure_csrf_cookie @cache_if_anonymous() def courses(request): enable_mktg_site = configuration_helpers.get_value('ENABLE_MKTG_SITE', settings.FEATURES.get('ENABLE_MKTG_SITE', False)) if enable_mktg_site: return redirect(marketing_link('COURSES'), permanent=True) if (not settings.FEATURES.get('COURSES_ARE_BROWSABLE')): raise Http404 return courseware.views.views.courses(request)
[ "@", "ensure_csrf_cookie", "@", "cache_if_anonymous", "(", ")", "def", "courses", "(", "request", ")", ":", "enable_mktg_site", "=", "configuration_helpers", ".", "get_value", "(", "'ENABLE_MKTG_SITE'", ",", "settings", ".", "FEATURES", ".", "get", "(", "'ENABLE_M...
render the "find courses" page .
train
false
13,654
def standard_node(hostname): return ProcessNode.using_ssh(hostname, 22, 'root', SSH_PRIVATE_KEY_PATH)
[ "def", "standard_node", "(", "hostname", ")", ":", "return", "ProcessNode", ".", "using_ssh", "(", "hostname", ",", "22", ",", "'root'", ",", "SSH_PRIVATE_KEY_PATH", ")" ]
create the default production inode for the given hostname .
train
false