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 |
|---|---|---|---|---|---|
54,145 | def force_link(src, dest):
return utils.system(('ln -sf %s %s' % (src, dest)))
| [
"def",
"force_link",
"(",
"src",
",",
"dest",
")",
":",
"return",
"utils",
".",
"system",
"(",
"(",
"'ln -sf %s %s'",
"%",
"(",
"src",
",",
"dest",
")",
")",
")"
] | link src to dest . | train | false |
54,146 | def test_rgb_to_hsl_part_2():
pass
| [
"def",
"test_rgb_to_hsl_part_2",
"(",
")",
":",
"pass"
] | test rgb to hsl color function . | train | false |
54,147 | def LocalService(name):
assert odoo.conf.deprecation.allow_local_service
_logger.warning(("LocalService() is deprecated since march 2013 (it was called with '%s')." % name))
if (name == 'workflow'):
return odoo.workflow
if name.startswith('report.'):
report = odoo.report.interface.report_int._reports.get(name)
if report:
return report
else:
dbname = getattr(threading.currentThread(), 'dbname', None)
if dbname:
registry = odoo.registry(dbname)
with registry.cursor() as cr:
return registry['ir.actions.report.xml']._lookup_report(cr, name[len('report.'):])
| [
"def",
"LocalService",
"(",
"name",
")",
":",
"assert",
"odoo",
".",
"conf",
".",
"deprecation",
".",
"allow_local_service",
"_logger",
".",
"warning",
"(",
"(",
"\"LocalService() is deprecated since march 2013 (it was called with '%s').\"",
"%",
"name",
")",
")",
"if... | the odoo . | train | false |
54,148 | def truncated(f):
@functools.wraps(f)
def wrapper(self, hints, *args, **kwargs):
if (not hasattr(hints, 'limit')):
raise exception.UnexpectedError(_('Cannot truncate a driver call without hints list as first parameter after self '))
if ((hints.limit is None) or hints.filters):
return f(self, hints, *args, **kwargs)
list_limit = hints.limit['limit']
hints.set_limit((list_limit + 1))
ref_list = f(self, hints, *args, **kwargs)
if (len(ref_list) > list_limit):
hints.set_limit(list_limit, truncated=True)
return ref_list[:list_limit]
else:
hints.set_limit(list_limit)
return ref_list
return wrapper
| [
"def",
"truncated",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"hints",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"hints",
",",
"'limit'",
")",
... | ensure list truncation is detected in driver list entity methods . | train | false |
54,149 | def qtapi_version():
try:
import sip
except ImportError:
return
try:
return sip.getapi('QString')
except ValueError:
return
| [
"def",
"qtapi_version",
"(",
")",
":",
"try",
":",
"import",
"sip",
"except",
"ImportError",
":",
"return",
"try",
":",
"return",
"sip",
".",
"getapi",
"(",
"'QString'",
")",
"except",
"ValueError",
":",
"return"
] | return which qstring api has been set . | train | false |
54,150 | def get_docstring(node, clean=True):
if (not isinstance(node, (AsyncFunctionDef, FunctionDef, ClassDef, Module))):
raise TypeError(("%r can't have docstrings" % node.__class__.__name__))
if (not (node.body and isinstance(node.body[0], Expr))):
return
node = node.body[0].value
if isinstance(node, Str):
text = node.s
elif (isinstance(node, Constant) and isinstance(node.value, str)):
text = node.value
else:
return
if clean:
import inspect
text = inspect.cleandoc(text)
return text
| [
"def",
"get_docstring",
"(",
"node",
",",
"clean",
"=",
"True",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"node",
",",
"(",
"AsyncFunctionDef",
",",
"FunctionDef",
",",
"ClassDef",
",",
"Module",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"(",... | return the docstring for the given node or none if no docstring can be found . | train | false |
54,151 | def iprand_all():
return 'iprand_all'
| [
"def",
"iprand_all",
"(",
")",
":",
"return",
"'iprand_all'"
] | some ipython tests with fully random output . | train | false |
54,154 | def get_technical_lengths(input_map, debug=False):
if debug:
print 'Making debug output'
(body, header, comments) = parse_mapping_file(input_map)
if debug:
print 'HEADER:', header
key_index = header.index('KEY_SEQ')
bc_index = header.index('BARCODE')
if ('LINKER' in header):
linker_index = header.index('LINKER')
else:
linker_index = None
primer_index = header.index('PRIMER')
technical_lengths = {}
for fields in body:
curr_tech_len = ((len(fields[key_index]) + len(fields[bc_index])) + len(fields[primer_index]))
if (linker_index is not None):
curr_tech_len += len(fields[linker_index])
technical_lengths[fields[0]] = curr_tech_len
if debug:
print 'Technical lengths:'
print technical_lengths
return technical_lengths
| [
"def",
"get_technical_lengths",
"(",
"input_map",
",",
"debug",
"=",
"False",
")",
":",
"if",
"debug",
":",
"print",
"'Making debug output'",
"(",
"body",
",",
"header",
",",
"comments",
")",
"=",
"parse_mapping_file",
"(",
"input_map",
")",
"if",
"debug",
"... | returns per-sample info on technical lengths . | train | false |
54,156 | def _send_message(room_id, message, from_name, api_key=None, api_version=None, api_url=None, color=None, notify=False):
parameters = dict()
parameters['room_id'] = room_id
parameters['from'] = from_name[:15]
parameters['message'] = message[:10000]
parameters['message_format'] = 'text'
parameters['color'] = color
parameters['notify'] = notify
result = _query(function='message', api_key=api_key, api_version=api_version, room_id=room_id, api_url=api_url, method='POST', data=parameters)
if result:
return True
else:
return False
| [
"def",
"_send_message",
"(",
"room_id",
",",
"message",
",",
"from_name",
",",
"api_key",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"api_url",
"=",
"None",
",",
"color",
"=",
"None",
",",
"notify",
"=",
"False",
")",
":",
"parameters",
"=",
"d... | send a message to a hipchat room . | train | false |
54,158 | def build_pool(test_case):
return StoragePool(reactor, create_zfs_pool(test_case), FilePath(test_case.mktemp()))
| [
"def",
"build_pool",
"(",
"test_case",
")",
":",
"return",
"StoragePool",
"(",
"reactor",
",",
"create_zfs_pool",
"(",
"test_case",
")",
",",
"FilePath",
"(",
"test_case",
".",
"mktemp",
"(",
")",
")",
")"
] | create a storagepool . | train | false |
54,159 | def _fire_score_changed_for_block(course_id, student, block, module_state_key):
if (block and block.has_score):
max_score = block.max_score()
if (max_score is not None):
PROBLEM_RAW_SCORE_CHANGED.send(sender=None, raw_earned=0, raw_possible=max_score, weight=getattr(block, 'weight', None), user_id=student.id, course_id=unicode(course_id), usage_id=unicode(module_state_key), score_deleted=True, only_if_higher=False, modified=datetime.now().replace(tzinfo=pytz.UTC), score_db_table=ScoreDatabaseTableEnum.courseware_student_module)
| [
"def",
"_fire_score_changed_for_block",
"(",
"course_id",
",",
"student",
",",
"block",
",",
"module_state_key",
")",
":",
"if",
"(",
"block",
"and",
"block",
".",
"has_score",
")",
":",
"max_score",
"=",
"block",
".",
"max_score",
"(",
")",
"if",
"(",
"ma... | fires a problem_raw_score_changed event for the given module . | train | false |
54,162 | @contextmanager
def assuming(*assumptions):
old_global_assumptions = global_assumptions.copy()
global_assumptions.update(assumptions)
try:
(yield)
finally:
global_assumptions.clear()
global_assumptions.update(old_global_assumptions)
| [
"@",
"contextmanager",
"def",
"assuming",
"(",
"*",
"assumptions",
")",
":",
"old_global_assumptions",
"=",
"global_assumptions",
".",
"copy",
"(",
")",
"global_assumptions",
".",
"update",
"(",
"assumptions",
")",
"try",
":",
"(",
"yield",
")",
"finally",
":"... | context manager for assumptions examples . | train | false |
54,163 | def double_redirect_view(request):
return HttpResponseRedirect('/test_client/permanent_redirect_view/')
| [
"def",
"double_redirect_view",
"(",
"request",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"'/test_client/permanent_redirect_view/'",
")"
] | a view that redirects all requests to a redirection view . | train | false |
54,164 | @hooks.register(u'before_serve_page')
def check_view_restrictions(page, request, serve_args, serve_kwargs):
for restriction in page.get_view_restrictions():
if (not restriction.accept_request(request)):
if (restriction.restriction_type == PageViewRestriction.PASSWORD):
from wagtail.wagtailcore.forms import PasswordPageViewRestrictionForm
form = PasswordPageViewRestrictionForm(instance=restriction, initial={u'return_url': request.get_full_path()})
action_url = reverse(u'wagtailcore_authenticate_with_password', args=[restriction.id, page.id])
return page.serve_password_required_response(request, form, action_url)
elif (restriction.restriction_type in [PageViewRestriction.LOGIN, PageViewRestriction.GROUPS]):
return require_wagtail_login(next=request.get_full_path())
| [
"@",
"hooks",
".",
"register",
"(",
"u'before_serve_page'",
")",
"def",
"check_view_restrictions",
"(",
"page",
",",
"request",
",",
"serve_args",
",",
"serve_kwargs",
")",
":",
"for",
"restriction",
"in",
"page",
".",
"get_view_restrictions",
"(",
")",
":",
"... | check whether there are any view restrictions on this page which are not fulfilled by the given request object . | train | false |
54,165 | def close_all_open_files(exclude=set()):
maxfd = get_maximum_file_descriptors()
for fd in reversed(range(maxfd)):
if (fd not in exclude):
close_file_descriptor_if_open(fd)
| [
"def",
"close_all_open_files",
"(",
"exclude",
"=",
"set",
"(",
")",
")",
":",
"maxfd",
"=",
"get_maximum_file_descriptors",
"(",
")",
"for",
"fd",
"in",
"reversed",
"(",
"range",
"(",
"maxfd",
")",
")",
":",
"if",
"(",
"fd",
"not",
"in",
"exclude",
")... | close all open file descriptors . | train | false |
54,166 | def get_engine(hass, config):
return DemoProvider(config[CONF_LANG])
| [
"def",
"get_engine",
"(",
"hass",
",",
"config",
")",
":",
"return",
"DemoProvider",
"(",
"config",
"[",
"CONF_LANG",
"]",
")"
] | setup demo speech component . | train | false |
54,167 | def decode_wanted(parts):
wanted = {}
key_map = dict(d='data', m='meta')
if parts:
for k in key_map:
if (k in parts[0]):
wanted[key_map[k]] = True
if (not wanted):
wanted['data'] = True
return wanted
| [
"def",
"decode_wanted",
"(",
"parts",
")",
":",
"wanted",
"=",
"{",
"}",
"key_map",
"=",
"dict",
"(",
"d",
"=",
"'data'",
",",
"m",
"=",
"'meta'",
")",
"if",
"parts",
":",
"for",
"k",
"in",
"key_map",
":",
"if",
"(",
"k",
"in",
"parts",
"[",
"0... | parse missing_check line parts to determine which parts of local diskfile were wanted by the receiver . | train | false |
54,168 | def random_all():
pass
| [
"def",
"random_all",
"(",
")",
":",
"pass"
] | a function where we ignore the output of all examples . | train | false |
54,172 | @api_wrapper
def get_export(module, filesystem, system):
export = None
exports_to_list = system.exports.to_list()
for e in exports_to_list:
if (e.get_export_path() == module.params['name']):
export = e
break
return export
| [
"@",
"api_wrapper",
"def",
"get_export",
"(",
"module",
",",
"filesystem",
",",
"system",
")",
":",
"export",
"=",
"None",
"exports_to_list",
"=",
"system",
".",
"exports",
".",
"to_list",
"(",
")",
"for",
"e",
"in",
"exports_to_list",
":",
"if",
"(",
"e... | retrun export if found . | train | false |
54,173 | def rte_classifier(trainer, features=rte_features):
train = ((pair, pair.value) for pair in nltk.corpus.rte.pairs(['rte1_dev.xml', 'rte2_dev.xml', 'rte3_dev.xml']))
test = ((pair, pair.value) for pair in nltk.corpus.rte.pairs(['rte1_test.xml', 'rte2_test.xml', 'rte3_test.xml']))
print('Training classifier...')
classifier = trainer([(features(pair), label) for (pair, label) in train])
print('Testing classifier...')
acc = accuracy(classifier, [(features(pair), label) for (pair, label) in test])
print(('Accuracy: %6.4f' % acc))
return classifier
| [
"def",
"rte_classifier",
"(",
"trainer",
",",
"features",
"=",
"rte_features",
")",
":",
"train",
"=",
"(",
"(",
"pair",
",",
"pair",
".",
"value",
")",
"for",
"pair",
"in",
"nltk",
".",
"corpus",
".",
"rte",
".",
"pairs",
"(",
"[",
"'rte1_dev.xml'",
... | classify rtepairs . | train | false |
54,177 | def get_patch_verts(patch):
trans = patch.get_patch_transform()
path = patch.get_path()
polygons = path.to_polygons(trans)
if len(polygons):
return polygons[0]
else:
return []
| [
"def",
"get_patch_verts",
"(",
"patch",
")",
":",
"trans",
"=",
"patch",
".",
"get_patch_transform",
"(",
")",
"path",
"=",
"patch",
".",
"get_path",
"(",
")",
"polygons",
"=",
"path",
".",
"to_polygons",
"(",
"trans",
")",
"if",
"len",
"(",
"polygons",
... | return a list of vertices for the path of a patch . | train | false |
54,178 | def kegg_find(database, query, option=None):
if ((database in ['compound', 'drug']) and (option in ['formula', 'exact_mass', 'mol_weight'])):
resp = _q('find', database, query, option)
elif option:
raise Exception('Invalid option arg for kegg find request.')
else:
if isinstance(query, list):
query = '+'.join(query)
resp = _q('find', database, query)
return resp
| [
"def",
"kegg_find",
"(",
"database",
",",
"query",
",",
"option",
"=",
"None",
")",
":",
"if",
"(",
"(",
"database",
"in",
"[",
"'compound'",
",",
"'drug'",
"]",
")",
"and",
"(",
"option",
"in",
"[",
"'formula'",
",",
"'exact_mass'",
",",
"'mol_weight'... | kegg find - data search . | train | false |
54,179 | def _auc(y_true, y_score):
pos_label = np.unique(y_true)[1]
pos = y_score[(y_true == pos_label)]
neg = y_score[(y_true != pos_label)]
diff_matrix = (pos.reshape(1, (-1)) - neg.reshape((-1), 1))
n_correct = np.sum((diff_matrix > 0))
return (n_correct / float((len(pos) * len(neg))))
| [
"def",
"_auc",
"(",
"y_true",
",",
"y_score",
")",
":",
"pos_label",
"=",
"np",
".",
"unique",
"(",
"y_true",
")",
"[",
"1",
"]",
"pos",
"=",
"y_score",
"[",
"(",
"y_true",
"==",
"pos_label",
")",
"]",
"neg",
"=",
"y_score",
"[",
"(",
"y_true",
"... | alternative implementation to check for correctness of roc_auc_score . | train | false |
54,180 | def is_interactive():
return _is_interactive
| [
"def",
"is_interactive",
"(",
")",
":",
"return",
"_is_interactive"
] | general api for a script specifying that it is being run in an interactive environment . | train | false |
54,181 | def get_dataset_toy():
trainset = ToyDataset()
testset = ToyDataset()
return (trainset, testset)
| [
"def",
"get_dataset_toy",
"(",
")",
":",
"trainset",
"=",
"ToyDataset",
"(",
")",
"testset",
"=",
"ToyDataset",
"(",
")",
"return",
"(",
"trainset",
",",
"testset",
")"
] | the toy dataset is only meant to used for testing pipelines . | train | false |
54,182 | def _create_image_html(figure, area_data, plot_info):
(png, bbox) = _create_png(figure)
areas = [(_AREA_TEMPLATE % ((data['left'] - bbox[0]), (data['top'] - bbox[1]), (data['right'] - bbox[0]), (data['bottom'] - bbox[1]), data['title'], data['callback'], _json_encoder.encode(data['callback_arguments']).replace('"', '"'))) for data in area_data]
map_name = (plot_info.drilldown_callback + '_map')
return (_HTML_TEMPLATE % (base64.b64encode(png), map_name, map_name, '\n'.join(areas)))
| [
"def",
"_create_image_html",
"(",
"figure",
",",
"area_data",
",",
"plot_info",
")",
":",
"(",
"png",
",",
"bbox",
")",
"=",
"_create_png",
"(",
"figure",
")",
"areas",
"=",
"[",
"(",
"_AREA_TEMPLATE",
"%",
"(",
"(",
"data",
"[",
"'left'",
"]",
"-",
... | given the figure and drilldown data . | train | false |
54,183 | @must_have_permission(ADMIN)
@must_be_valid_project
def new_draft_registration(auth, node, *args, **kwargs):
if node.is_registration:
raise HTTPError(http.FORBIDDEN, data={'message_short': "Can't create draft", 'message_long': 'Creating draft registrations on registered projects is not allowed.'})
data = request.values
schema_name = data.get('schema_name')
if (not schema_name):
raise HTTPError(http.BAD_REQUEST, data={'message_short': 'Must specify a schema_name', 'message_long': 'Please specify a schema_name'})
schema_version = data.get('schema_version', 2)
meta_schema = get_schema_or_fail((Q('name', 'eq', schema_name) & Q('schema_version', 'eq', int(schema_version))))
draft = DraftRegistration.create_from_node(node, user=auth.user, schema=meta_schema, data={})
return redirect(node.web_url_for('edit_draft_registration_page', draft_id=draft._id))
| [
"@",
"must_have_permission",
"(",
"ADMIN",
")",
"@",
"must_be_valid_project",
"def",
"new_draft_registration",
"(",
"auth",
",",
"node",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"node",
".",
"is_registration",
":",
"raise",
"HTTPError",
"(",
"h... | create a new draft registration for the node :return: redirect to the new drafts edit page :rtype: flask . | train | false |
54,184 | def tree_item_iterator(items, ancestors=False):
structure = {}
opts = None
first_item_level = 0
for (previous, current, next_) in previous_current_next(items):
if (opts is None):
opts = current._mptt_meta
current_level = getattr(current, opts.level_attr)
if previous:
structure[u'new_level'] = (getattr(previous, opts.level_attr) < current_level)
if ancestors:
if structure[u'closed_levels']:
structure[u'ancestors'] = structure[u'ancestors'][:(- len(structure[u'closed_levels']))]
if structure[u'new_level']:
structure[u'ancestors'].append(text_type(previous))
else:
structure[u'new_level'] = True
if ancestors:
structure[u'ancestors'] = []
first_item_level = current_level
if next_:
structure[u'closed_levels'] = list(range(current_level, getattr(next_, opts.level_attr), (-1)))
else:
structure[u'closed_levels'] = list(range(current_level, (first_item_level - 1), (-1)))
(yield (current, copy.deepcopy(structure)))
| [
"def",
"tree_item_iterator",
"(",
"items",
",",
"ancestors",
"=",
"False",
")",
":",
"structure",
"=",
"{",
"}",
"opts",
"=",
"None",
"first_item_level",
"=",
"0",
"for",
"(",
"previous",
",",
"current",
",",
"next_",
")",
"in",
"previous_current_next",
"(... | given a list of tree items . | train | false |
54,186 | def _count1Bits(num):
ret = 0
while (num > 0):
num = (num >> 1)
ret += 1
return ret
| [
"def",
"_count1Bits",
"(",
"num",
")",
":",
"ret",
"=",
"0",
"while",
"(",
"num",
">",
"0",
")",
":",
"num",
"=",
"(",
"num",
">>",
"1",
")",
"ret",
"+=",
"1",
"return",
"ret"
] | find the highest bit set to 1 in an integer . | train | false |
54,187 | def holdReject():
a = TpPd(pd=3)
b = MessageType(mesType=26)
c = Cause()
packet = ((a / b) / c)
return packet
| [
"def",
"holdReject",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"26",
")",
"c",
"=",
"Cause",
"(",
")",
"packet",
"=",
"(",
"(",
"a",
"/",
"b",
")",
"/",
"c",
")",
"return",
"pac... | hold reject section 9 . | train | true |
54,188 | def customize_config_vars(_config_vars):
if (not _supports_universal_builds()):
_remove_universal_flags(_config_vars)
_override_all_archs(_config_vars)
_check_for_unavailable_sdk(_config_vars)
return _config_vars
| [
"def",
"customize_config_vars",
"(",
"_config_vars",
")",
":",
"if",
"(",
"not",
"_supports_universal_builds",
"(",
")",
")",
":",
"_remove_universal_flags",
"(",
"_config_vars",
")",
"_override_all_archs",
"(",
"_config_vars",
")",
"_check_for_unavailable_sdk",
"(",
... | customize python build configuration variables . | train | false |
54,190 | def cc_benchmark(name, deps=[], **kwargs):
cc_config = configparse.blade_config.get_config('cc_config')
benchmark_libs = cc_config['benchmark_libs']
benchmark_main_libs = cc_config['benchmark_main_libs']
deps = ((var_to_list(deps) + benchmark_libs) + benchmark_main_libs)
cc_binary(name=name, deps=deps, **kwargs)
| [
"def",
"cc_benchmark",
"(",
"name",
",",
"deps",
"=",
"[",
"]",
",",
"**",
"kwargs",
")",
":",
"cc_config",
"=",
"configparse",
".",
"blade_config",
".",
"get_config",
"(",
"'cc_config'",
")",
"benchmark_libs",
"=",
"cc_config",
"[",
"'benchmark_libs'",
"]",... | cc_benchmark target . | train | false |
54,191 | def read_dot(path):
try:
import pygraphviz
except ImportError:
raise ImportError('read_dot() requires pygraphviz ', 'http://pygraphviz.github.io/')
A = pygraphviz.AGraph(file=path)
return from_agraph(A)
| [
"def",
"read_dot",
"(",
"path",
")",
":",
"try",
":",
"import",
"pygraphviz",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'read_dot() requires pygraphviz '",
",",
"'http://pygraphviz.github.io/'",
")",
"A",
"=",
"pygraphviz",
".",
"AGraph",
"(",
"f... | return a networkx graph from a dot file on path . | train | false |
54,192 | def EvalBinomialPmf(k, n, p):
return stats.binom.pmf(k, n, p)
| [
"def",
"EvalBinomialPmf",
"(",
"k",
",",
"n",
",",
"p",
")",
":",
"return",
"stats",
".",
"binom",
".",
"pmf",
"(",
"k",
",",
"n",
",",
"p",
")"
] | evaluates the binomial pmf . | train | true |
54,193 | def dict_to_str(args, sep=u'&'):
t = []
for k in args.keys():
t.append(((str(k) + u'=') + urllib.quote(str((args[k] or u'')))))
return sep.join(t)
| [
"def",
"dict_to_str",
"(",
"args",
",",
"sep",
"=",
"u'&'",
")",
":",
"t",
"=",
"[",
"]",
"for",
"k",
"in",
"args",
".",
"keys",
"(",
")",
":",
"t",
".",
"append",
"(",
"(",
"(",
"str",
"(",
"k",
")",
"+",
"u'='",
")",
"+",
"urllib",
".",
... | converts a dictionary to url . | train | false |
54,194 | def unbare_repo(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if self.repo.bare:
raise InvalidGitRepositoryError(("Method '%s' cannot operate on bare repositories" % func.__name__))
return func(self, *args, **kwargs)
return wrapper
| [
"def",
"unbare_repo",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"self",
".",
"repo",
".",
"bare",
":",
"raise",
"InvalidGitRepositoryError",
"(",
"(",
... | methods with this decorator raise invalidgitrepositoryerror if they encounter a bare repository . | train | true |
54,195 | def calc_dihedral(v1, v2, v3, v4):
ab = (v1 - v2)
cb = (v3 - v2)
db = (v4 - v3)
u = (ab ** cb)
v = (db ** cb)
w = (u ** v)
angle = u.angle(v)
try:
if (cb.angle(w) > 0.001):
angle = (- angle)
except ZeroDivisionError:
pass
return angle
| [
"def",
"calc_dihedral",
"(",
"v1",
",",
"v2",
",",
"v3",
",",
"v4",
")",
":",
"ab",
"=",
"(",
"v1",
"-",
"v2",
")",
"cb",
"=",
"(",
"v3",
"-",
"v2",
")",
"db",
"=",
"(",
"v4",
"-",
"v3",
")",
"u",
"=",
"(",
"ab",
"**",
"cb",
")",
"v",
... | calculate the dihedral angle between 4 vectors representing 4 connected points . | train | false |
54,197 | @register.filter(name='user_which_groups')
def user_which_group(user, member):
member = getattr(user, member)
names = [members.name for members in member.all()]
return ','.join(names)
| [
"@",
"register",
".",
"filter",
"(",
"name",
"=",
"'user_which_groups'",
")",
"def",
"user_which_group",
"(",
"user",
",",
"member",
")",
":",
"member",
"=",
"getattr",
"(",
"user",
",",
"member",
")",
"names",
"=",
"[",
"members",
".",
"name",
"for",
... | instance is a user object . | train | false |
54,198 | def _simplify_variable_coeff(sol, syms, func, funcarg):
eta = Symbol('eta')
if (len(syms) == 1):
sym = syms.pop()
final = sol.subs(sym, func(funcarg))
else:
fname = func.__name__
for (key, sym) in enumerate(syms):
tempfun = Function((fname + str(key)))
final = sol.subs(sym, func(funcarg))
return simplify(final.subs(eta, funcarg))
| [
"def",
"_simplify_variable_coeff",
"(",
"sol",
",",
"syms",
",",
"func",
",",
"funcarg",
")",
":",
"eta",
"=",
"Symbol",
"(",
"'eta'",
")",
"if",
"(",
"len",
"(",
"syms",
")",
"==",
"1",
")",
":",
"sym",
"=",
"syms",
".",
"pop",
"(",
")",
"final"... | helper function to replace constants by functions in 1st_linear_variable_coeff . | train | false |
54,199 | def ex(e):
e_message = u''
if ((not e) or (not e.args)):
return e_message
for arg in e.args:
if (arg is not None):
if isinstance(arg, (str, unicode)):
fixed_arg = fixStupidEncodings(arg, True)
else:
try:
fixed_arg = (u'error ' + fixStupidEncodings(str(arg), True))
except:
fixed_arg = None
if fixed_arg:
if (not e_message):
e_message = fixed_arg
else:
e_message = ((e_message + ' : ') + fixed_arg)
return e_message
| [
"def",
"ex",
"(",
"e",
")",
":",
"e_message",
"=",
"u''",
"if",
"(",
"(",
"not",
"e",
")",
"or",
"(",
"not",
"e",
".",
"args",
")",
")",
":",
"return",
"e_message",
"for",
"arg",
"in",
"e",
".",
"args",
":",
"if",
"(",
"arg",
"is",
"not",
"... | returns a unicode string from the exception text if it exists . | train | false |
54,200 | def _compile_from_parse_tree(root_node, *a, **kw):
return _CompiledGrammar(root_node, *a, **kw)
| [
"def",
"_compile_from_parse_tree",
"(",
"root_node",
",",
"*",
"a",
",",
"**",
"kw",
")",
":",
"return",
"_CompiledGrammar",
"(",
"root_node",
",",
"*",
"a",
",",
"**",
"kw",
")"
] | compile grammar . | train | false |
54,201 | def setvcpus(vm_, vcpus, config=False):
if (vm_state(vm_)[vm_] != 'shutdown'):
return False
dom = _get_domain(vm_)
flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM
if config:
flags = (flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG)
ret1 = dom.setVcpusFlags(vcpus, flags)
ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
return (ret1 == ret2 == 0)
| [
"def",
"setvcpus",
"(",
"vm_",
",",
"vcpus",
",",
"config",
"=",
"False",
")",
":",
"if",
"(",
"vm_state",
"(",
"vm_",
")",
"[",
"vm_",
"]",
"!=",
"'shutdown'",
")",
":",
"return",
"False",
"dom",
"=",
"_get_domain",
"(",
"vm_",
")",
"flags",
"=",
... | changes the amount of vcpus allocated to vm . | train | false |
54,203 | def _parse_circ_entry(entry):
if ('=' in entry):
(fingerprint, nickname) = entry.split('=')
elif ('~' in entry):
(fingerprint, nickname) = entry.split('~')
elif (entry[0] == '$'):
(fingerprint, nickname) = (entry, None)
else:
(fingerprint, nickname) = (None, entry)
if (fingerprint is not None):
if (not stem.util.tor_tools.is_valid_fingerprint(fingerprint, True)):
raise stem.ProtocolError(('Fingerprint in the circuit path is malformed (%s)' % fingerprint))
fingerprint = fingerprint[1:]
if ((nickname is not None) and (not stem.util.tor_tools.is_valid_nickname(nickname))):
raise stem.ProtocolError(('Nickname in the circuit path is malformed (%s)' % nickname))
return (fingerprint, nickname)
| [
"def",
"_parse_circ_entry",
"(",
"entry",
")",
":",
"if",
"(",
"'='",
"in",
"entry",
")",
":",
"(",
"fingerprint",
",",
"nickname",
")",
"=",
"entry",
".",
"split",
"(",
"'='",
")",
"elif",
"(",
"'~'",
"in",
"entry",
")",
":",
"(",
"fingerprint",
"... | parses a single relays longname or serverid . | train | false |
54,205 | def libvlc_media_set_user_data(p_md, p_new_user_data):
f = (_Cfunctions.get('libvlc_media_set_user_data', None) or _Cfunction('libvlc_media_set_user_data', ((1,), (1,)), None, None, Media, ctypes.c_void_p))
return f(p_md, p_new_user_data)
| [
"def",
"libvlc_media_set_user_data",
"(",
"p_md",
",",
"p_new_user_data",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_set_user_data'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_set_user_data'",
",",
"(",
"(",
"1",
",",... | sets media descriptors user_data . | train | true |
54,206 | @requires_pyopengl()
def test_import_vispy_pyopengl():
allmodnames = loaded_vispy_modules('vispy.gloo.gl.pyopengl2', 2, True)
assert_in('OpenGL', allmodnames)
| [
"@",
"requires_pyopengl",
"(",
")",
"def",
"test_import_vispy_pyopengl",
"(",
")",
":",
"allmodnames",
"=",
"loaded_vispy_modules",
"(",
"'vispy.gloo.gl.pyopengl2'",
",",
"2",
",",
"True",
")",
"assert_in",
"(",
"'OpenGL'",
",",
"allmodnames",
")"
] | importing vispy . | train | false |
54,207 | def ComputeErrorRate(error_count, truth_count):
if (truth_count == 0):
truth_count = 1
error_count = 1
elif (error_count > truth_count):
error_count = truth_count
return ((error_count * 100.0) / truth_count)
| [
"def",
"ComputeErrorRate",
"(",
"error_count",
",",
"truth_count",
")",
":",
"if",
"(",
"truth_count",
"==",
"0",
")",
":",
"truth_count",
"=",
"1",
"error_count",
"=",
"1",
"elif",
"(",
"error_count",
">",
"truth_count",
")",
":",
"error_count",
"=",
"tru... | returns a sanitized percent error rate from the raw counts . | train | false |
54,208 | def save_translations(key):
if (not hasattr(_to_save, 'translations')):
return
for trans in _to_save.translations.get(key, []):
is_new = (trans.autoid is None)
trans.save(force_insert=is_new, force_update=(not is_new))
if (key in _to_save.translations):
del _to_save.translations[key]
| [
"def",
"save_translations",
"(",
"key",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"_to_save",
",",
"'translations'",
")",
")",
":",
"return",
"for",
"trans",
"in",
"_to_save",
".",
"translations",
".",
"get",
"(",
"key",
",",
"[",
"]",
")",
":",
"i... | for a given key . | train | false |
54,209 | def find_program_variables(code):
vars = {}
lines = code.split('\n')
for line in lines:
m = re.match((('\\s*' + re_prog_var_declaration) + '\\s*(=|;)'), line)
if (m is not None):
(vtype, dtype, names) = m.groups()[:3]
for name in names.split(','):
vars[name.strip()] = (vtype, dtype)
return vars
| [
"def",
"find_program_variables",
"(",
"code",
")",
":",
"vars",
"=",
"{",
"}",
"lines",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"m",
"=",
"re",
".",
"match",
"(",
"(",
"(",
"'\\\\s*'",
"+",
"re_prog_var_declar... | return a dict describing program variables:: {var_name: . | train | true |
54,210 | @not_implemented_for('directed')
def biconnected_component_edges(G):
for comp in _biconnected_dfs(G, components=True):
(yield comp)
| [
"@",
"not_implemented_for",
"(",
"'directed'",
")",
"def",
"biconnected_component_edges",
"(",
"G",
")",
":",
"for",
"comp",
"in",
"_biconnected_dfs",
"(",
"G",
",",
"components",
"=",
"True",
")",
":",
"(",
"yield",
"comp",
")"
] | return a generator of lists of edges . | train | false |
54,211 | def class_result(classname):
def wrap_errcheck(result, func, arguments):
if (result is None):
return None
return classname(result)
return wrap_errcheck
| [
"def",
"class_result",
"(",
"classname",
")",
":",
"def",
"wrap_errcheck",
"(",
"result",
",",
"func",
",",
"arguments",
")",
":",
"if",
"(",
"result",
"is",
"None",
")",
":",
"return",
"None",
"return",
"classname",
"(",
"result",
")",
"return",
"wrap_e... | errcheck function . | train | true |
54,213 | def _makeGetterFactory(url, factoryFactory, contextFactory=None, *args, **kwargs):
uri = URI.fromBytes(url)
factory = factoryFactory(url, *args, **kwargs)
if (uri.scheme == 'https'):
from twisted.internet import ssl
if (contextFactory is None):
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(nativeString(uri.host), uri.port, factory, contextFactory)
else:
reactor.connectTCP(nativeString(uri.host), uri.port, factory)
return factory
| [
"def",
"_makeGetterFactory",
"(",
"url",
",",
"factoryFactory",
",",
"contextFactory",
"=",
"None",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"uri",
"=",
"URI",
".",
"fromBytes",
"(",
"url",
")",
"factory",
"=",
"factoryFactory",
"(",
"url",
",",
... | create and connect an http page getting factory . | train | false |
54,214 | def define_rate(name, description, unit_seconds=1, manager=counters):
counter = _RateCounter(name, description, unit_seconds)
manager.register(counter)
return counter
| [
"def",
"define_rate",
"(",
"name",
",",
"description",
",",
"unit_seconds",
"=",
"1",
",",
"manager",
"=",
"counters",
")",
":",
"counter",
"=",
"_RateCounter",
"(",
"name",
",",
"description",
",",
"unit_seconds",
")",
"manager",
".",
"register",
"(",
"co... | creates a performance counter which tracks some rate at which a value accumulates over the course of the program . | train | false |
54,215 | def review_request_closed_cb(sender, user, review_request, type, **kwargs):
siteconfig = SiteConfiguration.objects.get_current()
if siteconfig.get(u'mail_send_review_close_mail'):
mail_review_request(review_request, user, close_type=type)
| [
"def",
"review_request_closed_cb",
"(",
"sender",
",",
"user",
",",
"review_request",
",",
"type",
",",
"**",
"kwargs",
")",
":",
"siteconfig",
"=",
"SiteConfiguration",
".",
"objects",
".",
"get_current",
"(",
")",
"if",
"siteconfig",
".",
"get",
"(",
"u'ma... | send e-mail when a review request is closed . | train | false |
54,216 | def load_list_of_roles(ds, play, current_role_path=None, variable_manager=None, loader=None):
from ansible.playbook.role.include import RoleInclude
assert isinstance(ds, list)
roles = []
for role_def in ds:
i = RoleInclude.load(role_def, play=play, current_role_path=current_role_path, variable_manager=variable_manager, loader=loader)
roles.append(i)
return roles
| [
"def",
"load_list_of_roles",
"(",
"ds",
",",
"play",
",",
"current_role_path",
"=",
"None",
",",
"variable_manager",
"=",
"None",
",",
"loader",
"=",
"None",
")",
":",
"from",
"ansible",
".",
"playbook",
".",
"role",
".",
"include",
"import",
"RoleInclude",
... | loads and returns a list of roleinclude objects from the datastructure list of role definitions . | train | false |
54,217 | def filter_sff_file(flowgrams, header, filter_list, out_fh):
write_sff_header(header, out_fh)
l = 0
for f in flowgrams:
passed = True
for filter in filter_list:
passed = (passed and filter(f))
if (not passed):
break
if passed:
out_fh.write((f.createFlowHeader() + '\n'))
l += 1
return l
| [
"def",
"filter_sff_file",
"(",
"flowgrams",
",",
"header",
",",
"filter_list",
",",
"out_fh",
")",
":",
"write_sff_header",
"(",
"header",
",",
"out_fh",
")",
"l",
"=",
"0",
"for",
"f",
"in",
"flowgrams",
":",
"passed",
"=",
"True",
"for",
"filter",
"in"... | filters all flowgrams in handle with filter . | train | false |
54,219 | def apply_policy(policy, r, name, sub):
if isinstance(policy, (list, tuple)):
ret = ''
for sub_policy in policy:
ret += sub_policy(r, name, sub)
return ret
return policy(r, name, sub)
| [
"def",
"apply_policy",
"(",
"policy",
",",
"r",
",",
"name",
",",
"sub",
")",
":",
"if",
"isinstance",
"(",
"policy",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"ret",
"=",
"''",
"for",
"sub_policy",
"in",
"policy",
":",
"ret",
"+=",
"sub_polic... | apply the list of policies to name . | train | false |
54,221 | def _StrictParseLogEntry(entry, clean_message=True):
(magic, level, timestamp, message) = entry.split(' ', 3)
if (magic != 'LOG'):
raise ValueError()
(timestamp, level) = (int(timestamp), int(level))
if (level not in LOG_LEVELS):
raise ValueError()
return (timestamp, level, _Clean(message), (None if clean_message else message))
| [
"def",
"_StrictParseLogEntry",
"(",
"entry",
",",
"clean_message",
"=",
"True",
")",
":",
"(",
"magic",
",",
"level",
",",
"timestamp",
",",
"message",
")",
"=",
"entry",
".",
"split",
"(",
"' '",
",",
"3",
")",
"if",
"(",
"magic",
"!=",
"'LOG'",
")"... | parses a single log entry emitted by app_logging . | train | false |
54,222 | def remove_arrays(code, count=1):
res = ''
last = ''
replacements = {}
for e in bracket_split(code, ['[]']):
if (e[0] == '['):
if is_array(last):
name = (ARRAY_LVAL % count)
res += (' ' + name)
replacements[name] = e
count += 1
else:
(cand, new_replacements, count) = remove_arrays(e[1:(-1)], count)
res += ('[%s]' % cand)
replacements.update(new_replacements)
else:
res += e
last = e
return (res, replacements, count)
| [
"def",
"remove_arrays",
"(",
"code",
",",
"count",
"=",
"1",
")",
":",
"res",
"=",
"''",
"last",
"=",
"''",
"replacements",
"=",
"{",
"}",
"for",
"e",
"in",
"bracket_split",
"(",
"code",
",",
"[",
"'[]'",
"]",
")",
":",
"if",
"(",
"e",
"[",
"0"... | removes arrays and replaces them with array_lvals returns new code and replacement dict *note* has to be called after remove objects . | train | true |
54,223 | def _toCSSname(DOMname):
def _doDOMtoCSSname2(m):
return ('-' + m.group(0).lower())
return _reDOMtoCSSname.sub(_doDOMtoCSSname2, DOMname)
| [
"def",
"_toCSSname",
"(",
"DOMname",
")",
":",
"def",
"_doDOMtoCSSname2",
"(",
"m",
")",
":",
"return",
"(",
"'-'",
"+",
"m",
".",
"group",
"(",
"0",
")",
".",
"lower",
"(",
")",
")",
"return",
"_reDOMtoCSSname",
".",
"sub",
"(",
"_doDOMtoCSSname2",
... | return cssname for given domname e . | train | false |
54,225 | def _FormatFirstToken(first_token, indent_depth, prev_uwline, final_lines):
first_token.AddWhitespacePrefix(_CalculateNumberOfNewlines(first_token, indent_depth, prev_uwline, final_lines), indent_level=indent_depth)
| [
"def",
"_FormatFirstToken",
"(",
"first_token",
",",
"indent_depth",
",",
"prev_uwline",
",",
"final_lines",
")",
":",
"first_token",
".",
"AddWhitespacePrefix",
"(",
"_CalculateNumberOfNewlines",
"(",
"first_token",
",",
"indent_depth",
",",
"prev_uwline",
",",
"fina... | format the first token in the unwrapped line . | train | false |
54,226 | def to_seconds(time_string):
elts = time_string.split(':')
if (len(elts) == 1):
return time_string
return str(((int(elts[0]) * 60) + float(elts[1])))
| [
"def",
"to_seconds",
"(",
"time_string",
")",
":",
"elts",
"=",
"time_string",
".",
"split",
"(",
"':'",
")",
"if",
"(",
"len",
"(",
"elts",
")",
"==",
"1",
")",
":",
"return",
"time_string",
"return",
"str",
"(",
"(",
"(",
"int",
"(",
"elts",
"[",... | converts a string in m+:ss . | train | false |
54,227 | def svm_read_problem(data_file_name):
prob_y = []
prob_x = []
for line in open(data_file_name):
line = line.split(None, 1)
if (len(line) == 1):
line += ['']
(label, features) = line
xi = {}
for e in features.split():
(ind, val) = e.split(':')
xi[int(ind)] = float(val)
prob_y += [float(label)]
prob_x += [xi]
return (prob_y, prob_x)
| [
"def",
"svm_read_problem",
"(",
"data_file_name",
")",
":",
"prob_y",
"=",
"[",
"]",
"prob_x",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"data_file_name",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"None",
",",
"1",
")",
"if",
"(",
"l... | svm_read_problem -> [y . | train | false |
54,228 | def boto_supports_associate_public_ip_address(ec2):
try:
network_interface = boto.ec2.networkinterface.NetworkInterfaceSpecification()
getattr(network_interface, 'associate_public_ip_address')
return True
except AttributeError:
return False
| [
"def",
"boto_supports_associate_public_ip_address",
"(",
"ec2",
")",
":",
"try",
":",
"network_interface",
"=",
"boto",
".",
"ec2",
".",
"networkinterface",
".",
"NetworkInterfaceSpecification",
"(",
")",
"getattr",
"(",
"network_interface",
",",
"'associate_public_ip_a... | check if boto library has associate_public_ip_address in the networkinterfacespecification class . | train | false |
54,230 | @register.filter
def xssafe(value):
return jinja2.Markup(value)
| [
"@",
"register",
".",
"filter",
"def",
"xssafe",
"(",
"value",
")",
":",
"return",
"jinja2",
".",
"Markup",
"(",
"value",
")"
] | like |safe but for strings with interpolation . | train | false |
54,232 | def delete_instance_profile(name, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if (not instance_profile_exists(name, region, key, keyid, profile)):
return True
try:
conn.delete_instance_profile(name)
log.info('Deleted {0} instance profile.'.format(name))
except boto.exception.BotoServerError as e:
log.debug(e)
msg = 'Failed to delete {0} instance profile.'
log.error(msg.format(name))
return False
return True
| [
"def",
"delete_instance_profile",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",... | delete an instance profile . | train | true |
54,234 | def get_configured_hadoop_version():
return hadoopcli().version.lower()
| [
"def",
"get_configured_hadoop_version",
"(",
")",
":",
"return",
"hadoopcli",
"(",
")",
".",
"version",
".",
"lower",
"(",
")"
] | cdh4 has a slightly different syntax for interacting with hdfs via the command line . | train | false |
54,235 | def _replace_conditional(match, string):
conditional_match = _CONDITIONAL.search(string)
while conditional_match:
start = conditional_match.start()
end = _find_closing_brace(string, (start + 4))
args = _split_conditional(string[(start + 4):(end - 1)])
rv = ''
if match.group(int(conditional_match.group(1))):
rv = unescape(_replace_conditional(match, args[0]))
elif (len(args) > 1):
rv = unescape(_replace_conditional(match, args[1]))
string = ((string[:start] + rv) + string[end:])
conditional_match = _CONDITIONAL.search(string)
return string
| [
"def",
"_replace_conditional",
"(",
"match",
",",
"string",
")",
":",
"conditional_match",
"=",
"_CONDITIONAL",
".",
"search",
"(",
"string",
")",
"while",
"conditional_match",
":",
"start",
"=",
"conditional_match",
".",
"start",
"(",
")",
"end",
"=",
"_find_... | replaces a conditional match in a transformation . | train | false |
54,236 | def is_image_visible(context, image, status=None):
if context.is_admin:
return True
if (image['owner'] is None):
return True
if (image['visibility'] in ['public', 'community']):
return True
if (context.owner is not None):
if (context.owner == image['owner']):
return True
if ('shared' == image['visibility']):
members = image_member_find(context, image_id=image['id'], member=context.owner, status=status)
if members:
return True
return False
| [
"def",
"is_image_visible",
"(",
"context",
",",
"image",
",",
"status",
"=",
"None",
")",
":",
"if",
"context",
".",
"is_admin",
":",
"return",
"True",
"if",
"(",
"image",
"[",
"'owner'",
"]",
"is",
"None",
")",
":",
"return",
"True",
"if",
"(",
"ima... | return true if the image is visible in this context . | train | false |
54,237 | def assert_similar_pages(first, second, ratio=0.9, msg=None):
lines_a = set([l.strip() for l in first.split('\n')])
lines_b = set([l.strip() for l in second.split('\n')])
common = lines_a.intersection(lines_b)
similarity = ((1.0 * len(common)) / max(len(lines_a), len(lines_b)))
nose.tools.assert_true((similarity >= ratio), msg)
| [
"def",
"assert_similar_pages",
"(",
"first",
",",
"second",
",",
"ratio",
"=",
"0.9",
",",
"msg",
"=",
"None",
")",
":",
"lines_a",
"=",
"set",
"(",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"first",
".",
"split",
"(",
"'\\n'",
")",
"]"... | asserts that most of the lines in the two pages are identical . | train | false |
54,238 | def create_request(url=None, method=None, body=None):
if ((not url) or (not method)):
raise MissingRequestArgs
return tornado.httpclient.HTTPRequest(url=url, method=method, body=body, validate_cert=False, request_timeout=hermes_constants.REQUEST_TIMEOUT)
| [
"def",
"create_request",
"(",
"url",
"=",
"None",
",",
"method",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"(",
"(",
"not",
"url",
")",
"or",
"(",
"not",
"method",
")",
")",
":",
"raise",
"MissingRequestArgs",
"return",
"tornado",
".",
... | creates a tornado . | train | false |
54,239 | def run_cmd(pl, cmd, stdin=None, strip=True):
try:
p = Popen(cmd, shell=False, stdout=PIPE, stdin=PIPE)
except OSError as e:
pl.exception(u'Could not execute command ({0}): {1}', e, cmd)
return None
else:
(stdout, err) = p.communicate((stdin if (stdin is None) else stdin.encode(get_preferred_output_encoding())))
stdout = stdout.decode(get_preferred_input_encoding())
return (stdout.strip() if strip else stdout)
| [
"def",
"run_cmd",
"(",
"pl",
",",
"cmd",
",",
"stdin",
"=",
"None",
",",
"strip",
"=",
"True",
")",
":",
"try",
":",
"p",
"=",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"stdout",
"=",
"PIPE",
",",
"stdin",
"=",
"PIPE",
")",
"except"... | run command and return its stdout . | train | false |
54,240 | def check_key_expired(key, node, url):
if (key in node.private_link_keys_deleted):
url = furl(url).add({'status': 'expired'}).url
return url
| [
"def",
"check_key_expired",
"(",
"key",
",",
"node",
",",
"url",
")",
":",
"if",
"(",
"key",
"in",
"node",
".",
"private_link_keys_deleted",
")",
":",
"url",
"=",
"furl",
"(",
"url",
")",
".",
"add",
"(",
"{",
"'status'",
":",
"'expired'",
"}",
")",
... | check if key expired if is return url with args so it will push status message else return url . | train | false |
54,241 | def search_lxc_bridge():
return search_lxc_bridges()[0]
| [
"def",
"search_lxc_bridge",
"(",
")",
":",
"return",
"search_lxc_bridges",
"(",
")",
"[",
"0",
"]"
] | search the first bridge which is potentially available as lxc bridge cli example: . | train | false |
54,243 | def already_backported(branch, since_tag=None):
if (since_tag is None):
since_tag = check_output(['git', 'describe', branch, '--abbrev=0']).decode('utf8').strip()
cmd = ['git', 'log', ('%s..%s' % (since_tag, branch)), '--oneline']
lines = check_output(cmd).decode('utf8')
return set((int(num) for num in backport_re.findall(lines)))
| [
"def",
"already_backported",
"(",
"branch",
",",
"since_tag",
"=",
"None",
")",
":",
"if",
"(",
"since_tag",
"is",
"None",
")",
":",
"since_tag",
"=",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
",",
"branch",
",",
"'--abbrev=0'",
"]",
")",
"."... | return set of prs that have been backported already . | train | false |
54,244 | def _generate_indices(f, values=False):
axes = f.axes
if values:
axes = [lrange(len(a)) for a in axes]
return itertools.product(*axes)
| [
"def",
"_generate_indices",
"(",
"f",
",",
"values",
"=",
"False",
")",
":",
"axes",
"=",
"f",
".",
"axes",
"if",
"values",
":",
"axes",
"=",
"[",
"lrange",
"(",
"len",
"(",
"a",
")",
")",
"for",
"a",
"in",
"axes",
"]",
"return",
"itertools",
"."... | generate the indicies if values is true . | train | false |
54,245 | def read_file_as_root(file_path):
try:
(out, _err) = execute('cat', file_path, run_as_root=True)
return out
except processutils.ProcessExecutionError:
raise exception.FileNotFound(file_path=file_path)
| [
"def",
"read_file_as_root",
"(",
"file_path",
")",
":",
"try",
":",
"(",
"out",
",",
"_err",
")",
"=",
"execute",
"(",
"'cat'",
",",
"file_path",
",",
"run_as_root",
"=",
"True",
")",
"return",
"out",
"except",
"processutils",
".",
"ProcessExecutionError",
... | secure helper to read file as root . | train | false |
54,247 | def locale_list(request):
locales = Locale.objects.all()
return render(request, 'wiki/locale_list.html', {'locales': locales})
| [
"def",
"locale_list",
"(",
"request",
")",
":",
"locales",
"=",
"Locale",
".",
"objects",
".",
"all",
"(",
")",
"return",
"render",
"(",
"request",
",",
"'wiki/locale_list.html'",
",",
"{",
"'locales'",
":",
"locales",
"}",
")"
] | list the support kb locales . | train | false |
54,249 | def set_priority_js():
wptable = s3db.cap_warning_priority
rows = db(wptable).select(wptable.name, wptable.urgency, wptable.severity, wptable.certainty, wptable.color_code, orderby=wptable.name)
from gluon.serializers import json as jsons
from s3 import s3_str
p_settings = [(s3_str(T(r.name)), r.urgency, r.severity, r.certainty, r.color_code) for r in rows]
priority_conf = s3_str(('S3.cap_priorities=%s' % jsons(p_settings)))
js_global = s3.js_global
if (not (priority_conf in js_global)):
js_global.append(priority_conf)
return
| [
"def",
"set_priority_js",
"(",
")",
":",
"wptable",
"=",
"s3db",
".",
"cap_warning_priority",
"rows",
"=",
"db",
"(",
"wptable",
")",
".",
"select",
"(",
"wptable",
".",
"name",
",",
"wptable",
".",
"urgency",
",",
"wptable",
".",
"severity",
",",
"wptab... | output json for priority field . | train | false |
54,250 | def _replace_locals(tok):
(toknum, tokval) = tok
if ((toknum == tokenize.OP) and (tokval == '@')):
return (tokenize.OP, _LOCAL_TAG)
return (toknum, tokval)
| [
"def",
"_replace_locals",
"(",
"tok",
")",
":",
"(",
"toknum",
",",
"tokval",
")",
"=",
"tok",
"if",
"(",
"(",
"toknum",
"==",
"tokenize",
".",
"OP",
")",
"and",
"(",
"tokval",
"==",
"'@'",
")",
")",
":",
"return",
"(",
"tokenize",
".",
"OP",
","... | replace local variables with a syntactically valid name . | train | true |
54,251 | def localhost():
global _localhost
if (_localhost is None):
_localhost = socket.gethostbyname('localhost')
return _localhost
| [
"def",
"localhost",
"(",
")",
":",
"global",
"_localhost",
"if",
"(",
"_localhost",
"is",
"None",
")",
":",
"_localhost",
"=",
"socket",
".",
"gethostbyname",
"(",
"'localhost'",
")",
"return",
"_localhost"
] | return the ip address of the magic hostname localhost . | train | false |
54,252 | def sqllist(lst):
if isinstance(lst, string_types):
return lst
else:
return ', '.join(lst)
| [
"def",
"sqllist",
"(",
"lst",
")",
":",
"if",
"isinstance",
"(",
"lst",
",",
"string_types",
")",
":",
"return",
"lst",
"else",
":",
"return",
"', '",
".",
"join",
"(",
"lst",
")"
] | converts the arguments for use in something like a where clause . | train | false |
54,254 | def filter_re_search(val, pattern):
if (not isinstance(val, basestring)):
return val
result = re.search(pattern, val)
if result:
return result.group(0)
return u''
| [
"def",
"filter_re_search",
"(",
"val",
",",
"pattern",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"val",
",",
"basestring",
")",
")",
":",
"return",
"val",
"result",
"=",
"re",
".",
"search",
"(",
"pattern",
",",
"val",
")",
"if",
"result",
":",
... | perform a search for given regexp pattern . | train | false |
54,255 | @register.simple_tag()
def product_first_image(product, size, method='crop'):
all_images = product.images.all()
main_image = (all_images[0].image if all_images else None)
return get_thumbnail(main_image, size, method)
| [
"@",
"register",
".",
"simple_tag",
"(",
")",
"def",
"product_first_image",
"(",
"product",
",",
"size",
",",
"method",
"=",
"'crop'",
")",
":",
"all_images",
"=",
"product",
".",
"images",
".",
"all",
"(",
")",
"main_image",
"=",
"(",
"all_images",
"[",... | returns main product image . | train | false |
54,257 | def after_all(context):
dbutils.close_cn(context.cn)
dbutils.drop_db(context.conf[u'host'], context.conf[u'user'], context.conf[u'pass'], context.conf[u'dbname'])
for (k, v) in context.pgenv.items():
if ((k in os.environ) and (v is None)):
del os.environ[k]
elif v:
os.environ[k] = v
| [
"def",
"after_all",
"(",
"context",
")",
":",
"dbutils",
".",
"close_cn",
"(",
"context",
".",
"cn",
")",
"dbutils",
".",
"drop_db",
"(",
"context",
".",
"conf",
"[",
"u'host'",
"]",
",",
"context",
".",
"conf",
"[",
"u'user'",
"]",
",",
"context",
"... | unset env parameters . | train | false |
54,258 | def xml_format(a):
if isinstance(a, basestring):
return ('"%s"' % encode_entities(a))
if isinstance(a, bool):
return ('"%s"' % ('no', 'yes')[int(a)])
if isinstance(a, (int, long)):
return ('"%s"' % a)
if isinstance(a, float):
return ('"%s"' % round(a, 5))
if isinstance(a, type(None)):
return '""'
if isinstance(a, Date):
return ('"%s"' % str(a))
if isinstance(a, datetime.datetime):
return ('"%s"' % str(date(mktime(a.timetuple()))))
| [
"def",
"xml_format",
"(",
"a",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"basestring",
")",
":",
"return",
"(",
"'\"%s\"'",
"%",
"encode_entities",
"(",
"a",
")",
")",
"if",
"isinstance",
"(",
"a",
",",
"bool",
")",
":",
"return",
"(",
"'\"%s\"'",... | returns the given attribute as a quoted unicode string . | train | false |
54,259 | def nn_words(table, wordvecs, query, k=10):
keys = table.keys()
qf = table[query]
scores = numpy.dot(qf, wordvecs.T).flatten()
sorted_args = numpy.argsort(scores)[::(-1)]
words = [keys[a] for a in sorted_args[:k]]
print ('QUERY: ' + query)
print 'NEAREST: '
for (i, w) in enumerate(words):
print w
| [
"def",
"nn_words",
"(",
"table",
",",
"wordvecs",
",",
"query",
",",
"k",
"=",
"10",
")",
":",
"keys",
"=",
"table",
".",
"keys",
"(",
")",
"qf",
"=",
"table",
"[",
"query",
"]",
"scores",
"=",
"numpy",
".",
"dot",
"(",
"qf",
",",
"wordvecs",
"... | get the nearest neighbour words . | train | false |
54,260 | def extents_may_overlap(context, builder, a_start, a_end, b_start, b_end):
may_overlap = builder.and_(builder.icmp_unsigned('<', a_start, b_end), builder.icmp_unsigned('<', b_start, a_end))
return may_overlap
| [
"def",
"extents_may_overlap",
"(",
"context",
",",
"builder",
",",
"a_start",
",",
"a_end",
",",
"b_start",
",",
"b_end",
")",
":",
"may_overlap",
"=",
"builder",
".",
"and_",
"(",
"builder",
".",
"icmp_unsigned",
"(",
"'<'",
",",
"a_start",
",",
"b_end",
... | whether two memory extents [a_start . | train | false |
54,261 | @contextlib.contextmanager
def import_state(**kwargs):
originals = {}
try:
for (attr, default) in (('meta_path', []), ('path', []), ('path_hooks', []), ('path_importer_cache', {})):
originals[attr] = getattr(sys, attr)
if (attr in kwargs):
new_value = kwargs[attr]
del kwargs[attr]
else:
new_value = default
setattr(sys, attr, new_value)
if len(kwargs):
raise ValueError('unrecognized arguments: {0}'.format(kwargs.keys()))
(yield)
finally:
for (attr, value) in originals.items():
setattr(sys, attr, value)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"import_state",
"(",
"**",
"kwargs",
")",
":",
"originals",
"=",
"{",
"}",
"try",
":",
"for",
"(",
"attr",
",",
"default",
")",
"in",
"(",
"(",
"'meta_path'",
",",
"[",
"]",
")",
",",
"(",
"'path'",
... | context manager to manage the various importers and stored state in the sys module . | train | false |
54,262 | def find_undeclared_variables(ast):
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers
| [
"def",
"find_undeclared_variables",
"(",
"ast",
")",
":",
"codegen",
"=",
"TrackingCodeGenerator",
"(",
"ast",
".",
"environment",
")",
"codegen",
".",
"visit",
"(",
"ast",
")",
"return",
"codegen",
".",
"undeclared_identifiers"
] | returns a set of all variables in the ast that will be looked up from the context at runtime . | train | true |
54,263 | @none_if_empty
def blobproperty_from_base64(value):
decoded_value = base64.b64decode(value)
return datastore_types.Blob(decoded_value)
| [
"@",
"none_if_empty",
"def",
"blobproperty_from_base64",
"(",
"value",
")",
":",
"decoded_value",
"=",
"base64",
".",
"b64decode",
"(",
"value",
")",
"return",
"datastore_types",
".",
"Blob",
"(",
"decoded_value",
")"
] | return a datastore blob property containing the base64 decoded value . | train | false |
54,264 | def get_order_args():
orders = {}
for arg in request.args:
re_match = re.findall('_oc_(.*)', arg)
if re_match:
orders[re_match[0]] = (request.args.get(arg), request.args.get(('_od_' + re_match[0])))
return orders
| [
"def",
"get_order_args",
"(",
")",
":",
"orders",
"=",
"{",
"}",
"for",
"arg",
"in",
"request",
".",
"args",
":",
"re_match",
"=",
"re",
".",
"findall",
"(",
"'_oc_(.*)'",
",",
"arg",
")",
"if",
"re_match",
":",
"orders",
"[",
"re_match",
"[",
"0",
... | get order arguments . | train | true |
54,267 | def autodiscover():
global _RACE_PROTECTION
if _RACE_PROTECTION:
return
_RACE_PROTECTION = True
try:
return filter(None, [find_related_module(app, 'tasks') for app in settings.INSTALLED_APPS])
finally:
_RACE_PROTECTION = False
| [
"def",
"autodiscover",
"(",
")",
":",
"global",
"_RACE_PROTECTION",
"if",
"_RACE_PROTECTION",
":",
"return",
"_RACE_PROTECTION",
"=",
"True",
"try",
":",
"return",
"filter",
"(",
"None",
",",
"[",
"find_related_module",
"(",
"app",
",",
"'tasks'",
")",
"for",
... | include tasks for all applications in installed_apps . | train | true |
54,269 | def is_frozen():
try:
base_path = sys._MEIPASS
except Exception:
return False
return True
| [
"def",
"is_frozen",
"(",
")",
":",
"try",
":",
"base_path",
"=",
"sys",
".",
"_MEIPASS",
"except",
"Exception",
":",
"return",
"False",
"return",
"True"
] | return whether we are running in a frozen environment . | train | false |
54,270 | def factorialk(n, k, exact=True):
if exact:
if (n < (1 - k)):
return 0
if (n <= 0):
return 1
val = 1
for j in xrange(n, 0, (- k)):
val = (val * j)
return val
else:
raise NotImplementedError
| [
"def",
"factorialk",
"(",
"n",
",",
"k",
",",
"exact",
"=",
"True",
")",
":",
"if",
"exact",
":",
"if",
"(",
"n",
"<",
"(",
"1",
"-",
"k",
")",
")",
":",
"return",
"0",
"if",
"(",
"n",
"<=",
"0",
")",
":",
"return",
"1",
"val",
"=",
"1",
... | multifactorial of n of order k . | train | false |
54,271 | def resolve_model_string(model_string, default_app=None):
if isinstance(model_string, string_types):
try:
(app_label, model_name) = model_string.split(u'.')
except ValueError:
if (default_app is not None):
app_label = default_app
model_name = model_string
else:
raise ValueError(u'Can not resolve {0!r} into a model. Model names should be in the form app_label.model_name'.format(model_string), model_string)
return apps.get_model(app_label, model_name)
elif (isinstance(model_string, type) and issubclass(model_string, Model)):
return model_string
else:
raise ValueError(u'Can not resolve {0!r} into a model'.format(model_string), model_string)
| [
"def",
"resolve_model_string",
"(",
"model_string",
",",
"default_app",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"model_string",
",",
"string_types",
")",
":",
"try",
":",
"(",
"app_label",
",",
"model_name",
")",
"=",
"model_string",
".",
"split",
"(... | resolve an app_label . | train | false |
54,276 | def parse_query_part(part, query_classes={}, prefixes={}, default_class=query.SubstringQuery):
part = part.strip()
match = PARSE_QUERY_PART_REGEX.match(part)
assert match
negate = bool(match.group(1))
key = match.group(2)
term = match.group(3).replace('\\:', ':')
for (pre, query_class) in prefixes.items():
if term.startswith(pre):
return (key, term[len(pre):], query_class, negate)
query_class = query_classes.get(key, default_class)
return (key, term, query_class, negate)
| [
"def",
"parse_query_part",
"(",
"part",
",",
"query_classes",
"=",
"{",
"}",
",",
"prefixes",
"=",
"{",
"}",
",",
"default_class",
"=",
"query",
".",
"SubstringQuery",
")",
":",
"part",
"=",
"part",
".",
"strip",
"(",
")",
"match",
"=",
"PARSE_QUERY_PART... | parse a single *query part* . | train | false |
54,277 | @utils.arg('pool', metavar='<floating-ip-pool>', help=_('Name of Floating IP Pool. (Optional)'), nargs='?', default=None)
@deprecated_network
def do_floating_ip_create(cs, args):
_print_floating_ip_list([cs.floating_ips.create(pool=args.pool)])
| [
"@",
"utils",
".",
"arg",
"(",
"'pool'",
",",
"metavar",
"=",
"'<floating-ip-pool>'",
",",
"help",
"=",
"_",
"(",
"'Name of Floating IP Pool. (Optional)'",
")",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"None",
")",
"@",
"deprecated_network",
"def",
"do... | allocate a floating ip for the current tenant . | train | false |
54,278 | @snippet
def client_list_datasets(client, _):
def do_something_with(_):
pass
for dataset in client.list_datasets():
do_something_with(dataset)
| [
"@",
"snippet",
"def",
"client_list_datasets",
"(",
"client",
",",
"_",
")",
":",
"def",
"do_something_with",
"(",
"_",
")",
":",
"pass",
"for",
"dataset",
"in",
"client",
".",
"list_datasets",
"(",
")",
":",
"do_something_with",
"(",
"dataset",
")"
] | list datasets for a project . | train | false |
54,280 | def get_cpu_percentage(function, *args, **dargs):
child_pre = resource.getrusage(resource.RUSAGE_CHILDREN)
self_pre = resource.getrusage(resource.RUSAGE_SELF)
start = time.time()
to_return = function(*args, **dargs)
elapsed = (time.time() - start)
self_post = resource.getrusage(resource.RUSAGE_SELF)
child_post = resource.getrusage(resource.RUSAGE_CHILDREN)
(s_user, s_system) = [(a - b) for (a, b) in zip(self_post, self_pre)[:2]]
(c_user, c_system) = [(a - b) for (a, b) in zip(child_post, child_pre)[:2]]
cpu_percent = ((((s_user + c_user) + s_system) + c_system) / elapsed)
return (cpu_percent, to_return)
| [
"def",
"get_cpu_percentage",
"(",
"function",
",",
"*",
"args",
",",
"**",
"dargs",
")",
":",
"child_pre",
"=",
"resource",
".",
"getrusage",
"(",
"resource",
".",
"RUSAGE_CHILDREN",
")",
"self_pre",
"=",
"resource",
".",
"getrusage",
"(",
"resource",
".",
... | returns a tuple containing the cpu% and return value from function call . | train | false |
54,281 | def build_parser():
parser = optparse.OptionParser(add_help_option=False)
option_factories = (SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ)
for option_factory in option_factories:
option = option_factory()
parser.add_option(option)
def parser_exit(self, msg):
raise RequirementsFileParseError(msg)
parser.exit = parser_exit
return parser
| [
"def",
"build_parser",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"add_help_option",
"=",
"False",
")",
"option_factories",
"=",
"(",
"SUPPORTED_OPTIONS",
"+",
"SUPPORTED_OPTIONS_REQ",
")",
"for",
"option_factory",
"in",
"option_factories",
... | return a parser for parsing requirement lines . | train | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.